repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cugraph/python/cugraph-service
rapidsai_public_repos/cugraph/python/cugraph-service/server/pyproject.toml
# Copyright (c) 2022, NVIDIA CORPORATION. [build-system] requires = [ "setuptools>=61.0.0", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../../dependencies.yaml and run `rapids-dependency-file-generator`. build-backend = "setuptools.build_meta" [project] name = "cugraph-service-server" dynamic = ["version", "entry-points"] description = "cuGraph Service server" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "cudf==23.12.*", "cugraph-service-client==23.12.*", "cugraph==23.12.*", "cupy-cuda11x>=12.0.0", "dask-cuda==23.12.*", "dask-cudf==23.12.*", "numba>=0.57", "numpy>=1.21", "rapids-dask-dependency==23.12.*", "rmm==23.12.*", "thriftpy2", "ucx-py==0.35.*", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ] [project.optional-dependencies] test = [ "networkx>=2.5.1", "numpy>=1.21", "pandas", "pytest", "pytest-benchmark", "pytest-cov", "pytest-xdist", "python-louvain", "scikit-learn>=0.23.1", "scipy", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cugraph" Documentation = "https://docs.rapids.ai/api/cugraph/stable/" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "cugraph_service_server/VERSION"} [tool.setuptools.packages.find] include = [ "cugraph_service_server", "cugraph_service_server.*" ]
0
rapidsai_public_repos/cugraph/python/cugraph-service
rapidsai_public_repos/cugraph/python/cugraph-service/server/README.md
# cugraph_service ## Description [RAPIDS](https://rapids.ai) cugraph-service provides an RPC interace to a remote [RAPIDS cuGraph](https://github.com/rapidsai/cugraph) session, allowing users to perform GPU accelerated graph analytics from a remote process. cugraph-service uses cuGraph, cuDF, and other libraries on the server to execute graph data prep and analysis on server-side GPUs. Multiple clients can connect to the server allowing different users and processes the ability to access large graph data that may not otherwise be possible using the client resources. ## <div align="center"><img src="img/cugraph_service_pict.png" width="400px"/></div> ----- ### Quick start 1. Install the cugraph-service conda packages (installing the server package also installs the client): ``` conda install -c rapidsai-nightly -c rapidsai -c conda-forge -c nvidia cugraph-service-server ``` 1. Run the server (use --help to see more options) - To run on a single-GPU: ``` cugraph-service-server ``` - To run on multiple GPUs: ``` cugraph-service-server --start-local-cuda-cluster ``` 1. Use the client in your application: ``` >>> from cugraph_service_client import CugraphServiceClient >>> client = CugraphServiceClient() >>> # check connection to the server, uptime is in seconds >>> client.uptime() 28 >>> # create a graph from a CSV on the server >>> graph_id = client.create_graph() >>> client.get_graph_ids() [1] >>> client.load_csv_as_edge_data("karate.csv", dtypes=["int32", "int32", "float32"], vertex_col_names=["src", "dst"], header=0, graph_id=graph_id) >>> # check the graph info >>> client.get_graph_info(graph_id=graph_id) {'num_vertex_properties': 0, 'num_edge_properties': 1, 'is_multi_gpu': 0, 'num_edges': 156, 'num_vertices_from_vertex_data': 0, 'num_vertices': 34} >>> # run an algo >>> client.uniform_neighbor_sample(start_list=[0,12], fanout_vals=[2], graph_id=graph_id) UniformNeighborSampleResult(sources=[0, 0, 12, 12], destinations=[1, 21, 0, 3], indices=[1.0, 1.0, 1.0, 1.0]) >>> # cleanup the graph on the server >>> client.delete_graph(graph_id) >>> client.get_graph_ids() [] ``` ### Debugging #### UCX-Py related variables: `UCX_TLS` - set the transports to use, in priority order. Example: ``` UCX_TLS=tcp,cuda_copy,cuda_ipc ``` `UCX_TCP_CM_REUSEADDR` - reuse addresses. This can be used to avoid "resource in use" errors during starting/restarting the service repeatedly. ``` UCX_TCP_CM_REUSEADDR=y ``` `UCX_LOG_LEVEL` - set the level for which UCX will output messages to the console. The example below will only output "ERROR" or higher. Set to "DEBUG" to see debug and higher messages. ``` UCX_LOG_LEVEL=ERROR ``` #### UCX performance checks: Because cugraph-service uses UCX-Py for direct-to-client GPU data transfers when specified, it can be helpful to understand the various UCX performance chacks available to ensure cugraph-service is transfering results as efficiently as the system is capable of. ``` ucx_perftest -m cuda -t tag_bw -n 100 -s 16000 & ucx_perftest -m cuda -t tag_bw -n 100 -s 16000 localhost ``` ``` ucx_perftest -m cuda -t tag_bw -n 100 -s 1000000000 & ucx_perftest -m cuda -t tag_bw -n 100 -s 1000000000 localhost ``` ``` CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 100 -s 16000 & CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 100 -s 16000 localhost ``` ``` CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 100 -s 1000000000 & CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 100 -s 1000000000 localhost ``` ``` CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 1000000 -s 1000000000 & CUDA_VISIBLE_DEVICES=0,1 ucx_perftest -m cuda -t tag_bw -n 1000000 -s 1000000000 localhost ``` ### Building from source Build and install the client first, then the server. This is necessary because the server depends on shared modules provided by the client. ``` $> cd cugraph_repo/python/cugraph_service/client $> python setup.py install $> cd ../server $> python setup.py install ``` ------ ## <div align="left"><img src="img/rapids_logo.png" width="265px"/></div> Open GPU Data Science The RAPIDS suite of open source software libraries aims to enable execution of end-to-end data science and analytics pipelines entirely on GPUs. It relies on NVIDIA® CUDA® primitives for low-level compute optimization but exposing that GPU parallelism and high-bandwidth memory speed through user-friendly Python interfaces.
0
rapidsai_public_repos/cugraph/python/cugraph-service
rapidsai_public_repos/cugraph/python/cugraph-service/server/setup.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import find_packages, setup packages = find_packages(include=["cugraph_service_server*"]) setup( entry_points={ "console_scripts": [ "cugraph-service-server=cugraph_service_server.__main__:main" ], }, package_data={key: ["VERSION"] for key in packages}, )
0
rapidsai_public_repos/cugraph/python/cugraph-service
rapidsai_public_repos/cugraph/python/cugraph-service/server/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-service/server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import importlib.resources # Read VERSION file from the module that is symlinked to VERSION file # in the root of the repo at build time or copied to the moudle at # installation. VERSION is a separate file that allows CI build-time scripts # to update version info (including commit hashes) without modifying # source files. __version__ = ( importlib.resources.files("cugraph_service_server") .joinpath("VERSION") .read_text() .strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cugraph/python/cugraph-service/server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/cugraph_handler.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import cached_property from pathlib import Path import importlib import time import traceback import re from inspect import signature import asyncio import tempfile # FIXME This optional import is required to support graph creation # extensions that use OGB. It should be removed when a better # workaround is found. from cugraph.utilities.utils import import_optional import numpy as np import cupy as cp import ucp import cudf import dask_cudf import rmm from cugraph import ( batched_ego_graphs, uniform_neighbor_sample, node2vec, Graph, MultiGraph, ) from dask.distributed import Client from dask_cuda import LocalCUDACluster from dask_cuda.initialize import initialize as dask_initialize from cugraph.experimental import PropertyGraph, MGPropertyGraph from cugraph.dask.comms import comms as Comms from cugraph.dask import uniform_neighbor_sample as mg_uniform_neighbor_sample from cugraph.structure.graph_implementation.simpleDistributedGraph import ( simpleDistributedGraphImpl, ) from cugraph.dask.common.mg_utils import get_visible_devices from cugraph_service_client import defaults from cugraph_service_client import ( extension_return_dtype_map, supported_extension_return_dtypes, ) from cugraph_service_client.exceptions import CugraphServiceError from cugraph_service_client.types import ( BatchedEgoGraphsResult, Node2vecResult, UniformNeighborSampleResult, ValueWrapper, GraphVertexEdgeIDWrapper, Offsets, ) ogb = import_optional("ogb") def call_algo(sg_algo_func, G, **kwargs): """ Calls the appropriate algo function based on the graph G being MG or SG. If G is SG, sg_algo_func will be called and passed kwargs, otherwise the MG version of sg_algo_func will be called with kwargs. """ is_multi_gpu_graph = isinstance(G._Impl, simpleDistributedGraphImpl) if sg_algo_func is uniform_neighbor_sample: if is_multi_gpu_graph: possible_args = ["start_list", "fanout_vals", "with_replacement"] kwargs_to_pass = {a: kwargs[a] for a in possible_args if a in kwargs} result_ddf = mg_uniform_neighbor_sample(G, **kwargs_to_pass) # Convert DataFrame into CuPy arrays for returning to the client result_df = result_ddf.compute() sources = result_df["sources"].to_cupy() destinations = result_df["destinations"].to_cupy() indices = result_df["indices"].to_cupy() else: possible_args = [ "start_list", "fanout_vals", "with_replacement", "is_edge_ids", ] kwargs_to_pass = {a: kwargs[a] for a in possible_args if a in kwargs} result_df = uniform_neighbor_sample(G, **kwargs_to_pass) # Convert DataFrame into CuPy arrays for returning to the client sources = result_df["sources"].to_cupy() destinations = result_df["destinations"].to_cupy() indices = result_df["indices"].to_cupy() return UniformNeighborSampleResult( sources=sources, destinations=destinations, indices=indices, ) else: raise RuntimeError(f"internal error: {sg_algo_func} is not supported") class ExtensionServerFacade: """ Instances of this class are passed to server extension functions to be used to access various aspects of the cugraph_service_client server from within the extension. This provideas a means to insulate the CugraphHandler (considered here to be the "server") from direct access by end user extensions, allowing extension code to query/access the server as needed without giving extensions the ability to call potentially unsafe methods directly on the CugraphHandler. An example is using an instance of a ExtensionServerFacade to allow a Graph creation extension to query the SG/MG state the server is using in order to determine how to create a Graph instance. """ def __init__(self, cugraph_handler): self.__handler = cugraph_handler @property def is_multi_gpu(self): return self.__handler.is_multi_gpu def get_server_info(self): # The handler returns objects suitable for serialization over RPC so # convert them to regular py objs since this call is originating # server-side. return { k: ValueWrapper(v).get_py_obj() for (k, v) in self.__handler.get_server_info().items() } def get_graph_ids(self): return self.__handler.get_graph_ids() def get_graph(self, graph_id): return self.__handler._get_graph(graph_id) def add_graph(self, G): return self.__handler._add_graph(G) class CugraphHandler: """ Class which handles RPC requests for a cugraph_service server. """ # The name of the param that should be set to a ExtensionServerFacade # instance for server extension functions. __server_facade_extension_param_name = "server" def __init__(self): self.__next_graph_id = defaults.graph_id + 1 self.__graph_objs = {} self.__graph_creation_extensions = {} self.__extensions = {} self.__dask_client = None self.__dask_cluster = None self.__start_time = int(time.time()) self.__next_test_array_id = 0 self.__test_arrays = {} def __del__(self): self.shutdown_dask_client() ########################################################################### # Environment management @cached_property def is_multi_gpu(self): """ True if the CugraphHandler has multiple GPUs available via a dask cluster. """ return self.__dask_client is not None @cached_property def num_gpus(self): """ If dask is not available, this returns "1". Otherwise it returns the number of GPUs accessible through dask. """ return ( len(self.__dask_client.scheduler_info()["workers"]) if self.is_multi_gpu else 1 ) def uptime(self): """ Return the server uptime in seconds. This is often used as a "ping". """ return int(time.time()) - self.__start_time def get_server_info(self): """ Returns a dictionary of meta-data about the server. Dictionary items are string:union_objs, where union_objs are Value "unions" used for RPC serialization. """ # FIXME: expose self.__dask_client.scheduler_info() as needed return { "num_gpus": ValueWrapper(self.num_gpus).union, "extensions": ValueWrapper(list(self.__extensions.keys())).union, "graph_creation_extensions": ValueWrapper( list(self.__graph_creation_extensions.keys()) ).union, } def load_graph_creation_extensions(self, extension_dir_or_mod_path): """ Loads ("imports") all modules matching the pattern '_extension.py' in the directory specified by extension_dir_or_mod_path. extension_dir_or_mod_path can be either a path to a directory on disk, or a python import path to a package. The modules are searched and their functions are called (if a match is found) when call_graph_creation_extension() is called. The extensions loaded are to be used for graph creation, and the server assumes the return value of the extension functions is a Graph-like object which is registered and assigned a unique graph ID. """ modules_loaded = [] try: extension_files = self.__get_extension_files_from_path( extension_dir_or_mod_path ) for ext_file in extension_files: module_file_path = ext_file.absolute().as_posix() spec = importlib.util.spec_from_file_location( module_file_path, ext_file ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) self.__graph_creation_extensions[module_file_path] = module modules_loaded.append(module_file_path) return modules_loaded except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def load_extensions(self, extension_dir_or_mod_path): """ Loads ("imports") all modules matching the pattern _extension.py in the directory specified by extension_dir_or_mod_path. extension_dir_or_mod_path can be either a path to a directory on disk, or a python import path to a package. The modules are searched and their functions are called (if a match is found) when call_graph_creation_extension() is called. """ modules_loaded = [] try: extension_files = self.__get_extension_files_from_path( extension_dir_or_mod_path ) for ext_file in extension_files: module_file_path = ext_file.absolute().as_posix() spec = importlib.util.spec_from_file_location( module_file_path, ext_file ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) self.__extensions[module_file_path] = module modules_loaded.append(module_file_path) return modules_loaded except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def unload_extension_module(self, modname): """ Removes all extension functions in modname. """ if (self.__graph_creation_extensions.pop(modname, None) is None) and ( self.__extensions.pop(modname, None) is None ): raise CugraphServiceError(f"bad extension module {modname}") def call_graph_creation_extension( self, func_name, func_args_repr, func_kwargs_repr ): """ Calls the graph creation extension function func_name and passes it the eval'd func_args_repr and func_kwargs_repr objects. If successful, it associates the graph returned by the extension function with a new graph ID and returns it. func_name cannot be a private name (name starting with __). """ graph_obj = self.__call_extension( self.__graph_creation_extensions, func_name, func_args_repr, func_kwargs_repr, ) # FIXME: ensure graph_obj is a graph obj return self._add_graph(graph_obj) def call_extension( self, func_name, func_args_repr, func_kwargs_repr, result_host=None, result_port=None, ): """ Calls the extension function func_name and passes it the eval'd func_args_repr and func_kwargs_repr objects. If successful, returns a Value object containing the results returned by the extension function. func_name cannot be a private name (name starting with __). """ try: result = self.__call_extension( self.__extensions, func_name, func_args_repr, func_kwargs_repr ) if self.__check_host_port_args(result_host, result_port): # Ensure result is in list format for calling __ucx_send_results so it # sends the contents as individual arrays. if isinstance(result, (list, tuple)): result_list = result else: result_list = [result] # Form the meta-data array to send first. This array contains uint8 # values which map to dtypes the client uses when converting bytes to # values. meta_data = [] for r in result_list: if hasattr(r, "dtype"): dtype_str = str(r.dtype) else: dtype_str = type(r).__name__ dtype_enum_val = extension_return_dtype_map.get(dtype_str) if dtype_enum_val is None: raise TypeError( f"extension {func_name} returned an invalid type " f"{dtype_str}, only " f"{supported_extension_return_dtypes} are supported" ) meta_data.append(dtype_enum_val) # FIXME: meta_data should not need to be a cupy array meta_data = cp.array(meta_data, dtype="uint8") asyncio.run( self.__ucx_send_results( result_host, result_port, meta_data, *result_list, ) ) # FIXME: Thrift still expects something of the expected type to # be returned to be serialized and sent. Look into a separate # API that uses the Thrift "oneway" modifier when returning # results via client device. return ValueWrapper(None) else: return ValueWrapper(result) except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def initialize_dask_client( self, protocol=None, rmm_pool_size=None, dask_worker_devices=None, dask_scheduler_file=None, ): """ Initialize a dask client to be used for MG operations. """ if dask_scheduler_file is not None: dask_initialize() self.__dask_client = Client(scheduler_file=dask_scheduler_file) else: # The tempdir created by tempdir_object should be cleaned up once # tempdir_object goes out-of-scope and is deleted. tempdir_object = tempfile.TemporaryDirectory() cluster = LocalCUDACluster( local_directory=tempdir_object.name, protocol=protocol, rmm_pool_size=rmm_pool_size, CUDA_VISIBLE_DEVICES=dask_worker_devices, ) # Initialize the client to use RMM pool allocator if cluster is # using it. if rmm_pool_size is not None: rmm.reinitialize(pool_allocator=True) self.__dask_client = Client(cluster) if dask_worker_devices is not None: # FIXME: this assumes a properly formatted string with commas num_workers = len(dask_worker_devices.split(",")) else: num_workers = len(get_visible_devices()) self.__dask_client.wait_for_workers(num_workers) if not Comms.is_initialized(): Comms.initialize(p2p=True) def shutdown_dask_client(self): """ Shutdown/cleanup the dask client for this handler instance. """ if self.__dask_client is not None: Comms.destroy() self.__dask_client.close() if self.__dask_cluster is not None: self.__dask_cluster.close() self.__dask_cluster = None self.__dask_client = None ########################################################################### # Graph management def create_graph(self): """ Create a new graph associated with a new unique graph ID, return the new graph ID. """ pG = self.__create_graph() return self._add_graph(pG) def delete_graph(self, graph_id): """ Remove the graph identified by graph_id from the server. """ dG = self.__graph_objs.pop(graph_id, None) if dG is None: raise CugraphServiceError(f"invalid graph_id {graph_id}") del dG print(f"deleted graph with id {graph_id}") def get_graph_ids(self): """ Returns a list of the graph IDs currently in use. """ return list(self.__graph_objs.keys()) def get_graph_info(self, keys, graph_id): """ Returns a dictionary of meta-data about the graph identified by graph_id. If keys passed, only returns the values in keys. Dictionary items are string:union_objs, where union_objs are Value "unions" used for RPC serialization. """ valid_keys = set( [ "num_vertices", "num_vertices_from_vertex_data", "num_edges", "num_vertex_properties", "num_edge_properties", "is_multi_gpu", ] ) if len(keys) == 0: keys = valid_keys else: invalid_keys = set(keys) - valid_keys if len(invalid_keys) != 0: raise CugraphServiceError(f"got invalid keys: {invalid_keys}") G = self._get_graph(graph_id) info = {} try: if isinstance(G, (PropertyGraph, MGPropertyGraph)): for k in keys: if k == "num_vertices": info[k] = G.get_num_vertices() elif k == "num_vertices_from_vertex_data": info[k] = G.get_num_vertices(include_edge_data=False) elif k == "num_edges": info[k] = G.get_num_edges() elif k == "num_vertex_properties": info[k] = len(G.vertex_property_names) elif k == "num_edge_properties": info[k] = len(G.edge_property_names) elif k == "is_multi_gpu": info[k] = isinstance(G, MGPropertyGraph) else: for k in keys: if k == "num_vertices": info[k] = G.number_of_vertices() elif k == "num_vertices_from_vertex_data": info[k] = 0 elif k == "num_edges": info[k] = G.number_of_edges() elif k == "num_vertex_properties": info[k] = 0 elif k == "num_edge_properties": info[k] = 0 elif k == "is_multi_gpu": info[k] = G.is_multi_gpu() except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") return {key: ValueWrapper(value) for (key, value) in info.items()} def load_csv_as_vertex_data( self, csv_file_name, delimiter, dtypes, header, vertex_col_name, type_name, property_columns, graph_id, names, ): """ Given a CSV csv_file_name present on the server's file system, read it and apply it as edge data to the graph specified by graph_id, or the default graph if not specified. """ pG = self._get_graph(graph_id) if header == -1: header = "infer" elif header == -2: header = None if len(names) == 0: names = None # FIXME: error check that file exists # FIXME: error check that edgelist was read correctly try: gdf = self.__get_dataframe_from_csv( csv_file_name, delimiter=delimiter, dtypes=dtypes, header=header, names=names, ) pG.add_vertex_data( gdf, type_name=type_name, vertex_col_name=vertex_col_name, property_columns=property_columns, ) except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def load_csv_as_edge_data( self, csv_file_name, delimiter, dtypes, header, vertex_col_names, type_name, property_columns, graph_id, names, edge_id_col_name, ): """ Given a CSV csv_file_name present on the server's file system, read it and apply it as vertex data to the graph specified by graph_id, or the default graph if not specified. """ pG = self._get_graph(graph_id) # FIXME: error check that file exists # FIXME: error check that edgelist read correctly if header == -1: header = "infer" elif header == -2: header = None if len(names) == 0: names = None if edge_id_col_name == "": edge_id_col_name = None try: gdf = self.__get_dataframe_from_csv( csv_file_name, delimiter=delimiter, dtypes=dtypes, header=header, names=names, ) pG.add_edge_data( gdf, type_name=type_name, vertex_col_names=vertex_col_names, property_columns=property_columns, edge_id_col_name=edge_id_col_name, ) except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") # FIXME: ensure edge IDs can also be filtered by edge type # See: https://github.com/rapidsai/cugraph/issues/2655 def get_edge_IDs_for_vertices(self, src_vert_IDs, dst_vert_IDs, graph_id): """ Return a list of edge IDs corresponding to the vertex IDs in each of src_vert_IDs and dst_vert_IDs that, when combined, define an edge in the graph associated with graph_id. For example, if src_vert_IDs is [0, 1, 2] and dst_vert_IDs is [7, 8, 9] return the edge IDs for edges (0, 7), (1, 8), and (2, 9). graph_id must be associated with a Graph extracted from a PropertyGraph (MG or SG). """ G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): raise CugraphServiceError( "get_edge_IDs_for_vertices() only " "accepts an extracted subgraph ID, got " f"an ID for a {type(G)}." ) return self.__get_edge_IDs_from_graph_edge_data(G, src_vert_IDs, dst_vert_IDs) def renumber_vertices_by_type(self, prev_id_column: str, graph_id: int) -> Offsets: G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): if prev_id_column == "": prev_id_column = None offset_df = G.renumber_vertices_by_type(prev_id_column=prev_id_column) if self.is_multi_gpu: offset_df = offset_df.compute() # type needs be converted twice due to cudf bug offsets_obj = Offsets( type=offset_df.index.values_host.to_numpy(), start=offset_df.start.to_numpy(), stop=offset_df.stop.to_numpy(), ) return offsets_obj else: raise CugraphServiceError( "Renumbering graphs without properties is currently unsupported" ) def renumber_edges_by_type(self, prev_id_column: str, graph_id: int) -> Offsets: G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): if prev_id_column == "": prev_id_column = None offset_df = G.renumber_edges_by_type(prev_id_column=prev_id_column) if self.is_multi_gpu: offset_df = offset_df.compute() # type needs be converted twice due to cudf bug offsets_obj = Offsets( type=offset_df.index.values_host.to_numpy(), start=offset_df.start.to_numpy(), stop=offset_df.stop.to_numpy(), ) return offsets_obj else: raise CugraphServiceError( "Renumbering graphs without properties is currently unsupported" ) def extract_subgraph( self, create_using, selection, edge_weight_property, default_edge_weight, check_multi_edges, renumber_graph, add_edge_data, graph_id, ): """ Extract a subgraph, return a new graph ID """ pG = self._get_graph(graph_id) if not (isinstance(pG, (PropertyGraph, MGPropertyGraph))): raise CugraphServiceError( "extract_subgraph() can only be called " "on a graph with properties." ) # Convert defaults needed for the RPC API into defaults used by # PropertyGraph.extract_subgraph() try: if create_using == "": create_using = None elif create_using is not None: create_using = self.__parse_create_using_string(create_using) edge_weight_property = edge_weight_property or None if selection == "": selection = None elif selection is not None: selection = pG.select_edges(selection) # FIXME: create_using and selection should not be strings at this point G = pG.extract_subgraph( create_using=create_using, selection=selection, edge_weight_property=edge_weight_property, default_edge_weight=default_edge_weight, check_multi_edges=check_multi_edges, renumber_graph=renumber_graph, add_edge_data=add_edge_data, ) except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") return self._add_graph(G) def get_graph_vertex_data( self, id_or_ids, null_replacement_value, property_keys, types, graph_id ): """ Returns the vertex data as a serialized numpy array for the given id_or_ids. null_replacement_value must be provided if the data contains NA values, since NA values cannot be serialized. If the graph is a structural graph (a graph without properties), this method does not accept the id_or_ids, property_keys, or types arguments, and instead returns a list of valid vertex ids. """ G = self._get_graph(graph_id) ids = GraphVertexEdgeIDWrapper(id_or_ids).get_py_obj() null_replacement_value = ValueWrapper(null_replacement_value).get_py_obj() if ids == -1: ids = None elif not isinstance(ids, list): ids = [ids] if property_keys == []: columns = None else: columns = property_keys if types == []: types = None if isinstance(G, (PropertyGraph, MGPropertyGraph)): if columns is not None and G.vertex_col_name in columns: raise CugraphServiceError( f"ID key {G.vertex_col_name} is not allowed for property query. " f"Vertex IDs are always returned in query." ) try: df = G.get_vertex_data(vertex_ids=ids, columns=columns, types=types) if isinstance(df, dask_cudf.DataFrame): df = df.compute() except KeyError: df = None else: if (columns is not None) or (ids is not None) or (types is not None): raise CugraphServiceError("Graph does not contain properties") if self.is_multi_gpu: # FIXME may run out of memory for very lage graphs. s = ( dask_cudf.concat( [ G.edgelist.edgelist_df[ G.renumber_map.renumbered_src_col_name ], G.edgelist.edgelist_df[ G.renumber_map.renumbered_dst_col_name ], ] ) .unique() .compute() ) df = cudf.DataFrame() df["id"] = s df = dask_cudf.from_cudf(df, npartitions=self.num_gpus) else: s = cudf.concat( [ G.edgelist.edgelist_df[G.srcCol], G.edgelist.edgelist_df[G.dstCol], ] ).unique() df = cudf.DataFrame() df["id"] = s if G.is_renumbered(): df = G.unrenumber(df, "id", preserve_order=True) return self.__get_graph_data_as_numpy_bytes(df, null_replacement_value) def get_graph_edge_data( self, id_or_ids, null_replacement_value, property_keys, types, graph_id ): """ Returns the edge data as a serialized numpy array for the given id_or_ids. null_replacement_value must be provided if the data contains NA values, since NA values cannot be serialized. """ G = self._get_graph(graph_id) ids = GraphVertexEdgeIDWrapper(id_or_ids).get_py_obj() if ids == -1: ids = None elif not isinstance(ids, list): ids = [ids] if property_keys == []: columns = None else: columns = property_keys if types == []: types = None if isinstance(G, (PropertyGraph, MGPropertyGraph)): try: df = G.get_edge_data(edge_ids=ids, columns=columns, types=types) except KeyError: df = None else: if columns is not None: raise CugraphServiceError( f"Graph does not contain properties. {columns}" ) # Get the edgelist; API expects edge id, src, dst, type df = G.edgelist.edgelist_df if G.edgeIdCol in df.columns: if ids is not None: if self.is_multi_gpu: # FIXME use ids = cudf.Series(ids) after dask_cudf fix ids = np.array(ids) df = df.reindex(df[G.edgeIdCol]).loc[ids] else: ids = cudf.Series(ids) df = df.reindex(df[G.edgeIdCol]).loc[ids] else: if ids is not None: raise CugraphServiceError("Graph does not have edge ids") df[G.edgeIdCol] = df.index if G.edgeTypeCol in df.columns: if types is not None: df = df[df[G.edgeTypeCol].isin(types)] else: if types is not None: raise CugraphServiceError("Graph does not have typed edges") df[G.edgeTypeCol] = "" src_col_name = ( G.renumber_map.renumbered_src_col_name if self.is_multi_gpu else G.srcCol ) dst_col_name = ( G.renumber_map.renumbered_dst_col_name if self.is_multi_gpu else G.dstCol ) if G.is_renumbered(): df = G.unrenumber(df, src_col_name, preserve_order=True) df = G.unrenumber(df, dst_col_name, preserve_order=True) df = df[[G.edgeIdCol, src_col_name, dst_col_name, G.edgeTypeCol]] if isinstance(df, dask_cudf.DataFrame): df = df.compute() return self.__get_graph_data_as_numpy_bytes(df, null_replacement_value) def is_vertex_property(self, property_key, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return property_key in G.vertex_property_names raise CugraphServiceError("Graph does not contain properties") def is_edge_property(self, property_key, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return property_key in G.edge_property_names raise CugraphServiceError("Graph does not contain properties") def get_graph_vertex_property_names(self, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return G.vertex_property_names return [] def get_graph_edge_property_names(self, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return G.edge_property_names return [] def get_graph_vertex_types(self, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return G.vertex_types else: return [""] def get_graph_edge_types(self, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): return G.edge_types else: # FIXME should call G.vertex_types (See issue #2889) if G.edgeTypeCol in G.edgelist.edgelist_df.columns: return ( G.edgelist.edgelist_df[G.edgeTypeCol] .unique() .astype("str") .values_host ) else: return [""] def get_num_vertices(self, vertex_type, include_edge_data, graph_id): # FIXME should include_edge_data always be True in the remote case? G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): if vertex_type == "": return G.get_num_vertices(include_edge_data=include_edge_data) else: return G.get_num_vertices( type=vertex_type, include_edge_data=include_edge_data ) else: if vertex_type != "": raise CugraphServiceError("Graph does not support vertex types") return G.number_of_vertices() def get_num_edges(self, edge_type, graph_id): G = self._get_graph(graph_id) if isinstance(G, (PropertyGraph, MGPropertyGraph)): if edge_type == "": return G.get_num_edges() else: return G.get_num_edges(type=edge_type) else: if edge_type == "": return G.number_of_edges() else: # FIXME Issue #2899, call get_num_edges() instead. mask = G.edgelist.edgelist_df[G.edgeTypeCol] == edge_type return G.edgelist.edgelist_df[mask].count() # FIXME this should be valid for a graph without properties ########################################################################### # Algos def batched_ego_graphs(self, seeds, radius, graph_id): """ """ # FIXME: finish docstring above # FIXME: exception handling G = self._get_graph(graph_id) # FIXME: write test to catch an MGPropertyGraph being passed in if isinstance(G, PropertyGraph): raise CugraphServiceError( "batched_ego_graphs() cannot operate " "directly on a graph with properties, " "call extract_subgraph() then call " "batched_ego_graphs() on the extracted " "subgraph instead." ) try: # FIXME: update this to use call_algo() # FIXME: this should not be needed, need to update # cugraph.batched_ego_graphs to also accept a list seeds = cudf.Series(seeds, dtype="int32") (ego_edge_list, seeds_offsets) = batched_ego_graphs(G, seeds, radius) # batched_ego_graphs_result = BatchedEgoGraphsResult( # src_verts=ego_edge_list["src"].values_host.tobytes(), #i32 # dst_verts=ego_edge_list["dst"].values_host.tobytes(), #i32 # edge_weights=ego_edge_list["weight"].values_host.tobytes(), # #f64 # seeds_offsets=seeds_offsets.values_host.tobytes() #i64 # ) batched_ego_graphs_result = BatchedEgoGraphsResult( src_verts=ego_edge_list["src"].values_host, dst_verts=ego_edge_list["dst"].values_host, edge_weights=ego_edge_list["weight"].values_host, seeds_offsets=seeds_offsets.values_host, ) return batched_ego_graphs_result except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") return batched_ego_graphs_result def node2vec(self, start_vertices, max_depth, graph_id): """ """ # FIXME: finish docstring above # FIXME: exception handling G = self._get_graph(graph_id) # FIXME: write test to catch an MGPropertyGraph being passed in if isinstance(G, PropertyGraph): raise CugraphServiceError( "node2vec() cannot operate directly on " "a graph with properties, call " "extract_subgraph() then call " "node2vec() on the extracted subgraph " "instead." ) try: # FIXME: update this to use call_algo() # FIXME: this should not be needed, need to update cugraph.node2vec # to also accept a list start_vertices = cudf.Series(start_vertices, dtype="int32") (paths, weights, path_sizes) = node2vec(G, start_vertices, max_depth) node2vec_result = Node2vecResult( vertex_paths=paths.values_host, edge_weights=weights.values_host, path_sizes=path_sizes.values_host, ) except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") return node2vec_result def uniform_neighbor_sample( self, start_list, fanout_vals, with_replacement, graph_id, result_host, result_port, ): print("SERVER: running uns", flush=True) try: G = self._get_graph(graph_id) if isinstance(G, (MGPropertyGraph, PropertyGraph)): # Implicitly extract a subgraph containing the entire multigraph. # G will be garbage collected when this function returns. G = G.extract_subgraph( create_using=MultiGraph(directed=True), default_edge_weight=1.0, ) print("SERVER: starting sampling...") st = time.perf_counter_ns() uns_result = call_algo( uniform_neighbor_sample, G, start_list=start_list, fanout_vals=fanout_vals, with_replacement=with_replacement, ) print( f"SERVER: done sampling, took {((time.perf_counter_ns() - st) / 1e9)}s" ) if self.__check_host_port_args(result_host, result_port): print("SERVER: calling ucx_send_results...") st = time.perf_counter_ns() asyncio.run( self.__ucx_send_results( result_host, result_port, uns_result.sources, uns_result.destinations, uns_result.indices, ) ) print( "SERVER: done ucx_send_results, took " f"{((time.perf_counter_ns() - st) / 1e9)}s" ) # FIXME: Thrift still expects something of the expected type to # be returned to be serialized and sent. Look into a separate # API that uses the Thrift "oneway" modifier when returning # results via client device. return UniformNeighborSampleResult() else: uns_result.sources = cp.asnumpy(uns_result.sources) uns_result.destinations = cp.asnumpy(uns_result.destinations) uns_result.indices = cp.asnumpy(uns_result.indices) return uns_result except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def pagerank(self, graph_id): """ """ raise NotImplementedError ########################################################################### # Test/Debug APIs def create_test_array(self, nbytes): """ Creates an array of bytes (int8 values set to 1) and returns an ID to use to reference the array in later test calls. The test array must be deleted by calling delete_test_array(). """ aid = self.__next_test_array_id self.__test_arrays[aid] = cp.ones(nbytes, dtype="int8") self.__next_test_array_id += 1 return aid def delete_test_array(self, test_array_id): """ Deletes the test array identified by test_array_id. """ a = self.__test_arrays.pop(test_array_id, None) if a is None: raise CugraphServiceError(f"invalid test_array_id {test_array_id}") del a def receive_test_array(self, test_array_id): """ Returns the test array identified by test_array_id to the client. This can be used to verify transfer speeds from server to client are performing as expected. """ return self.__test_arrays[test_array_id] def receive_test_array_to_device(self, test_array_id, result_host, result_port): """ Returns the test array identified by test_array_id to the client via UCX-Py listening on result_host/result_port. This can be used to verify transfer speeds from server to client are performing as expected. """ asyncio.run( self.__ucx_send_results( result_host, result_port, self.__test_arrays[test_array_id] ) ) def get_graph_type(self, graph_id): """ Returns a string repr of the graph type associated with graph_id. """ return repr(type(self._get_graph(graph_id))) ########################################################################### # "Protected" interface - used for both implementation and test/debug. Will # not be exposed to a cugraph_service client, but will be used by extensions # via the ExtensionServerFacade. def _add_graph(self, G): """ Create a new graph ID for G and add G to the internal mapping of graph ID:graph instance. """ gid = self.__next_graph_id self.__graph_objs[gid] = G self.__next_graph_id += 1 return gid def _get_graph(self, graph_id): """ Return the cuGraph Graph object associated with graph_id. If the graph_id is the default graph ID and the default graph has not been created, then instantiate a new PropertyGraph as the default graph and return it. """ pG = self.__graph_objs.get(graph_id) # Always create the default graph if it does not exist if pG is None: if graph_id == defaults.graph_id: pG = self.__create_graph() self.__graph_objs[graph_id] = pG else: raise CugraphServiceError(f"invalid graph_id {graph_id}") return pG ########################################################################### # Private def __parse_create_using_string(self, create_using): match = re.match(r"([MultiGraph|Graph]+)(\(.*\))?", create_using) if match is None: raise TypeError(f"Invalid graph type {create_using}") else: graph_type, args = match.groups() args_dict = {} if args is not None and args != "" and args != "()": for arg in args[1:-1].replace(" ", "").split(","): try: k, v = arg.split("=") if v == "True": args_dict[k] = True elif v == "False": args_dict[k] = False else: raise ValueError(f"Could not parse value {v}") except Exception as e: raise ValueError(f"Could not parse argument {arg}", e) if graph_type == "Graph": graph_type = Graph else: graph_type = MultiGraph return graph_type(**args_dict) @staticmethod def __check_host_port_args(result_host, result_port): """ Return True if host and port are set correctly, False if not set, and raise ValueError if set incorrectly. """ if (result_host is not None) or (result_port is not None): if (result_host is None) or (result_port is None): raise ValueError( "both result_host and result_port must be set if either is set. " f"Got: {result_host=}, {result_port=}" ) return True return False @staticmethod def __get_extension_files_from_path(extension_dir_or_mod_path): extension_path = Path(extension_dir_or_mod_path) # extension_dir_path is either a path on disk or an importable module path # (eg. import foo.bar.module) if (not extension_path.exists()) or (not extension_path.is_dir()): try: mod = importlib.import_module(str(extension_path)) except ModuleNotFoundError: raise CugraphServiceError(f"bad path: {extension_dir_or_mod_path}") mod_file_path = Path(mod.__file__).absolute() # If mod is a package, find all the .py files in it if mod_file_path.name == "__init__.py": extension_files = mod_file_path.parent.glob("*.py") else: extension_files = [mod_file_path] else: extension_files = extension_path.glob("*_extension.py") return extension_files async def __ucx_send_results(self, result_host, result_port, *results): # The cugraph_service_client should have set up a UCX listener waiting # for the result. Create an endpoint, send results, and close. ep = await ucp.create_endpoint(result_host, result_port) for r in results: await ep.send_obj(r) await ep.close() def __get_dataframe_from_csv(self, csv_file_name, delimiter, dtypes, header, names): """ Read a CSV into a DataFrame and return it. This will use either a cuDF DataFrame or a dask_cudf DataFrame based on if the handler is configured to use a dask cluster or not. """ gdf = cudf.read_csv( csv_file_name, delimiter=delimiter, dtype=dtypes, header=header, names=names ) if self.is_multi_gpu: return dask_cudf.from_cudf(gdf, npartitions=self.num_gpus) return gdf def __create_graph(self): """ Instantiate a graph object using a type appropriate for the handler ( either SG or MG) """ return MGPropertyGraph() if self.is_multi_gpu else PropertyGraph() # FIXME: consider adding this to PropertyGraph def __remove_internal_columns(self, pg_column_names): """ Removes all column names from pg_column_names that are "internal" (ie. used for PropertyGraph bookkeeping purposes only) """ internal_column_names = [ PropertyGraph.vertex_col_name, PropertyGraph.src_col_name, PropertyGraph.dst_col_name, PropertyGraph.type_col_name, PropertyGraph.edge_id_col_name, PropertyGraph.vertex_id_col_name, PropertyGraph.weight_col_name, ] # Create a list of user-visible columns by removing the internals while # preserving order user_visible_column_names = list(pg_column_names) for internal_column_name in internal_column_names: if internal_column_name in user_visible_column_names: user_visible_column_names.remove(internal_column_name) return user_visible_column_names # FIXME: consider adding this to PropertyGraph def __get_edge_IDs_from_graph_edge_data(self, G, src_vert_IDs, dst_vert_IDs): """ Return a list of edge IDs corresponding to the vertex IDs in each of src_vert_IDs and dst_vert_IDs that, when combined, define an edge in G. For example, if src_vert_IDs is [0, 1, 2] and dst_vert_IDs is [7, 8, 9] return the edge IDs for edges (0, 7), (1, 8), and (2, 9). G must have an "edge_data" attribute. """ edge_IDs = [] num_edges = len(src_vert_IDs) for i in range(num_edges): src_mask = G.edge_data[PropertyGraph.src_col_name] == src_vert_IDs[i] dst_mask = G.edge_data[PropertyGraph.dst_col_name] == dst_vert_IDs[i] value = G.edge_data[src_mask & dst_mask][PropertyGraph.edge_id_col_name] # FIXME: This will compute the result (if using dask) then transfer # to host memory for each iteration - is there a more efficient # way? if self.is_multi_gpu: value = value.compute() edge_IDs.append(value.values_host[0]) return edge_IDs def __get_graph_data_as_numpy_bytes(self, dataframe, null_replacement_value): """ Returns a byte array repr of the vertex or edge graph data. Since the byte array cannot represent NA values, null_replacement_value must be provided to be used in place of NAs. """ try: if dataframe is None: return np.ndarray(shape=(0, 0)).dumps() # null_replacement_value is a Value "union" n = ValueWrapper(null_replacement_value).get_py_obj() # This needs to be a copy of the df data to replace NA values # FIXME: should something other than a numpy type be serialized to # prevent a copy? (note: any other type required to be de-serialzed # on the client end could add dependencies on the client) df_numpy = dataframe.to_numpy(na_value=n) return df_numpy.dumps() except Exception: raise CugraphServiceError(f"{traceback.format_exc()}") def __call_extension( self, extension_dict, func_name, func_args_repr, func_kwargs_repr ): """ Calls the extension function func_name and passes it the eval'd func_args_repr and func_kwargs_repr objects. If successful, returns a Value object containing the results returned by the extension function. The arg/kwarg reprs are eval'd prior to calling in order to pass actual python objects to func_name (this is needed to allow arbitrary arg objects to be serialized as part of the RPC call from the client). func_name cannot be a private name (name starting with __). All loaded extension modules are checked when searching for func_name, and the first extension module that contains it will have its function called. """ if func_name.startswith("__"): raise CugraphServiceError(f"Cannot call private function {func_name}") for module in extension_dict.values(): func = getattr(module, func_name, None) if func is not None: # FIXME: look for a way to do this without using eval() func_args = eval(func_args_repr) func_kwargs = eval(func_kwargs_repr) func_sig = signature(func) func_params = list(func_sig.parameters.keys()) facade_param = self.__server_facade_extension_param_name # Graph creation extensions that have the last arg named # self.__server_facade_extension_param_name are passed a # ExtensionServerFacade instance to allow them to query the # "server" in a safe way, if needed. if facade_param in func_params: if func_params[-1] == facade_param: func_kwargs[facade_param] = ExtensionServerFacade(self) else: raise CugraphServiceError( f"{facade_param}, if specified, must be the last param." ) try: return func(*func_args, **func_kwargs) except Exception: # FIXME: raise a more detailed error raise CugraphServiceError( f"error running {func_name} : {traceback.format_exc()}" ) raise CugraphServiceError(f"extension {func_name} was not found")
0
rapidsai_public_repos/cugraph/python/cugraph-service/server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cugraph_service_client import defaults from cugraph_service_client.cugraph_service_thrift import create_server from cugraph_service_server.cugraph_handler import CugraphHandler def start_server_blocking( graph_creation_extension_dir=None, start_local_cuda_cluster=False, dask_scheduler_file=None, host=defaults.host, port=defaults.port, protocol=None, rmm_pool_size=None, dask_worker_devices=None, console_message="", ): """ Start the cugraph_service server on host/port, with graph creation extensions in graph_creation_extension_dir preloaded if specified, and a dask client initialized based on dask_scheduler_file if specified (if not specified, server runs in SG mode). If console_message is specified, the string is printed just after the handler is created and before the server starts listening for connections. This call blocks indefinitely until Ctrl-C. """ handler = CugraphHandler() if start_local_cuda_cluster and (dask_scheduler_file is not None): raise ValueError( "dask_scheduler_file cannot be set if start_local_cuda_cluster is True" ) if graph_creation_extension_dir is not None: handler.load_graph_creation_extensions(graph_creation_extension_dir) if dask_scheduler_file is not None: handler.initialize_dask_client(dask_scheduler_file=dask_scheduler_file) elif start_local_cuda_cluster: handler.initialize_dask_client( protocol=protocol, rmm_pool_size=rmm_pool_size, dask_worker_devices=dask_worker_devices, ) if console_message != "": print(console_message, flush=True) server = create_server(handler, host=host, port=port) server.serve() # blocks until Ctrl-C (kill -2) from cugraph_service_server._version import __git_commit__, __version__
0
rapidsai_public_repos/cugraph/python/cugraph-service/server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/__main__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from pathlib import Path from cugraph_service_server import ( defaults, start_server_blocking, ) def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument( "--host", type=str, default=defaults.host, help="hostname the server should use, default is " f"{defaults.host}", ) arg_parser.add_argument( "--port", type=int, default=defaults.port, help="port the server should listen on, default " f"is {defaults.port}", ) arg_parser.add_argument( "--graph-creation-extension-dir", type=Path, help="dir to load graph creation extension " "functions from", ) arg_parser.add_argument( "--dask-scheduler-file", type=Path, help="file generated by a dask scheduler, used " "for connecting to a dask cluster for MG support", ) arg_parser.add_argument( "--start-local-cuda-cluster", action="store_true", help="use a LocalCUDACluster for multi-GPU", ) arg_parser.add_argument( "--protocol", type=str, help="protocol to use by the dask cluster, ex 'ucx'", ) arg_parser.add_argument( "--rmm-pool-size", type=str, help="RMM pool size, ex. '28GB'", ) arg_parser.add_argument( "--dask-worker-devices", type=str, help="list of GPU device IDs the dask cluster should use, ex. '0,1,2,3'", ) args = arg_parser.parse_args() msg = "Starting the cugraph_service server " if (args.dask_scheduler_file is None) and (args.start_local_cuda_cluster is False): msg += "(single-GPU)..." elif (args.dask_scheduler_file is not None) and ( args.start_local_cuda_cluster is True ): raise RuntimeError( "dask-scheduler-file cannot be set if start-local-cuda-cluster is specified" ) elif args.dask_scheduler_file is not None: msg += f"(multi-GPU, scheduler file: {args.dask_scheduler_file})..." elif args.start_local_cuda_cluster is True: msg += "(multi-GPU, LocalCUDACluster)..." start_server_blocking( args.graph_creation_extension_dir, args.start_local_cuda_cluster, args.dask_scheduler_file, args.host, args.port, args.protocol, args.rmm_pool_size, args.dask_worker_devices, console_message=msg, ) print("done.") if __name__ == "__main__": main()
0
rapidsai_public_repos/cugraph/python/cugraph-service/server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/VERSION
23.12.00
0
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/testing/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/testing/utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import subprocess import time from tempfile import TemporaryDirectory from pathlib import Path from cugraph_service_client import ( CugraphServiceClient, defaults, ) from cugraph_service_client.exceptions import CugraphServiceError def create_tmp_extension_dir(file_contents, file_name="my_extension.py"): """ Create and return a temporary dir to be used as a dir containing extensions to be read by a cugraph_service server. file_contents is a string containing the contents of the extension file to write out. """ tmp_extension_dir = TemporaryDirectory() graph_creation_extension_file = open(Path(tmp_extension_dir.name) / file_name, "w") print(file_contents, file=graph_creation_extension_file, flush=True) return tmp_extension_dir _failed_subproc_err_msg = ( f"\n{'*' * 21} cugraph-service-server STDOUT/STDERR {'*' * 22}\n" "%s" f"{'*' * 80}\n" ) def start_server_subprocess( host=defaults.host, port=defaults.port, graph_creation_extension_dir=None, start_local_cuda_cluster=False, dask_scheduler_file=None, env_additions=None, ): """ Start a cugraph_service server as a subprocess. Returns the Popen object for the server. """ server_process = None env_dict = os.environ.copy() if env_additions is not None: env_dict.update(env_additions) # pytest will update sys.path based on the tests it discovers and optional # settings in pytest.ini. Make sure any path settings are passed on the the # server so modules are properly found. env_dict["PYTHONPATH"] = ":".join(sys.path) # special case: some projects organize their tests/benchmarks by package # name, such as "cugraph". Unfortunately, these can collide with installed # package names since python will treat them as a namespace package if this # is run from a directory with a "cugraph" or similar subdir. Simply change # to a temp dir prior to running the server to avoid collisions. tempdir_object = TemporaryDirectory() args = [ sys.executable, "-m", "cugraph_service_server", "--host", host, "--port", str(port), ] if graph_creation_extension_dir is not None: args += [ "--graph-creation-extension-dir", graph_creation_extension_dir, ] if dask_scheduler_file is not None: args += [ "--dask-scheduler-file", dask_scheduler_file, ] if start_local_cuda_cluster: args += ["--start-local-cuda-cluster"] try: print( f"Starting server subprocess using:\n\"{' '.join(args)}\"\n", flush=True, ) server_process = subprocess.Popen( args, env=env_dict, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=tempdir_object.name, ) # Attach tempdir_object to server_process so it is not deleted and # removed when it goes out of scope. Instead, it should get deleted # when server_process is GC'd server_process.tempdir = tempdir_object print( "Launched cugraph_service server, waiting for it to start...", end="", flush=True, ) client = CugraphServiceClient(host, port) max_retries = 60 retries = 0 while retries < max_retries: try: client.uptime() print("started.") break except CugraphServiceError: time.sleep(1) retries += 1 # poll() returns exit code, or None if still running if (server_process is not None) and (server_process.poll() is not None): err_output = _failed_subproc_err_msg % server_process.stdout.read() server_process = None raise RuntimeError(f"error starting server: {err_output}") if retries >= max_retries: raise RuntimeError("timed out waiting for server to respond") except Exception: # Stop the server if still running if server_process is not None: if server_process.poll() is None: server_process.terminate() server_process.wait(timeout=60) print(_failed_subproc_err_msg % server_process.stdout.read()) raise return server_process def ensure_running_server( host=defaults.host, port=defaults.port, dask_scheduler_file=None, start_local_cuda_cluster=False, ): """ Returns a tuple containg a CugraphService instance and a Popen instance for the server subprocess. If a server is found running, the Popen instance will be None and no attempt will be made to start a subprocess. """ host = "localhost" port = 9090 client = CugraphServiceClient(host, port) server_process = None try: client.uptime() print("FOUND RUNNING SERVER, ASSUMING IT SHOULD BE USED FOR TESTING!") except CugraphServiceError: # A server was not found, so start one for testing then stop it when # testing is done. server_process = start_server_subprocess( host=host, port=port, start_local_cuda_cluster=start_local_cuda_cluster, dask_scheduler_file=dask_scheduler_file, ) return (client, server_process) def ensure_running_server_for_sampling( host=defaults.host, port=defaults.port, dask_scheduler_file=None, start_local_cuda_cluster=False, ): """ Returns a tuple containing a Popen object for the running cugraph-service server subprocess, and a client object connected to it. If a server was detected already running, the Popen object will be None. """ (client, server_process) = ensure_running_server( host, port, dask_scheduler_file, start_local_cuda_cluster ) # Ensure the extensions needed for these benchmarks are loaded required_graph_creation_extension_module = "benchmark_server_extension" server_data = client.get_server_info() # .stem excludes .py extensions, so it can match a python module name loaded_graph_creation_extension_modules = [ Path(m).stem for m in server_data["graph_creation_extensions"] ] if ( required_graph_creation_extension_module not in loaded_graph_creation_extension_modules ): modules_loaded = client.load_graph_creation_extensions( "cugraph_service_server.testing.benchmark_server_extension" ) if len(modules_loaded) < 1: raise RuntimeError( "failed to load graph creation extension " f"{required_graph_creation_extension_module}" ) loaded_extension_modules = [Path(m).stem for m in server_data["extensions"]] if required_graph_creation_extension_module not in loaded_extension_modules: modules_loaded = client.load_extensions( "cugraph_service_server.testing.benchmark_server_extension" ) if len(modules_loaded) < 1: raise RuntimeError( "failed to load extension " f"{required_graph_creation_extension_module}" ) return (client, server_process)
0
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server
rapidsai_public_repos/cugraph/python/cugraph-service/server/cugraph_service_server/testing/benchmark_server_extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import dask_cudf import cugraph from cugraph.experimental import PropertyGraph, MGPropertyGraph from cugraph import datasets from cugraph.generators import rmat # Graph creation extensions (these are assumed to return a Graph object) def create_graph_from_builtin_dataset(dataset_name, mg=False, server=None): dataset_obj = getattr(datasets, dataset_name) # FIXME: create an MG graph if server is mg? return dataset_obj.get_graph(fetch=True) def create_property_graph_from_builtin_dataset(dataset_name, mg=False, server=None): dataset_obj = getattr(datasets, dataset_name) edgelist_df = dataset_obj.get_edgelist(fetch=True) if mg and (server is not None) and server.is_multi_gpu: G = MGPropertyGraph() edgelist_df = dask_cudf.from_cudf(edgelist_df) else: G = PropertyGraph() G.add_edge_data(edgelist_df, vertex_col_names=["src", "dst"]) return G def create_graph_from_rmat_generator( scale, num_edges, a=0.57, # from Graph500 b=0.19, # from Graph500 c=0.19, # from Graph500 seed=42, clip_and_flip=False, scramble_vertex_ids=False, # FIXME: need to understand relevance of this mg=False, server=None, ): if mg: if (server is not None) and server.is_multi_gpu: is_mg = True else: raise RuntimeError( f"{mg=} was specified but the server is not indicating " "it is MG-capable." ) else: is_mg = False edgelist_df = rmat( scale, num_edges, a, b, c, seed, clip_and_flip, scramble_vertex_ids, create_using=None, # None == return edgelist mg=is_mg, ) edgelist_df["weight"] = np.float32(1) # For PropertyGraph, uncomment: # if is_mg: # G = MGPropertyGraph() # else: # G = PropertyGraph() # # G.add_edge_data(edgelist_df, vertex_col_names=["src", "dst"]) # For Graph, uncomment: G = cugraph.Graph(directed=True) if is_mg: G.from_dask_cudf_edgelist( edgelist_df, source="src", destination="dst", edge_attr="weight", ) else: G.from_cudf_edgelist( edgelist_df, source="src", destination="dst", edge_attr="weight", ) return G # General-purpose extensions def gen_vertex_list(graph_id, num_verts_to_return, num_verts_in_graph, server=None): """ Returns a list of num_verts_to_return vertex IDs from the Graph referenced by graph_id. """ seed = 42 G = server.get_graph(graph_id) if not (isinstance(G, cugraph.Graph)): raise TypeError( f"{graph_id=} must refer to a cugraph.Graph instance, " f"got: {type(G)}" ) # vertex_list is a random sampling of the src verts. # Dask series only support the frac arg for getting n samples. srcs = G.edgelist.edgelist_df["src"] frac = num_verts_to_return / num_verts_in_graph vertex_list = srcs.sample(frac=frac, random_state=seed) # Attempt to automatically handle a dask Series if hasattr(vertex_list, "compute"): vertex_list = vertex_list.compute() # frac does not guarantee exactly num_verts_to_return, so ensure only # num_verts_to_return are returned vertex_list = vertex_list[:num_verts_to_return] assert len(vertex_list) == num_verts_to_return return vertex_list.to_cupy()
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph-dgl/pyproject.toml
# Copyright (c) 2023, NVIDIA CORPORATION. [build-system] requires = [ "setuptools>=61.0.0", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. build-backend = "setuptools.build_meta" [project] name = "cugraph-dgl" dynamic = ["version"] description = "cugraph extensions for DGL" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "cugraph==23.12.*", "numba>=0.57", "numpy>=1.21", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", ] [project.urls] Homepage = "https://github.com/rapidsai/cugraph" Documentation = "https://docs.rapids.ai/api/cugraph/stable/" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "cugraph_dgl/VERSION"} [tool.setuptools.packages.find] include = [ "cugraph_dgl*", ]
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph-dgl/README.md
# cugraph_dgl ## Description [RAPIDS](https://rapids.ai) cugraph_dgl provides a duck-typed version of the [DGLGraph](https://docs.dgl.ai/api/python/dgl.DGLGraph.html#dgl.DGLGraph) class, which uses cugraph for storing graph structure and node/edge feature data. Using cugraph as the backend allows DGL users to access a collection of GPU accelerated algorithms for graph analytics, such as centrality computation and community detection. ## Conda Install and update cugraph-dgl and the required dependencies using the command: ``` conda install mamba -n base -c conda-forge mamba install cugraph-dgl -c rapidsai-nightly -c rapidsai -c pytorch -c conda-forge -c nvidia -c dglteam ``` ## Build from Source ### Create the conda development environment ``` mamba env create -n cugraph_dgl_dev --file conda/cugraph_dgl_dev_11.6.yml ``` ### Install in editable mode ``` pip install -e . ``` ### Run tests ``` pytest tests/* ``` ## Usage ```diff +from cugraph_dgl.convert import cugraph_storage_from_heterograph +cugraph_g = cugraph_storage_from_heterograph(dgl_g) sampler = dgl.dataloading.NeighborSampler( [15, 10, 5], prefetch_node_feats=['feat'], prefetch_labels=['label']) train_dataloader = dgl.dataloading.DataLoader( - dgl_g, + cugraph_g, train_idx, sampler, device=device, batch_size=1024, shuffle=True, drop_last=False, num_workers=0) ```
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph-dgl/setup.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import find_packages, setup packages = find_packages(include=["cugraph_dgl*"]) setup( package_data={key: ["VERSION"] for key in packages}, )
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/cugraph-dgl/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/test_cugraph_storage.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest try: import cugraph_dgl except ModuleNotFoundError: pytest.skip("cugraph_dgl not available", allow_module_level=True) from cugraph.utilities.utils import import_optional import cudf import numpy as np from cugraph_dgl import CuGraphStorage from .utils import assert_same_sampling_len th = import_optional("torch") dgl = import_optional("dgl") @pytest.fixture() def dgl_graph(): graph_data = { ("nt.a", "connects", "nt.b"): ( th.tensor([0, 1, 2]), th.tensor([0, 1, 2]), ), ("nt.a", "connects", "nt.c"): ( th.tensor([0, 1, 2]), th.tensor([0, 1, 2]), ), ("nt.c", "connects", "nt.c"): ( th.tensor([1, 3, 4, 5]), th.tensor([0, 0, 0, 0]), ), } g = dgl.heterograph(graph_data) return g def test_cugraphstore_basic_apis(): num_nodes_dict = {"drug": 3, "gene": 2, "disease": 1} # edges drug_interacts_drug_df = cudf.DataFrame({"src": [0, 1], "dst": [1, 2]}) drug_interacts_gene = cudf.DataFrame({"src": [0, 1], "dst": [0, 1]}) drug_treats_disease = cudf.DataFrame({"src": [1], "dst": [0]}) data_dict = { ("drug", "interacts", "drug"): drug_interacts_drug_df, ("drug", "interacts", "gene"): drug_interacts_gene, ("drug", "treats", "disease"): drug_treats_disease, } gs = CuGraphStorage(data_dict=data_dict, num_nodes_dict=num_nodes_dict) # add node data gs.add_node_data( ntype="drug", feat_name="node_feat", feat_obj=th.as_tensor([0.1, 0.2, 0.3], dtype=th.float64), ) # add edge data gs.add_edge_data( canonical_etype=("drug", "interacts", "drug"), feat_name="edge_feat", feat_obj=th.as_tensor([0.2, 0.4], dtype=th.float64), ) assert gs.num_nodes() == 6 assert gs.num_edges(("drug", "interacts", "drug")) == 2 assert gs.num_edges(("drug", "interacts", "gene")) == 2 assert gs.num_edges(("drug", "treats", "disease")) == 1 node_feat = ( gs.get_node_storage(key="node_feat", ntype="drug") .fetch([0, 1, 2]) .to("cpu") .numpy() ) np.testing.assert_equal(node_feat, np.asarray([0.1, 0.2, 0.3])) edge_feat = ( gs.get_edge_storage(key="edge_feat", etype=("drug", "interacts", "drug")) .fetch([0, 1]) .to("cpu") .numpy() ) np.testing.assert_equal(edge_feat, np.asarray([0.2, 0.4])) def test_sampling_heterograph(dgl_graph): cugraph_gs = cugraph_dgl.cugraph_storage_from_heterograph(dgl_graph) for fanout in [1, 2, 3, -1]: for ntype in ["nt.a", "nt.b", "nt.c"]: for d in ["in", "out"]: assert_same_sampling_len( dgl_graph, cugraph_gs, nodes={ntype: [0]}, fanout=fanout, edge_dir=d, ) def test_sampling_homogenous(): src_ar = np.asarray([0, 1, 2, 0, 1, 2, 7, 9, 10, 11], dtype=np.int32) dst_ar = np.asarray([3, 4, 5, 6, 7, 8, 6, 6, 6, 6], dtype=np.int32) g = dgl.heterograph({("a", "connects", "a"): (src_ar, dst_ar)}) cugraph_gs = cugraph_dgl.cugraph_storage_from_heterograph(g) # Convert to homogeneous g = dgl.to_homogeneous(g) nodes = [6] # Test for multiple fanouts for fanout in [1, 2, 3]: exp_g = g.sample_neighbors(nodes, fanout=fanout) cu_g = cugraph_gs.sample_neighbors(nodes, fanout=fanout) exp_src, exp_dst = exp_g.edges() cu_src, cu_dst = cu_g.edges() assert len(exp_src) == len(cu_src) # Test same results for all neighbours exp_g = g.sample_neighbors(nodes, fanout=-1) cu_g = cugraph_gs.sample_neighbors(nodes, fanout=-1) exp_src, exp_dst = exp_g.edges() exp_src, exp_dst = exp_src.numpy(), exp_dst.numpy() cu_src, cu_dst = cu_g.edges() cu_src, cu_dst = cu_src.to("cpu").numpy(), cu_dst.to("cpu").numpy() # Assert same values sorted by src exp_src_perm = exp_src.argsort() exp_src = exp_src[exp_src_perm] exp_dst = exp_dst[exp_src_perm] cu_src_perm = cu_src.argsort() cu_src = cu_src[cu_src_perm] cu_dst = cu_dst[cu_src_perm] np.testing.assert_equal(exp_dst, cu_dst) np.testing.assert_equal(exp_src, cu_src)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/test_dataloader.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest try: import cugraph_dgl except ModuleNotFoundError: pytest.skip("cugraph_dgl not available", allow_module_level=True) import dgl import torch as th from cugraph_dgl import cugraph_storage_from_heterograph import tempfile import numpy as np def sample_dgl_graphs(g, train_nid, fanouts): # Single fanout to match cugraph sampler = dgl.dataloading.NeighborSampler(fanouts) dataloader = dgl.dataloading.DataLoader( g, train_nid, sampler, batch_size=1, shuffle=False, drop_last=False, num_workers=0, ) dgl_output = {} for batch_id, (input_nodes, output_nodes, blocks) in enumerate(dataloader): dgl_output[batch_id] = { "input_nodes": input_nodes, "output_nodes": output_nodes, "blocks": blocks, } return dgl_output def sample_cugraph_dgl_graphs(cugraph_gs, train_nid, fanouts): sampler = cugraph_dgl.dataloading.NeighborSampler(fanouts) tempdir_object = tempfile.TemporaryDirectory() sampling_output_dir = tempdir_object dataloader = cugraph_dgl.dataloading.DataLoader( cugraph_gs, train_nid, sampler, batch_size=1, sampling_output_dir=sampling_output_dir.name, drop_last=False, shuffle=False, ) cugraph_dgl_output = {} for batch_id, (input_nodes, output_nodes, blocks) in enumerate(dataloader): cugraph_dgl_output[batch_id] = { "input_nodes": input_nodes, "output_nodes": output_nodes, "blocks": blocks, } return cugraph_dgl_output def test_same_heterograph_results(): single_gpu = True data_dict = { ("B", "BA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), ("C", "CA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), } train_nid = {"A": th.tensor([0])} # Create a heterograph with 3 node types and 3 edges types. dgl_g = dgl.heterograph(data_dict) cugraph_gs = cugraph_storage_from_heterograph(dgl_g, single_gpu=single_gpu) dgl_output = sample_dgl_graphs(dgl_g, train_nid, [{"BA": 1, "CA": 1}]) cugraph_output = sample_cugraph_dgl_graphs(cugraph_gs, train_nid, [2]) cugraph_output_nodes = cugraph_output[0]["output_nodes"]["A"].cpu().numpy() dgl_output_nodes = dgl_output[0]["output_nodes"]["A"].cpu().numpy() np.testing.assert_array_equal(cugraph_output_nodes, dgl_output_nodes) assert ( dgl_output[0]["blocks"][0].num_edges() == cugraph_output[0]["blocks"][0].num_edges() ) assert ( dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_output[0]["blocks"][0].num_dst_nodes() ) def test_same_homogeneousgraph_results(): single_gpu = True train_nid = th.tensor([1]) # Create a heterograph with 3 node types and 3 edges types. dgl_g = dgl.graph(([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1])) cugraph_gs = cugraph_storage_from_heterograph(dgl_g, single_gpu=single_gpu) dgl_output = sample_dgl_graphs(dgl_g, train_nid, [2]) cugraph_output = sample_cugraph_dgl_graphs(cugraph_gs, train_nid, [2]) cugraph_output_nodes = cugraph_output[0]["output_nodes"].cpu().numpy() dgl_output_nodes = dgl_output[0]["output_nodes"].cpu().numpy() np.testing.assert_array_equal(cugraph_output_nodes, dgl_output_nodes) assert ( dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_output[0]["blocks"][0].num_dst_nodes() ) assert ( dgl_output[0]["blocks"][0].num_edges() == cugraph_output[0]["blocks"][0].num_edges() ) def test_heterograph_multi_block_results(): data_dict = { ("B", "BA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), ("C", "CA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), ("A", "AA", "A"): ([1], [0]), } dgl_g = dgl.heterograph(data_dict) cugraph_g = cugraph_dgl.cugraph_storage_from_heterograph(dgl_g, single_gpu=True) train_nid = {"A": th.tensor([0])} cugraph_dgl_output = sample_cugraph_dgl_graphs(cugraph_g, train_nid, [10, 10]) assert ( cugraph_dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_dgl_output[0]["blocks"][1].num_src_nodes() ) def test_homogenousgraph_multi_block_results(): dgl_g = dgl.graph(data=([1, 2, 2, 3, 4, 5], [0, 0, 1, 2, 2, 3])) cugraph_g = cugraph_dgl.cugraph_storage_from_heterograph(dgl_g, single_gpu=True) train_nid = th.tensor([0]) cugraph_dgl_output = sample_cugraph_dgl_graphs(cugraph_g, train_nid, [2, 2, 2]) assert ( cugraph_dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_dgl_output[0]["blocks"][1].num_src_nodes() ) assert ( cugraph_dgl_output[0]["blocks"][1].num_dst_nodes() == cugraph_dgl_output[0]["blocks"][2].num_src_nodes() )
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/conftest.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import torch from cugraph.testing.mg_utils import ( start_dask_client, stop_dask_client, ) @pytest.fixture(scope="module") def dask_client(): # start_dask_client will check for the SCHEDULER_FILE and # DASK_WORKER_DEVICES env vars and use them when creating a client if # set. start_dask_client will also initialize the Comms singleton. dask_client, dask_cluster = start_dask_client( dask_worker_devices="0", protocol="tcp" ) yield dask_client stop_dask_client(dask_client, dask_cluster) class SparseGraphData1: size = (6, 5) nnz = 6 src_ids = torch.IntTensor([0, 1, 2, 3, 2, 5]).cuda() dst_ids = torch.IntTensor([1, 2, 3, 4, 0, 3]).cuda() values = torch.IntTensor([10, 20, 30, 40, 50, 60]).cuda() # CSR src_ids_sorted_by_src = torch.IntTensor([0, 1, 2, 2, 3, 5]).cuda() dst_ids_sorted_by_src = torch.IntTensor([1, 2, 0, 3, 4, 3]).cuda() csrc_ids = torch.IntTensor([0, 1, 2, 4, 5, 5, 6]).cuda() values_csr = torch.IntTensor([10, 20, 50, 30, 40, 60]).cuda() # CSC src_ids_sorted_by_dst = torch.IntTensor([2, 0, 1, 5, 2, 3]).cuda() dst_ids_sorted_by_dst = torch.IntTensor([0, 1, 2, 3, 3, 4]).cuda() cdst_ids = torch.IntTensor([0, 1, 2, 3, 5, 6]).cuda() values_csc = torch.IntTensor([50, 10, 20, 60, 30, 40]).cuda() @pytest.fixture def sparse_graph_1(): return SparseGraphData1()
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/__init__.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cugraph.utilities.utils import import_optional th = import_optional("torch") def assert_same_node_feats(gs, g): set(gs.ndata.keys()) == set(g.ndata.keys()) for key in g.ndata.keys(): for ntype in g.ntypes: indices = th.arange(0, g.num_nodes(ntype), dtype=g.idtype).cuda() if len(g.ntypes) <= 1 or ntype in g.ndata[key]: g_output = g.get_node_storage(key=key, ntype=ntype).fetch( indices, device="cuda" ) gs_output = gs.get_node_storage(key=key, ntype=ntype).fetch(indices) equal_t = (gs_output != g_output).sum().cpu() assert equal_t == 0 def assert_same_num_nodes(gs, g): for ntype in g.ntypes: assert g.num_nodes(ntype) == gs.num_nodes(ntype) def assert_same_num_edges_can_etypes(gs, g): for can_etype in g.canonical_etypes: assert g.num_edges(can_etype) == gs.num_edges(can_etype) def assert_same_num_edges_etypes(gs, g): for etype in g.etypes: assert g.num_edges(etype) == gs.num_edges(etype) def assert_same_edge_feats(gs, g): set(gs.edata.keys()) == set(g.edata.keys()) for key in g.edata.keys(): for etype in g.canonical_etypes: indices = th.arange(0, g.num_edges(etype), dtype=g.idtype).cuda() if len(g.etypes) <= 1 or etype in g.edata[key]: g_output = g.get_edge_storage(key=key, etype=etype).fetch( indices, device="cuda" ) gs_output = gs.get_edge_storage(key=key, etype=etype).fetch(indices) equal_t = (gs_output != g_output).sum().cpu() assert equal_t == 0 def assert_same_sampling_len(dgl_g, cugraph_gs, nodes, fanout, edge_dir): dgl_o = dgl_g.sample_neighbors(nodes, fanout=fanout, edge_dir=edge_dir) cugraph_o = cugraph_gs.sample_neighbors(nodes, fanout=fanout, edge_dir=edge_dir) assert cugraph_o.num_edges() == dgl_o.num_edges() for etype in dgl_o.canonical_etypes: assert dgl_o.num_edges(etype) == cugraph_o.num_edges(etype)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/test_from_dgl_heterograph.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest try: import cugraph_dgl except ModuleNotFoundError: pytest.skip("cugraph_dgl not available", allow_module_level=True) from cugraph.utilities.utils import import_optional from .utils import ( assert_same_edge_feats, assert_same_node_feats, assert_same_num_edges_can_etypes, assert_same_num_edges_etypes, assert_same_num_nodes, ) th = import_optional("torch") dgl = import_optional("dgl") F = import_optional("dgl.backend") def create_heterograph1(idtype): ctx = th.device("cuda") graph_data = { ("nt.a", "join.1", "nt.a"): ( F.tensor([0, 1, 2], dtype=idtype), F.tensor([0, 1, 2], dtype=idtype), ), ("nt.a", "join.2", "nt.a"): ( F.tensor([0, 1, 2], dtype=idtype), F.tensor([0, 1, 2], dtype=idtype), ), } g = dgl.heterograph(graph_data, device=th.device("cuda")) g.nodes["nt.a"].data["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=ctx) return g def create_heterograph2(idtype): ctx = th.device("cuda") g = dgl.heterograph( { ("user", "plays", "game"): ( F.tensor([0, 1, 1, 2], dtype=idtype), F.tensor([0, 0, 1, 1], dtype=idtype), ), ("developer", "develops", "game"): ( F.tensor([0, 1], dtype=idtype), F.tensor([0, 1], dtype=idtype), ), ("developer", "tests", "game"): ( F.tensor([0, 1], dtype=idtype), F.tensor([0, 1], dtype=idtype), ), }, idtype=idtype, device=th.device("cuda"), ) g.nodes["user"].data["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=ctx) g.nodes["user"].data["p"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=ctx) g.nodes["game"].data["h"] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=ctx) g.nodes["developer"].data["h"] = F.copy_to(F.tensor([3, 3], dtype=idtype), ctx=ctx) g.edges["plays"].data["h"] = F.copy_to( F.tensor([1, 1, 1, 1], dtype=idtype), ctx=ctx ) return g def create_heterograph3(idtype): ctx = th.device("cuda") g = dgl.heterograph( { ("user", "follows", "user"): ( F.tensor([0, 1, 1, 2, 2, 2], dtype=idtype), F.tensor([0, 0, 1, 1, 2, 2], dtype=idtype), ), ("user", "plays", "game"): ( F.tensor([0, 1], dtype=idtype), F.tensor([0, 1], dtype=idtype), ), }, idtype=idtype, device=th.device("cuda"), ) g.nodes["user"].data["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=ctx) g.nodes["game"].data["h"] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=ctx) g.edges["follows"].data["h"] = F.copy_to( F.tensor([10, 20, 30, 40, 50, 60], dtype=idtype), ctx=ctx ) g.edges["follows"].data["p"] = F.copy_to( F.tensor([1, 2, 3, 4, 5, 6], dtype=idtype), ctx=ctx ) g.edges["plays"].data["h"] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=ctx) return g def create_heterograph4(idtype): ctx = th.device("cuda") g = dgl.heterograph( { ("user", "follows", "user"): ( F.tensor([1, 2], dtype=idtype), F.tensor([0, 1], dtype=idtype), ), ("user", "plays", "game"): ( F.tensor([0, 1], dtype=idtype), F.tensor([0, 1], dtype=idtype), ), }, idtype=idtype, device=th.device("cuda"), ) g.nodes["user"].data["h"] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=ctx) g.nodes["game"].data["h"] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=ctx) g.edges["follows"].data["h"] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=ctx) g.edges["plays"].data["h"] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=ctx) return g @pytest.mark.parametrize("idxtype", [th.int32, th.int64]) def test_heterograph_conversion_nodes(idxtype): graph_fs = [ create_heterograph1, create_heterograph2, create_heterograph3, create_heterograph4, ] for graph_f in graph_fs: g = graph_f(idxtype) gs = cugraph_dgl.cugraph_storage_from_heterograph(g) assert_same_num_nodes(gs, g) assert_same_node_feats(gs, g) @pytest.mark.parametrize("idxtype", [th.int32, th.int64]) def test_heterograph_conversion_edges(idxtype): graph_fs = [ create_heterograph1, create_heterograph2, create_heterograph3, create_heterograph4, ] for graph_f in graph_fs: g = graph_f(idxtype) gs = cugraph_dgl.cugraph_storage_from_heterograph(g) assert_same_num_edges_can_etypes(gs, g) assert_same_num_edges_etypes(gs, g) assert_same_edge_feats(gs, g)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/test_dataset.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest try: import cugraph_dgl del cugraph_dgl except ModuleNotFoundError: pytest.skip("cugraph_dgl not available", allow_module_level=True) from dgl.dataloading import MultiLayerNeighborSampler import dgl import torch import cudf import pandas as pd import cupy as cp import numpy as np from cugraph_dgl.dataloading.utils.sampling_helpers import ( create_homogeneous_sampled_graphs_from_dataframe, ) def get_edge_df_from_homogenous_block(block): block = block.to("cpu") src, dst, eid = block.edges("all") src = block.srcdata[dgl.NID][src] dst = block.dstdata[dgl.NID][dst] eid = block.edata[dgl.EID][eid] df = pd.DataFrame({"src": src, "dst": dst, "eid": eid}) return df.sort_values(by="eid").reset_index(drop=True) def create_dgl_mfgs(g, seed_nodes, fanout): sampler = MultiLayerNeighborSampler(fanout) return sampler.sample_blocks(g, seed_nodes) def create_cugraph_dgl_homogenous_mfgs(dgl_blocks, return_type): df_ls = [] unique_vertices_ls = [] for hop_id, block in enumerate(reversed(dgl_blocks)): block = block.to("cpu") src, dst, eid = block.edges("all") eid = block.edata[dgl.EID][eid] og_src = block.srcdata[dgl.NID][src] og_dst = block.dstdata[dgl.NID][dst] unique_vertices = pd.concat( [pd.Series(og_dst.numpy()), pd.Series(og_src.numpy())] ).drop_duplicates(keep="first") unique_vertices_ls.append(unique_vertices) df = cudf.DataFrame( { "sources": cp.asarray(src), "destinations": cp.asarray(dst), "edge_id": cp.asarray(eid), } ) df["hop_id"] = hop_id df_ls.append(df) df = cudf.concat(df_ls, ignore_index=True) df["batch_id"] = 0 # Add map column # to the dataframe renumberd_map = pd.concat(unique_vertices_ls).drop_duplicates(keep="first").values offsets = np.asarray([2, 2 + len(renumberd_map)]) map_ar = np.concatenate([offsets, renumberd_map]) map_ser = cudf.Series(map_ar) # Have to reindex cause map_ser can be of larger length than df df = df.reindex(df.index.union(map_ser.index)) df["map"] = map_ser return create_homogeneous_sampled_graphs_from_dataframe( df, return_type=return_type )[0] @pytest.mark.parametrize("return_type", ["dgl.Block", "cugraph_dgl.nn.SparseGraph"]) @pytest.mark.parametrize("seed_node", [3, 4, 5]) def test_homogeneous_sampled_graphs_from_dataframe(return_type, seed_node): g = dgl.graph(([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])) fanout = [1, 1, 1] seed_node = torch.as_tensor([seed_node]) dgl_seed_nodes, dgl_output_nodes, dgl_mfgs = create_dgl_mfgs(g, seed_node, fanout) ( cugraph_seed_nodes, cugraph_output_nodes, cugraph_mfgs, ) = create_cugraph_dgl_homogenous_mfgs(dgl_mfgs, return_type=return_type) np.testing.assert_equal( cugraph_seed_nodes.cpu().numpy().copy().sort(), dgl_seed_nodes.cpu().numpy().copy().sort(), ) np.testing.assert_equal( dgl_output_nodes.cpu().numpy().copy().sort(), cugraph_output_nodes.cpu().numpy().copy().sort(), ) if return_type == "dgl.Block": for dgl_block, cugraph_dgl_block in zip(dgl_mfgs, cugraph_mfgs): dgl_df = get_edge_df_from_homogenous_block(dgl_block) cugraph_dgl_df = get_edge_df_from_homogenous_block(cugraph_dgl_block) pd.testing.assert_frame_equal(dgl_df, cugraph_dgl_df) else: for dgl_block, cugraph_dgl_graph in zip(dgl_mfgs, cugraph_mfgs): # Can not verify edge ids as they are not # preserved in cugraph_dgl.nn.SparseGraph assert dgl_block.num_src_nodes() == cugraph_dgl_graph.num_src_nodes() assert dgl_block.num_dst_nodes() == cugraph_dgl_graph.num_dst_nodes() dgl_offsets, dgl_indices, _ = dgl_block.adj_tensors("csc") cugraph_offsets, cugraph_indices, _ = cugraph_dgl_graph.csc() assert torch.equal(dgl_offsets.to("cpu"), cugraph_offsets.to("cpu")) assert torch.equal(dgl_indices.to("cpu"), cugraph_indices.to("cpu"))
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/test_utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cudf import cupy as cp import numpy as np from cugraph_dgl.dataloading.utils.sampling_helpers import ( cast_to_tensor, _get_renumber_map, _split_tensor, _get_tensor_d_from_sampled_df, create_homogeneous_sampled_graphs_from_dataframe, _get_source_destination_range, _create_homogeneous_cugraph_dgl_nn_sparse_graph, create_homogeneous_sampled_graphs_from_dataframe_csc, ) from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") cugraph_dgl = import_optional("cugraph_dgl") def test_casting_empty_array(): ar = cp.zeros(shape=0, dtype=cp.int32) ser = cudf.Series(ar) output_tensor = cast_to_tensor(ser) assert output_tensor.dtype == torch.int32 def get_dummy_sampled_df(): df = cudf.DataFrame() df["sources"] = [0, 0, 1, 0, 0, 1, 0, 0, 2] + [np.nan] * 4 df["destinations"] = [1, 2, 0, 1, 2, 1, 2, 0, 1] + [np.nan] * 4 df["batch_id"] = [0, 0, 0, 1, 1, 1, 2, 2, 2] + [np.nan] * 4 df["hop_id"] = [0, 1, 1, 0, 1, 1, 0, 1, 1] + [np.nan] * 4 df["map"] = [4, 7, 10, 13, 10, 11, 12, 13, 14, 15, 16, 17, 18] df = df.astype("int32") df["hop_id"] = df["hop_id"].astype("uint8") df["map"] = df["map"].astype("int64") return df def get_dummy_sampled_df_csc(): df_dict = dict( minors=np.array( [1, 1, 2, 1, 0, 3, 1, 3, 2, 3, 2, 4, 0, 1, 1, 0, 3, 2], dtype=np.int32 ), major_offsets=np.arange(19, dtype=np.int64), map=np.array( [26, 29, 33, 22, 23, 32, 18, 29, 33, 33, 8, 30, 32], dtype=np.int32 ), renumber_map_offsets=np.array([0, 4, 9, 13], dtype=np.int64), label_hop_offsets=np.array([0, 1, 3, 6, 7, 9, 13, 14, 16, 18], dtype=np.int64), ) # convert values to Series so that NaNs are padded automatically return cudf.DataFrame({k: cudf.Series(v) for k, v in df_dict.items()}) def test_get_renumber_map(): sampled_df = get_dummy_sampled_df() df, renumber_map, renumber_map_batch_indices = _get_renumber_map(sampled_df) # Ensure that map was dropped assert "map" not in df.columns expected_map = torch.as_tensor( [10, 11, 12, 13, 14, 15, 16, 17, 18], dtype=torch.int32, device="cuda" ) assert torch.equal(renumber_map, expected_map) expected_batch_indices = torch.as_tensor([3, 6], dtype=torch.int32, device="cuda") assert torch.equal(renumber_map_batch_indices, expected_batch_indices) # Ensure we dropped the Nans for rows corresponding to the renumber_map assert len(df) == 9 t_ls = _split_tensor(renumber_map, renumber_map_batch_indices) assert torch.equal( t_ls[0], torch.as_tensor([10, 11, 12], dtype=torch.int64, device="cuda") ) assert torch.equal( t_ls[1], torch.as_tensor([13, 14, 15], dtype=torch.int64, device="cuda") ) assert torch.equal( t_ls[2], torch.as_tensor([16, 17, 18], dtype=torch.int64, device="cuda") ) def test_get_tensor_d_from_sampled_df(): df = get_dummy_sampled_df() tensor_d = _get_tensor_d_from_sampled_df(df) expected_maps = {} expected_maps[0] = torch.as_tensor([10, 11, 12], dtype=torch.int64, device="cuda") expected_maps[1] = torch.as_tensor([13, 14, 15], dtype=torch.int64, device="cuda") expected_maps[2] = torch.as_tensor([16, 17, 18], dtype=torch.int64, device="cuda") for batch_id, batch_td in tensor_d.items(): batch_df = df[df["batch_id"] == batch_id] for hop_id, hop_t in batch_td.items(): if hop_id != "map": hop_df = batch_df[batch_df["hop_id"] == hop_id] assert torch.equal(hop_t["sources"], cast_to_tensor(hop_df["sources"])) assert torch.equal( hop_t["destinations"], cast_to_tensor(hop_df["destinations"]) ) assert torch.equal(batch_td["map"], expected_maps[batch_id]) def test_create_homogeneous_sampled_graphs_from_dataframe(): sampler = dgl.dataloading.MultiLayerNeighborSampler([2, 2]) g = dgl.graph(([0, 10, 20], [0, 0, 10])).to("cuda") dgl_input_nodes, dgl_output_nodes, dgl_blocks = sampler.sample_blocks( g, torch.as_tensor([0]).to("cuda") ) # Directions are reversed in dgl s1, d1 = dgl_blocks[0].edges() s0, d0 = dgl_blocks[1].edges() srcs = cp.concatenate([cp.asarray(s0), cp.asarray(s1)]) dsts = cp.concatenate([cp.asarray(d0), cp.asarray(d1)]) nids = dgl_blocks[0].srcdata[dgl.NID] nids = cp.concatenate( [cp.asarray([2]), cp.asarray([len(nids) + 2]), cp.asarray(nids)] ) df = cudf.DataFrame() df["sources"] = srcs df["destinations"] = dsts df["hop_id"] = [0] * len(s0) + [1] * len(s1) df["batch_id"] = 0 df["map"] = nids ( cugraph_input_nodes, cugraph_output_nodes, cugraph_blocks, ) = create_homogeneous_sampled_graphs_from_dataframe(df)[0] assert torch.equal(dgl_input_nodes, cugraph_input_nodes) assert torch.equal(dgl_output_nodes, cugraph_output_nodes) for c_block, d_block in zip(cugraph_blocks, dgl_blocks): ce, cd = c_block.edges() de, dd = d_block.edges() assert torch.equal(ce, de) assert torch.equal(cd, dd) def test_get_source_destination_range(): df = get_dummy_sampled_df() output_d = _get_source_destination_range(df) expected_output = { (0, 0): {"sources_range": 0, "destinations_range": 1}, (0, 1): {"sources_range": 1, "destinations_range": 2}, (1, 0): {"sources_range": 0, "destinations_range": 1}, (1, 1): {"sources_range": 1, "destinations_range": 2}, (2, 0): {"sources_range": 0, "destinations_range": 2}, (2, 1): {"sources_range": 2, "destinations_range": 1}, } assert output_d == expected_output def test__create_homogeneous_cugraph_dgl_nn_sparse_graph(): tensor_d = { "sources_range": 1, "destinations_range": 2, "sources": torch.as_tensor([0, 0, 1, 1], dtype=torch.int64, device="cuda"), "destinations": torch.as_tensor([0, 0, 1, 2], dtype=torch.int64, device="cuda"), } seednodes_range = 10 sparse_graph = _create_homogeneous_cugraph_dgl_nn_sparse_graph( tensor_d, seednodes_range ) assert sparse_graph.num_src_nodes() == 2 assert sparse_graph.num_dst_nodes() == seednodes_range + 1 assert isinstance(sparse_graph, cugraph_dgl.nn.SparseGraph) def test_create_homogeneous_sampled_graphs_from_dataframe_csc(): df = get_dummy_sampled_df_csc() batches = create_homogeneous_sampled_graphs_from_dataframe_csc(df) assert len(batches) == 3 assert torch.equal(batches[0][0], torch.IntTensor([26, 29, 33, 22]).cuda()) assert torch.equal(batches[1][0], torch.IntTensor([23, 32, 18, 29, 33]).cuda()) assert torch.equal(batches[2][0], torch.IntTensor([33, 8, 30, 32]).cuda())
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/common.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cugraph.utilities.utils import import_optional th = import_optional("torch") dgl = import_optional("dgl") def create_graph1(): u = th.tensor([0, 1, 0, 2, 3, 0, 4, 0, 5, 0, 6, 7, 0, 8, 9]) v = th.tensor([1, 9, 2, 9, 9, 4, 9, 5, 9, 6, 9, 9, 8, 9, 0]) g = dgl.graph((u, v)) return g
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_sparsegraph.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cugraph.utilities.utils import import_optional from cugraph_dgl.nn import SparseGraph torch = import_optional("torch") def test_coo2csc(sparse_graph_1): data = sparse_graph_1 g = SparseGraph( size=data.size, src_ids=data.src_ids, dst_ids=data.dst_ids, values=data.values, formats=["csc"], ) cdst_ids, src_ids, values = g.csc() new = torch.sparse_csc_tensor(cdst_ids, src_ids, values).cuda() old = torch.sparse_coo_tensor( torch.vstack((data.src_ids, data.dst_ids)), data.values ).cuda() torch.allclose(new.to_dense(), old.to_dense()) def test_csc_input(sparse_graph_1): data = sparse_graph_1 g = SparseGraph( size=data.size, src_ids=data.src_ids_sorted_by_dst, cdst_ids=data.cdst_ids, values=data.values_csc, formats=["coo", "csc", "csr"], ) src_ids, dst_ids, values = g.coo() new = torch.sparse_coo_tensor(torch.vstack((src_ids, dst_ids)), values).cuda() old = torch.sparse_csc_tensor( data.cdst_ids, data.src_ids_sorted_by_dst, data.values_csc ).cuda() torch.allclose(new.to_dense(), old.to_dense()) csrc_ids, dst_ids, values = g.csr() new = torch.sparse_csr_tensor(csrc_ids, dst_ids, values).cuda() torch.allclose(new.to_dense(), old.to_dense())
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_transformerconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from cugraph_dgl.nn.conv.base import SparseGraph from cugraph_dgl.nn import TransformerConv from .common import create_graph1 dgl = pytest.importorskip("dgl", reason="DGL not available") torch = pytest.importorskip("torch", reason="PyTorch not available") ATOL = 1e-6 @pytest.mark.parametrize("beta", [False, True]) @pytest.mark.parametrize("bipartite_node_feats", [False, True]) @pytest.mark.parametrize("concat", [False, True]) @pytest.mark.parametrize("idtype_int", [False, True]) @pytest.mark.parametrize("num_heads", [1, 2, 3, 4]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("use_edge_feats", [False, True]) @pytest.mark.parametrize("sparse_format", ["coo", "csc", None]) def test_transformerconv( beta, bipartite_node_feats, concat, idtype_int, num_heads, to_block, use_edge_feats, sparse_format, ): torch.manual_seed(12345) device = "cuda" g = create_graph1().to(device) if idtype_int: g = g.int() if to_block: g = dgl.to_block(g) size = (g.num_src_nodes(), g.num_dst_nodes()) if sparse_format == "coo": sg = SparseGraph( size=size, src_ids=g.edges()[0], dst_ids=g.edges()[1], formats="csc" ) elif sparse_format == "csc": offsets, indices, _ = g.adj_tensors("csc") sg = SparseGraph(size=size, src_ids=indices, cdst_ids=offsets, formats="csc") if bipartite_node_feats: in_node_feats = (5, 3) nfeat = ( torch.rand(g.num_src_nodes(), in_node_feats[0], device=device), torch.rand(g.num_dst_nodes(), in_node_feats[1], device=device), ) else: in_node_feats = 3 nfeat = torch.rand(g.num_src_nodes(), in_node_feats, device=device) out_node_feats = 2 if use_edge_feats: edge_feats = 3 efeat = torch.rand(g.num_edges(), edge_feats, device=device) else: edge_feats = None efeat = None conv = TransformerConv( in_node_feats, out_node_feats, num_heads=num_heads, concat=concat, beta=beta, edge_feats=edge_feats, ).to(device) if sparse_format is not None: out = conv(sg, nfeat, efeat) else: out = conv(g, nfeat, efeat) grad_out = torch.rand_like(out) out.backward(grad_out)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_sageconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from cugraph_dgl.nn.conv.base import SparseGraph from cugraph_dgl.nn import SAGEConv as CuGraphSAGEConv from .common import create_graph1 dgl = pytest.importorskip("dgl", reason="DGL not available") torch = pytest.importorskip("torch", reason="PyTorch not available") ATOL = 1e-6 @pytest.mark.parametrize("aggr", ["mean", "pool"]) @pytest.mark.parametrize("bias", [False, True]) @pytest.mark.parametrize("bipartite", [False, True]) @pytest.mark.parametrize("idtype_int", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("sparse_format", ["coo", "csc", None]) def test_sageconv_equality( aggr, bias, bipartite, idtype_int, max_in_degree, to_block, sparse_format ): from dgl.nn.pytorch import SAGEConv torch.manual_seed(12345) kwargs = {"aggregator_type": aggr, "bias": bias} g = create_graph1().to("cuda") if idtype_int: g = g.int() if to_block: g = dgl.to_block(g) size = (g.num_src_nodes(), g.num_dst_nodes()) if bipartite: in_feats = (5, 3) feat = ( torch.rand(size[0], in_feats[0], requires_grad=True).cuda(), torch.rand(size[1], in_feats[1], requires_grad=True).cuda(), ) else: in_feats = 5 feat = torch.rand(size[0], in_feats).cuda() out_feats = 2 if sparse_format == "coo": sg = SparseGraph( size=size, src_ids=g.edges()[0], dst_ids=g.edges()[1], formats="csc" ) elif sparse_format == "csc": offsets, indices, _ = g.adj_tensors("csc") sg = SparseGraph(size=size, src_ids=indices, cdst_ids=offsets, formats="csc") conv1 = SAGEConv(in_feats, out_feats, **kwargs).cuda() conv2 = CuGraphSAGEConv(in_feats, out_feats, **kwargs).cuda() in_feats_src = conv2.in_feats_src with torch.no_grad(): conv2.lin.weight.data[:, :in_feats_src] = conv1.fc_neigh.weight.data conv2.lin.weight.data[:, in_feats_src:] = conv1.fc_self.weight.data if bias: conv2.lin.bias.data[:] = conv1.fc_self.bias.data if aggr == "pool": conv2.pre_lin.weight.data[:] = conv1.fc_pool.weight.data conv2.pre_lin.bias.data[:] = conv1.fc_pool.bias.data out1 = conv1(g, feat) if sparse_format is not None: out2 = conv2(sg, feat, max_in_degree=max_in_degree) else: out2 = conv2(g, feat, max_in_degree=max_in_degree) assert torch.allclose(out1, out2, atol=ATOL) grad_out = torch.rand_like(out1) out1.backward(grad_out) out2.backward(grad_out) assert torch.allclose( conv1.fc_neigh.weight.grad, conv2.lin.weight.grad[:, :in_feats_src], atol=ATOL, ) assert torch.allclose( conv1.fc_self.weight.grad, conv2.lin.weight.grad[:, in_feats_src:], atol=ATOL, ) if bias: assert torch.allclose(conv1.fc_self.bias.grad, conv2.lin.bias.grad, atol=ATOL)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_gatconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from cugraph_dgl.nn.conv.base import SparseGraph from cugraph_dgl.nn import GATConv as CuGraphGATConv from .common import create_graph1 dgl = pytest.importorskip("dgl", reason="DGL not available") torch = pytest.importorskip("torch", reason="PyTorch not available") ATOL = 1e-6 @pytest.mark.parametrize("bipartite", [False, True]) @pytest.mark.parametrize("idtype_int", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8]) @pytest.mark.parametrize("num_heads", [1, 2, 7]) @pytest.mark.parametrize("residual", [False, True]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("sparse_format", ["coo", "csc", None]) def test_gatconv_equality( bipartite, idtype_int, max_in_degree, num_heads, residual, to_block, sparse_format ): from dgl.nn.pytorch import GATConv torch.manual_seed(12345) g = create_graph1().to("cuda") if idtype_int: g = g.int() if to_block: g = dgl.to_block(g) size = (g.num_src_nodes(), g.num_dst_nodes()) if bipartite: in_feats = (10, 3) nfeat = ( torch.rand(g.num_src_nodes(), in_feats[0]).cuda(), torch.rand(g.num_dst_nodes(), in_feats[1]).cuda(), ) else: in_feats = 10 nfeat = torch.rand(g.num_src_nodes(), in_feats).cuda() out_feats = 2 if sparse_format == "coo": sg = SparseGraph( size=size, src_ids=g.edges()[0], dst_ids=g.edges()[1], formats="csc" ) elif sparse_format == "csc": offsets, indices, _ = g.adj_tensors("csc") sg = SparseGraph(size=size, src_ids=indices, cdst_ids=offsets, formats="csc") args = (in_feats, out_feats, num_heads) kwargs = {"bias": False, "allow_zero_in_degree": True} conv1 = GATConv(*args, **kwargs).cuda() out1 = conv1(g, nfeat) conv2 = CuGraphGATConv(*args, **kwargs).cuda() dim = num_heads * out_feats with torch.no_grad(): conv2.attn_weights.data[:dim] = conv1.attn_l.data.flatten() conv2.attn_weights.data[dim:] = conv1.attn_r.data.flatten() if bipartite: conv2.lin_src.weight.data = conv1.fc_src.weight.data.detach().clone() conv2.lin_dst.weight.data = conv1.fc_dst.weight.data.detach().clone() else: conv2.lin.weight.data = conv1.fc.weight.data.detach().clone() if residual and conv2.residual: conv2.lin_res.weight.data = conv1.fc_res.weight.data.detach().clone() if sparse_format is not None: out2 = conv2(sg, nfeat, max_in_degree=max_in_degree) else: out2 = conv2(g, nfeat, max_in_degree=max_in_degree) assert torch.allclose(out1, out2, atol=ATOL) grad_out1 = torch.rand_like(out1) grad_out2 = grad_out1.clone().detach() out1.backward(grad_out1) out2.backward(grad_out2) if bipartite: assert torch.allclose( conv1.fc_src.weight.grad, conv2.lin_src.weight.grad, atol=ATOL ) assert torch.allclose( conv1.fc_dst.weight.grad, conv2.lin_dst.weight.grad, atol=ATOL ) else: assert torch.allclose(conv1.fc.weight.grad, conv2.lin.weight.grad, atol=ATOL) assert torch.allclose( torch.cat((conv1.attn_l.grad, conv1.attn_r.grad), dim=0), conv2.attn_weights.grad.view(2, num_heads, out_feats), atol=ATOL, ) @pytest.mark.parametrize("bias", [False, True]) @pytest.mark.parametrize("bipartite", [False, True]) @pytest.mark.parametrize("concat", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8, 800]) @pytest.mark.parametrize("num_heads", [1, 2, 7]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("use_edge_feats", [False, True]) def test_gatconv_edge_feats( bias, bipartite, concat, max_in_degree, num_heads, to_block, use_edge_feats ): torch.manual_seed(12345) g = create_graph1().to("cuda") if to_block: g = dgl.to_block(g) if bipartite: in_feats = (10, 3) nfeat = ( torch.rand(g.num_src_nodes(), in_feats[0]).cuda(), torch.rand(g.num_dst_nodes(), in_feats[1]).cuda(), ) else: in_feats = 10 nfeat = torch.rand(g.num_src_nodes(), in_feats).cuda() out_feats = 2 if use_edge_feats: edge_feats = 3 efeat = torch.rand(g.num_edges(), edge_feats).cuda() else: edge_feats = None efeat = None conv = CuGraphGATConv( in_feats, out_feats, num_heads, concat=concat, edge_feats=edge_feats, bias=bias, allow_zero_in_degree=True, ).cuda() out = conv(g, nfeat, efeat=efeat, max_in_degree=max_in_degree) grad_out = torch.rand_like(out) out.backward(grad_out)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_relgraphconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from cugraph_dgl.nn.conv.base import SparseGraph from cugraph_dgl.nn import RelGraphConv as CuGraphRelGraphConv from .common import create_graph1 dgl = pytest.importorskip("dgl", reason="DGL not available") torch = pytest.importorskip("torch", reason="PyTorch not available") ATOL = 1e-6 @pytest.mark.parametrize("idtype_int", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8]) @pytest.mark.parametrize("num_bases", [1, 2, 5]) @pytest.mark.parametrize("regularizer", [None, "basis"]) @pytest.mark.parametrize("self_loop", [False, True]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("sparse_format", ["coo", "csc", None]) def test_relgraphconv_equality( idtype_int, max_in_degree, num_bases, regularizer, self_loop, to_block, sparse_format, ): from dgl.nn.pytorch import RelGraphConv torch.manual_seed(12345) in_feat, out_feat, num_rels = 10, 2, 3 args = (in_feat, out_feat, num_rels) kwargs = { "num_bases": num_bases, "regularizer": regularizer, "bias": False, "self_loop": self_loop, } g = create_graph1().to("cuda") g.edata[dgl.ETYPE] = torch.randint(num_rels, (g.num_edges(),)).cuda() if idtype_int: g = g.int() if to_block: g = dgl.to_block(g) size = (g.num_src_nodes(), g.num_dst_nodes()) feat = torch.rand(g.num_src_nodes(), in_feat).cuda() if sparse_format == "coo": sg = SparseGraph( size=size, src_ids=g.edges()[0], dst_ids=g.edges()[1], values=g.edata[dgl.ETYPE], formats="csc", ) elif sparse_format == "csc": offsets, indices, perm = g.adj_tensors("csc") etypes = g.edata[dgl.ETYPE][perm] sg = SparseGraph( size=size, src_ids=indices, cdst_ids=offsets, values=etypes, formats="csc" ) conv1 = RelGraphConv(*args, **kwargs).cuda() conv2 = CuGraphRelGraphConv(*args, **kwargs, apply_norm=False).cuda() with torch.no_grad(): if self_loop: conv2.W.data[:-1] = conv1.linear_r.W.data conv2.W.data[-1] = conv1.loop_weight.data else: conv2.W.data = conv1.linear_r.W.data.detach().clone() if regularizer is not None: conv2.coeff.data = conv1.linear_r.coeff.data.detach().clone() out1 = conv1(g, feat, g.edata[dgl.ETYPE]) if sparse_format is not None: out2 = conv2(sg, feat, sg.values(), max_in_degree=max_in_degree) else: out2 = conv2(g, feat, g.edata[dgl.ETYPE], max_in_degree=max_in_degree) assert torch.allclose(out1, out2, atol=ATOL) grad_out = torch.rand_like(out1) out1.backward(grad_out) out2.backward(grad_out) end = -1 if self_loop else None assert torch.allclose(conv1.linear_r.W.grad, conv2.W.grad[:end], atol=ATOL) if self_loop: assert torch.allclose(conv1.loop_weight.grad, conv2.W.grad[-1], atol=ATOL) if regularizer is not None: assert torch.allclose(conv1.linear_r.coeff.grad, conv2.coeff.grad, atol=ATOL)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/nn/test_gatv2conv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from cugraph_dgl.nn.conv.base import SparseGraph from cugraph_dgl.nn import GATv2Conv as CuGraphGATv2Conv from .common import create_graph1 dgl = pytest.importorskip("dgl", reason="DGL not available") torch = pytest.importorskip("torch", reason="PyTorch not available") ATOL = 1e-6 @pytest.mark.parametrize("bipartite", [False, True]) @pytest.mark.parametrize("idtype_int", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8]) @pytest.mark.parametrize("num_heads", [1, 2, 7]) @pytest.mark.parametrize("residual", [False, True]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("sparse_format", ["coo", "csc", None]) def test_gatv2conv_equality( bipartite, idtype_int, max_in_degree, num_heads, residual, to_block, sparse_format ): from dgl.nn.pytorch import GATv2Conv torch.manual_seed(12345) g = create_graph1().to("cuda") if idtype_int: g = g.int() if to_block: g = dgl.to_block(g) size = (g.num_src_nodes(), g.num_dst_nodes()) if bipartite: in_feats = (10, 3) nfeat = ( torch.rand(g.num_src_nodes(), in_feats[0]).cuda(), torch.rand(g.num_dst_nodes(), in_feats[1]).cuda(), ) else: in_feats = 10 nfeat = torch.rand(g.num_src_nodes(), in_feats).cuda() out_feats = 2 if sparse_format == "coo": sg = SparseGraph( size=size, src_ids=g.edges()[0], dst_ids=g.edges()[1], formats="csc" ) elif sparse_format == "csc": offsets, indices, _ = g.adj_tensors("csc") sg = SparseGraph(size=size, src_ids=indices, cdst_ids=offsets, formats="csc") args = (in_feats, out_feats, num_heads) kwargs = {"bias": False, "allow_zero_in_degree": True} conv1 = GATv2Conv(*args, **kwargs).cuda() out1 = conv1(g, nfeat) conv2 = CuGraphGATv2Conv(*args, **kwargs).cuda() with torch.no_grad(): conv2.attn.data = conv1.attn.data.flatten() conv2.lin_src.weight.data = conv1.fc_src.weight.data.detach().clone() conv2.lin_dst.weight.data = conv1.fc_dst.weight.data.detach().clone() if residual and conv2.residual: conv2.lin_res.weight.data = conv1.fc_res.weight.data.detach().clone() if sparse_format is not None: out2 = conv2(sg, nfeat, max_in_degree=max_in_degree) else: out2 = conv2(g, nfeat, max_in_degree=max_in_degree) assert torch.allclose(out1, out2, atol=ATOL) grad_out1 = torch.rand_like(out1) grad_out2 = grad_out1.clone().detach() out1.backward(grad_out1) out2.backward(grad_out2) assert torch.allclose( conv1.fc_src.weight.grad, conv2.lin_src.weight.grad, atol=ATOL ) assert torch.allclose( conv1.fc_dst.weight.grad, conv2.lin_dst.weight.grad, atol=ATOL ) assert torch.allclose(conv1.attn.grad, conv1.attn.grad, atol=ATOL) @pytest.mark.parametrize("bias", [False, True]) @pytest.mark.parametrize("bipartite", [False, True]) @pytest.mark.parametrize("concat", [False, True]) @pytest.mark.parametrize("max_in_degree", [None, 8, 800]) @pytest.mark.parametrize("num_heads", [1, 2, 7]) @pytest.mark.parametrize("to_block", [False, True]) @pytest.mark.parametrize("use_edge_feats", [False, True]) def test_gatv2conv_edge_feats( bias, bipartite, concat, max_in_degree, num_heads, to_block, use_edge_feats ): torch.manual_seed(12345) g = create_graph1().to("cuda") if to_block: g = dgl.to_block(g) if bipartite: in_feats = (10, 3) nfeat = ( torch.rand(g.num_src_nodes(), in_feats[0]).cuda(), torch.rand(g.num_dst_nodes(), in_feats[1]).cuda(), ) else: in_feats = 10 nfeat = torch.rand(g.num_src_nodes(), in_feats).cuda() out_feats = 2 if use_edge_feats: edge_feats = 3 efeat = torch.rand(g.num_edges(), edge_feats).cuda() else: edge_feats = None efeat = None conv = CuGraphGATv2Conv( in_feats, out_feats, num_heads, concat=concat, edge_feats=edge_feats, bias=bias, allow_zero_in_degree=True, ).cuda() out = conv(g, nfeat, efeat=efeat, max_in_degree=max_in_degree) grad_out = torch.rand_like(out) out.backward(grad_out)
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests
rapidsai_public_repos/cugraph/python/cugraph-dgl/tests/mg/test_dataloader.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest try: import cugraph_dgl except ModuleNotFoundError: pytest.skip("cugraph_dgl not available", allow_module_level=True) import dgl import torch as th from cugraph_dgl import cugraph_storage_from_heterograph import tempfile import numpy as np def sample_dgl_graphs(g, train_nid, fanouts): # Single fanout to match cugraph sampler = dgl.dataloading.NeighborSampler(fanouts) dataloader = dgl.dataloading.DataLoader( g, train_nid, sampler, batch_size=1, shuffle=False, drop_last=False, num_workers=0, ) dgl_output = {} for batch_id, (input_nodes, output_nodes, blocks) in enumerate(dataloader): dgl_output[batch_id] = { "input_nodes": input_nodes, "output_nodes": output_nodes, "blocks": blocks, } return dgl_output def sample_cugraph_dgl_graphs(cugraph_gs, train_nid, fanouts): sampler = cugraph_dgl.dataloading.NeighborSampler(fanouts) tempdir_object = tempfile.TemporaryDirectory() sampling_output_dir = tempdir_object dataloader = cugraph_dgl.dataloading.DataLoader( cugraph_gs, train_nid, sampler, batch_size=1, sampling_output_dir=sampling_output_dir.name, drop_last=False, shuffle=False, ) cugraph_dgl_output = {} for batch_id, (input_nodes, output_nodes, blocks) in enumerate(dataloader): cugraph_dgl_output[batch_id] = { "input_nodes": input_nodes, "output_nodes": output_nodes, "blocks": blocks, } return cugraph_dgl_output def test_same_heterograph_results(dask_client): single_gpu = False data_dict = { ("B", "BA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), ("C", "CA", "A"): ([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1]), } train_nid = {"A": th.tensor([0])} # Create a heterograph with 3 node types and 3 edges types. dgl_g = dgl.heterograph(data_dict) cugraph_gs = cugraph_storage_from_heterograph(dgl_g, single_gpu=single_gpu) dgl_output = sample_dgl_graphs(dgl_g, train_nid, [{"BA": 1, "CA": 1}]) cugraph_output = sample_cugraph_dgl_graphs(cugraph_gs, train_nid, [2]) cugraph_output_nodes = cugraph_output[0]["output_nodes"]["A"].cpu().numpy() dgl_output_nodes = dgl_output[0]["output_nodes"]["A"].cpu().numpy() np.testing.assert_array_equal(cugraph_output_nodes, dgl_output_nodes) assert ( dgl_output[0]["blocks"][0].num_edges() == cugraph_output[0]["blocks"][0].num_edges() ) assert ( dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_output[0]["blocks"][0].num_dst_nodes() ) def test_same_homogeneousgraph_results(dask_client): single_gpu = False train_nid = th.tensor([1]) # Create a heterograph with 3 node types and 3 edges types. dgl_g = dgl.graph(([1, 2, 3, 4, 5, 6, 7, 8], [0, 0, 0, 0, 1, 1, 1, 1])) cugraph_gs = cugraph_storage_from_heterograph(dgl_g, single_gpu=single_gpu) dgl_output = sample_dgl_graphs(dgl_g, train_nid, [2]) cugraph_output = sample_cugraph_dgl_graphs(cugraph_gs, train_nid, [2]) cugraph_output_nodes = cugraph_output[0]["output_nodes"].cpu().numpy() dgl_output_nodes = dgl_output[0]["output_nodes"].cpu().numpy() np.testing.assert_array_equal(cugraph_output_nodes, dgl_output_nodes) assert ( dgl_output[0]["blocks"][0].num_dst_nodes() == cugraph_output[0]["blocks"][0].num_dst_nodes() ) assert ( dgl_output[0]["blocks"][0].num_edges() == cugraph_output[0]["blocks"][0].num_edges() )
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import importlib.resources # Read VERSION file from the module that is symlinked to VERSION file # in the root of the repo at build time or copied to the moudle at # installation. VERSION is a separate file that allows CI build-time scripts # to update version info (including commit hashes) without modifying # source files. __version__ = ( importlib.resources.files("cugraph_dgl").joinpath("VERSION").read_text().strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/convert.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from cugraph.utilities.utils import import_optional from cugraph_dgl import CuGraphStorage from cugraph_dgl.utils.cugraph_conversion_utils import ( get_edges_dict_from_dgl_HeteroGraph, add_ndata_from_dgl_HeteroGraph, add_edata_from_dgl_HeteroGraph, ) dgl = import_optional("dgl") def cugraph_storage_from_heterograph( g: dgl.DGLGraph, single_gpu: bool = True ) -> CuGraphStorage: """ Convert DGL Graph to CuGraphStorage graph """ num_nodes_dict = {ntype: g.num_nodes(ntype) for ntype in g.ntypes} edges_dict = get_edges_dict_from_dgl_HeteroGraph(g, single_gpu) gs = CuGraphStorage( data_dict=edges_dict, num_nodes_dict=num_nodes_dict, single_gpu=single_gpu, idtype=g.idtype, ) add_ndata_from_dgl_HeteroGraph(gs, g) add_edata_from_dgl_HeteroGraph(gs, g) return gs
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/cugraph_storage.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Optional, Sequence, Tuple, Dict, Union from functools import cached_property from cugraph.utilities.utils import import_optional, MissingModule from cugraph.gnn import FeatureStore from cugraph.gnn.dgl_extensions.dgl_uniform_sampler import DGLUniformSampler import cudf import dask_cudf import cupy as cp from cugraph_dgl.utils.cugraph_storage_utils import ( _assert_valid_canonical_etype, backend_dtype_to_np_dtype_dict, add_edge_ids_to_edges_dict, add_node_offset_to_edges_dict, ) from cugraph_dgl.utils.feature_storage import dgl_FeatureStorage dgl = import_optional("dgl") F = import_optional("dgl.backend") torch = import_optional("torch") class CuGraphStorage: """ Duck-typed version of the DGLHeteroGraph class made for cuGraph for storing graph structure and node/edge feature data. This object is wrapper around cugraph's Multi GPU MultiGraph and returns samples that conform with `DGLHeteroGraph` See: https://docs.rapids.ai/api/cugraph/nightly/api_docs/cugraph_dgl.html """ def __init__( self, data_dict: Dict[ Tuple[str, str, str], Union[cudf.DataFrame, dask_cudf.DataFrame] ], num_nodes_dict: Dict[str, int], single_gpu: bool = True, device_id: int = 0, idtype=None if isinstance(F, MissingModule) else F.int64, ): """ Constructor for creating a object of instance CuGraphStorage See also ``cugraph_dgl.cugraph_storage_from_heterograph`` to convert from DGLHeteroGraph to CuGraphStorage Parameters ---------- data_dict: The dictionary data for constructing a heterogeneous graph. The keys are in the form of string triplets (src_type, edge_type, dst_type), specifying the source node, edge, and destination node types. The values are graph data is a dataframe with 2 columns form of (𝑈,𝑉), where (𝑈[𝑖],𝑉[𝑖]) forms the edge with ID 𝑖. num_nodes_dict: dict[str, int] The number of nodes for some node types, which is a dictionary mapping a node type T to the number of T-typed nodes. single_gpu: bool Whether to create the cugraph Property Graph on a single GPU or multiple GPUs single GPU = True single GPU = False device_id: int If specified, must be the integer ID of the GPU device to have the results being created on idtype: Framework-specific device object, The data type for storing the structure-related graph information this can be ``torch.int32`` or ``torch.int64`` for PyTorch. Defaults to ``torch.int64`` if pytorch is installed Examples -------- The following example uses `CuGraphStorage` : >>> from cugraph_dgl.cugraph_storage import CuGraphStorage >>> import cudf >>> import torch >>> num_nodes_dict={"drug": 3, "gene": 2, "disease": 1} >>> drug_interacts_drug_df = cudf.DataFrame({"src": [0, 1], "dst": [1, 2]}) >>> drug_interacts_gene = cudf.DataFrame({"src": [0, 1], "dst": [0, 1]}) >>> drug_treats_disease = cudf.DataFrame({"src": [1], "dst": [0]}) >>> data_dict = {("drug", "interacts", "drug"):drug_interacts_drug_df, ("drug", "interacts", "gene"):drug_interacts_gene, ("drug", "treats", "disease"):drug_treats_disease } >>> gs = CuGraphStorage(data_dict=data_dict, num_nodes_dict=num_nodes_dict) >>> gs.add_node_data(ntype='drug', feat_name='node_feat', feat_obj=torch.as_tensor([0.1, 0.2, 0.3])) >>> gs.add_edge_data(canonical_etype=("drug", "interacts", "drug"), feat_name='edge_feat', feat_obj=torch.as_tensor([0.2, 0.4])) >>> gs.ntypes ['disease', 'drug', 'gene'] >>> gs.etypes ['interacts', 'interacts', 'treats'] >>> gs.canonical_etypes [('drug', 'interacts', 'drug'), ('drug', 'interacts', 'gene'), ('drug', 'treats', 'disease')] >>> gs.sample_neighbors({'disease':[0]}, 1) Graph(num_nodes={'disease': 1, 'drug': 3, 'gene': 2}, num_edges={('drug', 'interacts', 'drug'): 0, ('drug', 'interacts', 'gene'): 0, ('drug', 'treats', 'disease'): 1}, metagraph=[('drug', 'drug', 'interacts'), ('drug', 'gene', 'interacts'), ('drug', 'disease', 'treats')]) >>> gs.get_node_storage(key='node_feat', ntype='drug').fetch([0,1,2]) tensor([0.1000, 0.2000, 0.3000], device='cuda:0', dtype=torch.float64) >>> es = gs.get_edge_storage(key='edge_feat', etype=('drug', 'interacts', 'drug')) >>> es.fetch([0,1]) tensor([0.2000, 0.4000], device='cuda:0', dtype=torch.float64) """ # Order is very important # do this first before cuda work # Create cuda context on the right gpu, # defaults to gpu-0 import numba.cuda as cuda cuda.select_device(device_id) self.idtype = idtype self.id_np_type = backend_dtype_to_np_dtype_dict[idtype] self.num_nodes_dict = num_nodes_dict self._ntype_offset_d = self.__get_ntype_offset_d(self.num_nodes_dict) # Todo: Can possibly optimize by persisting edge-list # Trade-off memory for run-time self.num_edges_dict = {k: len(v) for k, v in data_dict.items()} self._etype_offset_d = self.__get_etype_offset_d(self.num_edges_dict) self.single_gpu = single_gpu self.ndata_storage = FeatureStore(backend="torch") self.ndata = self.ndata_storage.fd self.edata_storage = FeatureStore(backend="torch") self.edata = self.edata_storage.fd self._etype_range_d = self.__get_etype_range_d( self._etype_offset_d, self.num_canonical_edges_dict ) _edges_dict = add_edge_ids_to_edges_dict( data_dict, self._etype_offset_d, self.id_np_type ) self._edges_dict = add_node_offset_to_edges_dict( _edges_dict, self._ntype_offset_d ) self._etype_id_dict = { etype: etype_id for etype_id, etype in enumerate(self.canonical_etypes) } self.uniform_sampler = None def add_node_data(self, feat_obj: Sequence, ntype: str, feat_name: str): """ Add node features Parameters ---------- df : array_like object The node feature to save in feature store ntype : str The node type to be added. For example, if dataframe contains data about users, ntype might be "users". feat_name : str The name of the feature being stored Returns ------- None """ self.ndata_storage.add_data( feat_obj=feat_obj, type_name=ntype, feat_name=feat_name, ) def add_edge_data( self, feat_obj: Sequence, canonical_etype: Tuple[str, str, str], feat_name: str, ): """ Add edge features Parameters ---------- feat_obj : array_like object The edge feature to save in feature store canonical_etype : Tuple[(str, str, str)] The edge type to be added feat_name : string Returns ------- None """ _assert_valid_canonical_etype(canonical_etype) self.edata_storage.add_data( feat_obj=feat_obj, type_name=canonical_etype, feat_name=feat_name, ) # Sampling Function def sample_neighbors( self, nodes, fanout: int, edge_dir: str = "in", prob: Optional[str] = None, exclude_edges=None, replace: bool = False, output_device=None, ): """ Return a DGLGraph which is a subgraph induced by sampling neighboring edges of the given nodes. See ``dgl.sampling.sample_neighbors`` for detailed semantics. Parameters ---------- nodes : Tensor or dict[str, Tensor] Node IDs to sample neighbors from. This argument can take a single ID tensor or a dictionary of node types and ID tensors. If a single tensor is given, the graph must only have one type of nodes. fanout : int or dict[etype, int] The number of edges to be sampled for each node on each edge type. This argument can take a single int or a dictionary of edge types and ints. If a single int is given, DGL will sample this number of edges for each node for every edge type. If -1 is given for a single edge type, all the neighboring edges with that edge type will be selected. edge_dir: 'in' or 'out' The direction of edges to import prob : str, optional Feature name used as the (un-normalized) probabilities associated with each neighboring edge of a node. The feature must have only one element for each edge. The features must be non-negative floats, and the sum of the features of inbound/outbound edges for every node must be positive (though they don't have to sum up to one). Otherwise, the result will be undefined. If :attr:`prob` is not None, GPU sampling is not supported. exclude_edges: tensor or dict Edge IDs to exclude during sampling neighbors for the seed nodes. This argument can take a single ID tensor or a dictionary of edge types and ID tensors. If a single tensor is given, the graph must only have one type of nodes. replace : bool, optional If True, sample with replacement. output_device : Framework-specific device context object, optional The output device. Default is the same as the input graph. Returns ------- DGLGraph A sampled subgraph with the same nodes as the original graph, but only the sampled neighboring edges. The induced edge IDs will be in ``edata[dgl.EID]``. """ if self.uniform_sampler is None: self.uniform_sampler = DGLUniformSampler( self._edges_dict, self._etype_range_d, self._etype_id_dict, self.single_gpu, ) if prob is not None: raise NotImplementedError( "prob is not currently supported", " for sample_neighbors in CuGraphStorage", ) if exclude_edges is not None: raise NotImplementedError( "exclude_edges is not currently supported", " for sample_neighbors in CuGraphStorage", ) if not isinstance(nodes, dict): if len(self.ntypes) > 1: raise dgl.DGLError( "Must specify node type when the graph is not homogeneous." ) nodes = cp.asarray(nodes) nodes = {self.ntypes[0]: nodes} else: nodes = { k: self.dgl_n_id_to_cugraph_id(F.tensor(n), k) for k, n in nodes.items() } nodes = {k: cp.asarray(F.tensor(n)) for k, n in nodes.items()} sampled_obj = self.uniform_sampler.sample_neighbors( nodes, fanout, edge_dir=edge_dir, prob=prob, replace=replace, ) # heterograph case if len(self.etypes) > 1: graph_data_d, graph_eid_d = self.__convert_to_dgl_tensor_d( sampled_obj, self.idtype ) sampled_graph = dgl.heterograph( data_dict=graph_data_d, num_nodes_dict=self.num_nodes_dict, idtype=self.idtype, ) sampled_graph.edata[dgl.EID] = graph_eid_d else: src_ids, dst_ids, edge_ids = sampled_obj src_ids = torch.as_tensor(src_ids, device="cuda") dst_ids = torch.as_tensor(dst_ids, device="cuda") edge_ids = torch.as_tensor(edge_ids, device="cuda") total_number_of_nodes = self.total_number_of_nodes sampled_graph = dgl.graph( (src_ids, dst_ids), num_nodes=total_number_of_nodes, idtype=self.idtype, ) sampled_graph.edata[dgl.EID] = edge_ids # to device function move the dgl graph to desired devices if output_device is not None: sampled_graph.to(output_device) return sampled_graph # Required in Cluster-GCN def subgraph(self, nodes, relabel_nodes=False, output_device=None): """Return a subgraph induced on given nodes. This has the same semantics as ``dgl.node_subgraph``. Parameters ---------- nodes : nodes or dict[str, nodes] The nodes to form the subgraph. The allowed nodes formats are: * Int Tensor: Each element is a node ID. The tensor must have the same device type and ID data type as the graph's. * iterable[int]: Each element is a node ID. * Bool Tensor: Each :math:`i^{th}` element is a bool flag indicating whether node :math:`i` is in the subgraph. If the graph is homogeneous, directly pass the above formats. Otherwise, the argument must be a dictionary with keys being node types and values being the node IDs in the above formats. relabel_nodes : bool, optional If True, the extracted subgraph will only have the nodes in the specified node set and it will relabel the nodes in order. output_device : Framework-specific device context object, optional The output device. Default is the same as the input graph. Returns ------- DGLGraph The subgraph. """ raise NotImplementedError("subgraph is not implemented yet") # Required in Link Prediction # relabel = F we use dgl functions, # relabel = T, we need to delete nodes and relabel def edge_subgraph(self, edges, relabel_nodes=False, output_device=None): """ Return a subgraph induced on given edges. This has the same semantics as ``dgl.edge_subgraph``. Parameters ---------- edges : edges or dict[(str, str, str), edges] The edges to form the subgraph. The allowed edges formats are: * Int Tensor: Each element is an edge ID. The tensor must have the same device type and ID data type as the graph's. * iterable[int]: Each element is an edge ID. * Bool Tensor: Each :math:`i^{th}` element is a bool flag indicating whether edge :math:`i` is in the subgraph. If the graph is homogeneous, one can directly pass the above formats. Otherwise, the argument must be a dictionary with keys being edge types and values being the edge IDs in the above formats relabel_nodes : bool, optional If True, the extracted subgraph will only have the nodes in the specified node set and it will relabel the nodes in order. output_device : Framework-specific device context object, optional The output device. Default is the same as the input graph. Returns ------- DGLGraph The subgraph. """ raise NotImplementedError("edge_subgraph is not implemented yet") # Required in Link Prediction negative sampler def find_edges( self, eid, etype: Optional[Tuple[str, str, str]] = None, output_device=None ): """ Return the source and destination node ID(s) given the edge ID(s). Parameters ---------- eid : edge ID(s) The edge IDs. The allowed formats are: * ``int``: A single ID. * Int Tensor: Each element is an ID. The tensor must have the same device type and ID data type as the graph's. * iterable[int]: Each element is an ID. etype : Tuple[str, str, str] The type name of the edges. Can be omitted if the graph has only one type of edges. Returns ------- Tensor The source node IDs of the edges. The i-th element is the source node ID of the i-th edge. Tensor The destination node IDs of the edges. The i-th element is the destination node ID of the i-th edge. """ if etype: src_type, connection_type, dst_type = etype eid = self.dgl_e_id_to_cugraph_id(eid, etype) # TODO: implement below src, dst = self.find_edges(eid, etype) src = torch.as_tensor(src, device="cuda") dst = torch.as_tensor(dst, device="cuda") src = self.cugraph_n_id_to_dgl_id(src, src_type) dst = self.cugraph_n_id_to_dgl_id(dst, dst_type) return src, dst # Required in Link Prediction negative sampler def global_uniform_negative_sampling( self, num_samples, exclude_self_loops=True, replace=False, etype=None ): """ Per source negative sampling as in ``dgl.dataloading.GlobalUniform`` """ raise NotImplementedError( "global_uniform_negative_sampling not implemented yet" ) def get_node_storage(self, key: str, ntype: str = None): """ Get storage object of node feature of type :attr:`ntype` and name :attr:`key` """ if ntype is None: if len(self.ntypes) > 1: raise ValueError( "ntype must be provided if multiple ntypes are present in the graph" ) else: ntype = self.ntype[0] return dgl_FeatureStorage(self.ndata_storage, type_name=ntype, feat_name=key) def get_edge_storage(self, key: str, etype: Optional[Tuple[str, str, str]] = None): """ Get storage object of edge feature of type :attr:`ntype` and name :attr:`key` """ if etype is None: if len(self.etypes) > 1: raise ValueError( "etype must be provided if multiple etypes are present in the graph" ) else: etype = self.etypes[0] return dgl_FeatureStorage(self.edata_storage, type_name=etype, feat_name=key) # Number of edges/nodes utils def num_nodes(self, ntype: str = None) -> int: """ Return the number of nodes in the graph. Parameters ---------- ntype : str, optional The node type name. If given, it returns the number of nodes of the type. If not given (default), it returns the total number of nodes of all types. Returns ------- int The number of nodes. """ if ntype: return self.num_nodes_dict[ntype] else: return self.total_number_of_nodes def number_of_nodes(self, ntype: str = None) -> int: """ Return the number of nodes in the graph. Alias of ``num_nodes`` Parameters ---------- ntype : str, optional The node type name. If given, it returns the number of nodes of the type. If not given (default), it returns the total number of nodes of all types. Returns ------- int The number of nodes. """ return self.num_nodes(ntype) @property def ntypes(self) -> Sequence[str]: """ Return all the node type names in the graph. Returns ------- list[str] All the node type names in a list. """ ntypes = list(self.num_nodes_dict.keys()) return ntypes @property def etypes(self) -> Sequence[str]: """ Return all the edge type names in the graph. Returns ------- list[str] All the edge type names in a list. """ return [can_etype[1] for can_etype in self.canonical_etypes] def num_edges(self, etype: Optional[str] = None) -> int: """ Return the number of edges in the graph. Parameters ---------- etype: Returns ------- int The number of edges """ if etype: if etype not in self.canonical_etypes: etype = self.get_corresponding_canonical_etype(etype) return self.num_edges_dict[etype] else: return self.total_number_of_edges @cached_property def total_number_of_edges(self) -> int: return sum(self.num_edges_dict.values()) @cached_property def total_number_of_nodes(self) -> int: return sum(self.num_nodes_dict.values()) @property def num_canonical_edges_dict(self) -> dict[str, int]: return self.num_edges_dict @property def canonical_etypes(self) -> Sequence[Tuple[str, str, str]]: return list(self.num_edges_dict.keys()) @property def device(self): """ Get the device of the graph. Returns ------- device context The device of the graph, which should be a framework-specific device object (e.g., ``torch.device``). """ return torch.cuda.current_device() # Index Conversion Utils def get_node_id_offset(self, ntype: str) -> int: """ Return the integer offset for node id of type ntype """ return self._ntype_offset_d[ntype] def get_edge_id_offset(self, canonical_etype: Tuple[str, str, str]) -> int: """ Return the integer offset for node id of type etype """ _assert_valid_canonical_etype(canonical_etype) return self._etype_offset_d[canonical_etype] def dgl_n_id_to_cugraph_id(self, index_t, ntype: str): return index_t + self.get_node_id_offset(ntype) def cugraph_n_id_to_dgl_id(self, index_t, ntype: str): return index_t - self.get_node_id_offset(ntype) def dgl_e_id_to_cugraph_id(self, index_t, canonical_etype: Tuple[str, str, str]): return index_t + self.get_edge_id_offset(canonical_etype) def cugraph_e_id_to_dgl_id(self, index_t, canonical_etype: Tuple[str, str, str]): return index_t - self.get_edge_id_offset(canonical_etype) # Methods for getting the offsets per type @staticmethod def __get_etype_offset_d(num_canonical_edges_dict): last_st = 0 etype_st_d = {} for etype in sorted(num_canonical_edges_dict.keys()): etype_st_d[etype] = last_st last_st = last_st + num_canonical_edges_dict[etype] return etype_st_d @staticmethod def __get_etype_range_d(etype_offset_d, num_canonical_edges_dict): # dict for edge_id_offset_start etype_range_d = {} for etype, st in etype_offset_d.items(): etype_range_d[etype] = (st, st + num_canonical_edges_dict[etype]) return etype_range_d @staticmethod def __get_ntype_offset_d(num_nodes_dict): # dict for node_id_offset_start last_st = 0 ntype_st_d = {} for ntype in sorted(num_nodes_dict.keys()): ntype_st_d[ntype] = last_st last_st = last_st + num_nodes_dict[ntype] return ntype_st_d def get_corresponding_canonical_etype(self, etype: str) -> str: can_etypes = [ can_etype for can_etype in self.canonical_etypes if can_etype[1] == etype ] if len(can_etypes) > 1: raise dgl.DGLError( f'Edge type "{etype}" is ambiguous. Please use canonical' + "edge type in the form of (srctype, etype, dsttype)" ) return can_etypes[0] def __convert_to_dgl_tensor_d( self, graph_sampled_data_d, o_dtype=None if isinstance(F, MissingModule) else F.int64, ): graph_data_d = {} graph_eid_d = {} for canonical_etype, ( src, dst, edge_id, ) in graph_sampled_data_d.items(): src_type = canonical_etype[0] dst_type = canonical_etype[2] src_t = _torch_tensor_from_cp_array(src) dst_t = _torch_tensor_from_cp_array(dst) edge_id_t = _torch_tensor_from_cp_array(edge_id) src_t = self.cugraph_n_id_to_dgl_id(src_t, src_type) dst_t = self.cugraph_n_id_to_dgl_id(dst_t, dst_type) edge_id_t = self.cugraph_e_id_to_dgl_id(edge_id_t, canonical_etype) graph_data_d[canonical_etype] = (src_t.to(o_dtype), dst_t.to(o_dtype)) graph_eid_d[canonical_etype] = edge_id_t.to(o_dtype) return graph_data_d, graph_eid_d def _torch_tensor_from_cp_array(ar): if len(ar) == 0: return torch.as_tensor(ar.get()).to("cuda") return torch.as_tensor(ar, device="cuda")
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/__init__.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os # to prevent rapids context being created when importing cugraph_dgl os.environ["RAPIDS_NO_INITIALIZE"] = "1" from cugraph_dgl.cugraph_storage import CuGraphStorage from cugraph_dgl.convert import cugraph_storage_from_heterograph import cugraph_dgl.dataloading import cugraph_dgl.nn from cugraph_dgl._version import __git_commit__, __version__
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/VERSION
23.12.00
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/utils/cugraph_storage_utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from cugraph.gnn.dgl_extensions.utils.sampling import eid_n, src_n, dst_n from cugraph.utilities.utils import import_optional, MissingModule dgl = import_optional("dgl") F = import_optional("dgl.backend") def _assert_valid_canonical_etype(canonical_etype): if not _is_valid_canonical_etype: error_message = ( f"Invalid canonical_etype {canonical_etype} " + "canonical etype should be is a string triplet (str, str, str)" + "for source node type, edge type and destination node type" ) raise dgl.DGLError(error_message) def _is_valid_canonical_etype(canonical_etype): if not isinstance(canonical_etype, tuple): return False if len(canonical_etype) != 3: return False for t in canonical_etype: if not isinstance(t, str): return False return True def add_edge_ids_to_edges_dict(edge_data_dict, edge_id_offset_d, id_dtype): eids_data_dict = {} for etype, df in edge_data_dict.items(): # Do not modify input by user if len(df.columns) != 2: raise ValueError( "Provided dataframe in edge_dict contains more than 2 columns", "DataFrame with only 2 columns is supported", "Where first is treated as src and second as dst", ) df = df.copy(deep=False) df = df.rename(columns={df.columns[0]: src_n, df.columns[1]: dst_n}) df[eid_n] = id_dtype(1) df[eid_n] = df[eid_n].cumsum() df[eid_n] = df[eid_n] + edge_id_offset_d[etype] - 1 df[eid_n] = df[eid_n].astype(id_dtype) eids_data_dict[etype] = df return eids_data_dict def add_node_offset_to_edges_dict(edge_data_dict, node_id_offset_d): for etype, df in edge_data_dict.items(): src_type, _, dst_type = etype df[src_n] = df[src_n] + node_id_offset_d[src_type] df[dst_n] = df[dst_n] + node_id_offset_d[dst_type] return edge_data_dict if isinstance(F, MissingModule): backend_dtype_to_np_dtype_dict = MissingModule("dgl") else: backend_dtype_to_np_dtype_dict = { F.bool: bool, F.uint8: np.uint8, F.int8: np.int8, F.int16: np.int16, F.int32: np.int32, F.int64: np.int64, F.float16: np.float16, F.float32: np.float32, F.float64: np.float64, }
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/utils/feature_storage.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from cugraph.gnn import FeatureStore from cugraph.utilities.utils import import_optional torch = import_optional("torch") class dgl_FeatureStorage: """ Storage for node/edge feature data. """ def __init__(self, fs: FeatureStore, type_name: str, feat_name: str): self.fs = fs self.type_name = type_name self.feat_name = feat_name def fetch(self, indices, device=None, pin_memory=False, **kwargs): """Fetch the features of the given node/edge IDs to the given device. Parameters ---------- indices : Tensor Node or edge IDs. device : Device Device context. pin_memory : bool Wether to use pin_memory for fetching features pin_memory=True is currently not supported Returns ------- Tensor Feature data stored in PyTorch Tensor. """ if pin_memory: raise ValueError("pinned memory not supported in dgl_FeatureStorage") if isinstance(indices, torch.Tensor): indices = indices.long() t = self.fs.get_data( indices=indices, type_name=self.type_name, feat_name=self.feat_name ) if device: return t.to(device) else: return t
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/utils/cugraph_conversion_utils.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Utils to convert b/w dgl heterograph to cugraph GraphStore from __future__ import annotations from typing import Dict, Tuple, Union import cudf import pandas as pd import dask.dataframe as dd import dask_cudf from dask.distributed import get_client import cupy as cp from cugraph.utilities.utils import import_optional from cugraph.gnn.dgl_extensions.dgl_uniform_sampler import src_n, dst_n dgl = import_optional("dgl") F = import_optional("dgl.backend") torch = import_optional("torch") # Feature Tensor to DataFrame Utils def convert_to_column_major(t: torch.Tensor): return t.t().contiguous().t() def create_ar_from_tensor(t: torch.Tensor): t = convert_to_column_major(t) if t.device.type == "cuda": ar = cp.asarray(t) else: ar = t.numpy() return ar def _create_edge_frame(src_t: torch.Tensor, dst_t: torch.Tensor, single_gpu: bool): """ Create a edge dataframe from src_t and dst_t """ src_ar = create_ar_from_tensor(src_t) dst_ar = create_ar_from_tensor(dst_t) edge_df = _create_df_from_edge_ar(src_ar, dst_ar, single_gpu=single_gpu) edge_df = edge_df.rename( columns={edge_df.columns[0]: src_n, edge_df.columns[1]: dst_n} ) return edge_df def _create_df_from_edge_ar(src_ar, dst_ar, single_gpu=True): if not single_gpu: nworkers = len(get_client().scheduler_info()["workers"]) npartitions = nworkers * 1 if single_gpu: df = cudf.DataFrame(data={src_n: src_ar, dst_n: dst_ar}) else: if isinstance(src_ar, cp.ndarray): src_ar = src_ar.get() if isinstance(dst_ar, cp.ndarray): dst_ar = dst_ar.get() df = pd.DataFrame(data={src_n: src_ar, dst_n: dst_ar}) # Only save stuff in host memory df = dd.from_pandas(df, npartitions=npartitions).persist() df = df.map_partitions(cudf.DataFrame.from_pandas) df = df.reset_index(drop=True) return df def get_edges_dict_from_dgl_HeteroGraph( graph: dgl.DGLHeteroGraph, single_gpu: bool ) -> Dict[Tuple[str, str, str], Union[cudf.DataFrame, dask_cudf.DataFrame]]: etype_d = {} for can_etype in graph.canonical_etypes: src_t, dst_t = graph.edges(form="uv", etype=can_etype) etype_d[can_etype] = _create_edge_frame(src_t, dst_t, single_gpu) return etype_d def add_ndata_from_dgl_HeteroGraph(gs, g): for feat_name, feat in g.ndata.items(): if isinstance(feat, torch.Tensor): assert len(g.ntypes) == 1 ntype = g.ntypes[0] gs.ndata_storage.add_data( feat_name=feat_name, type_name=ntype, feat_obj=feat ) else: for ntype, feat_t in feat.items(): gs.ndata_storage.add_data( feat_name=feat_name, type_name=ntype, feat_obj=feat_t ) def add_edata_from_dgl_HeteroGraph(gs, g): for feat_name, feat in g.edata.items(): if isinstance(feat, torch.Tensor): assert len(g.etypes) == 1 etype = g.etypes[0] gs.edata_storage.add_data( feat_name=feat_name, type_name=etype, feat_obj=feat ) else: for etype, feat_t in feat.items(): gs.edata_storage.add_data( feat_name=feat_name, type_name=etype, feat_obj=feat_t )
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/utils/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .conv import * # noqa
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/gatconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Tuple, Union from cugraph_dgl.nn.conv.base import BaseConv, SparseGraph from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") nn = import_optional("torch.nn") ops_torch = import_optional("pylibcugraphops.pytorch") class GATConv(BaseConv): r"""Graph attention layer from `Graph Attention Network <https://arxiv.org/pdf/1710.10903.pdf>`__, with the sparse aggregation accelerated by cugraph-ops. Parameters ---------- in_feats : int or tuple Input feature size. A pair denotes feature sizes of source and destination nodes. out_feats : int Output feature size. num_heads : int Number of heads in multi-head attention. feat_drop : float, optional Dropout rate on feature. Defaults: ``0``. concat : bool, optional If False, the multi-head attentions are averaged instead of concatenated. Default: ``True``. edge_feats : int, optional Edge feature size. Default: ``None``. negative_slope : float, optional LeakyReLU angle of negative slope. Defaults: ``0.2``. residual : bool, optional If True, use residual connection. Defaults: ``False``. allow_zero_in_degree : bool, optional If there are 0-in-degree nodes in the graph, output for those nodes will be invalid since no message will be passed to those nodes. This is harmful for some applications causing silent performance regression. This module will raise a DGLError if it detects 0-in-degree nodes in input graph. By setting ``True``, it will suppress the check and let the users handle it by themselves. Defaults: ``False``. bias : bool, optional If True, learns a bias term. Defaults: ``True``. Examples -------- >>> import dgl >>> import torch >>> from cugraph_dgl.nn import GATConv ... >>> device = 'cuda' >>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3])).to(device) >>> g = dgl.add_self_loop(g) >>> feat = torch.ones(6, 10).to(device) >>> conv = GATConv(10, 2, num_heads=3).to(device) >>> res = conv(g, feat) >>> res tensor([[[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]], [[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]], [[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]], [[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]], [[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]], [[ 0.2340, 1.9226], [ 1.6477, -1.9986], [ 1.1138, -1.9302]]], device='cuda:0', grad_fn=<ViewBackward0>) """ def __init__( self, in_feats: Union[int, Tuple[int, int]], out_feats: int, num_heads: int, feat_drop: float = 0.0, concat: bool = True, edge_feats: Optional[int] = None, negative_slope: float = 0.2, residual: bool = False, allow_zero_in_degree: bool = False, bias: bool = True, ): super().__init__() self.in_feats = in_feats self.out_feats = out_feats self.in_feats_src, self.in_feats_dst = dgl.utils.expand_as_pair(in_feats) self.num_heads = num_heads self.feat_drop = nn.Dropout(feat_drop) self.concat = concat self.edge_feats = edge_feats self.negative_slope = negative_slope self.allow_zero_in_degree = allow_zero_in_degree if isinstance(in_feats, int): self.lin = nn.Linear(in_feats, num_heads * out_feats, bias=False) else: self.lin_src = nn.Linear( self.in_feats_src, num_heads * out_feats, bias=False ) self.lin_dst = nn.Linear( self.in_feats_dst, num_heads * out_feats, bias=False ) if edge_feats is not None: self.lin_edge = nn.Linear(edge_feats, num_heads * out_feats, bias=False) self.attn_weights = nn.Parameter(torch.Tensor(3 * num_heads * out_feats)) else: self.register_parameter("lin_edge", None) self.attn_weights = nn.Parameter(torch.Tensor(2 * num_heads * out_feats)) if bias and concat: self.bias = nn.Parameter(torch.Tensor(num_heads, out_feats)) elif bias and not concat: self.bias = nn.Parameter(torch.Tensor(out_feats)) else: self.register_buffer("bias", None) self.residual = residual and self.in_feats_dst != out_feats * num_heads if self.residual: self.lin_res = nn.Linear( self.in_feats_dst, num_heads * out_feats, bias=bias ) else: self.register_buffer("lin_res", None) self.reset_parameters() def reset_parameters(self): r"""Reinitialize learnable parameters.""" gain = nn.init.calculate_gain("relu") if hasattr(self, "lin"): nn.init.xavier_normal_(self.lin.weight, gain=gain) else: nn.init.xavier_normal_(self.lin_src.weight, gain=gain) nn.init.xavier_normal_(self.lin_dst.weight, gain=gain) nn.init.xavier_normal_( self.attn_weights.view(-1, self.num_heads, self.out_feats), gain=gain ) if self.lin_edge is not None: self.lin_edge.reset_parameters() if self.lin_res is not None: self.lin_res.reset_parameters() if self.bias is not None: nn.init.zeros_(self.bias) def forward( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], nfeat: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], efeat: Optional[torch.Tensor] = None, max_in_degree: Optional[int] = None, ) -> torch.Tensor: r"""Forward computation. Parameters ---------- graph : DGLGraph or SparseGraph The graph. nfeat : torch.Tensor Input features of shape :math:`(N, D_{in})`. efeat: torch.Tensor, optional Optional edge features. max_in_degree : int Maximum in-degree of destination nodes. When :attr:`g` is generated from a neighbor sampler, the value should be set to the corresponding :attr:`fanout`. This option is used to invoke the MFG-variant of cugraph-ops kernel. Returns ------- torch.Tensor The output feature of shape :math:`(N, H, D_{out})` where :math:`H` is the number of heads, and :math:`D_{out}` is size of output feature. """ if isinstance(g, dgl.DGLHeteroGraph): if not self.allow_zero_in_degree: if (g.in_degrees() == 0).any(): raise dgl.base.DGLError( "There are 0-in-degree nodes in the graph, " "output for those nodes will be invalid. " "This is harmful for some applications, " "causing silent performance regression. " "Adding self-loop on the input graph by " "calling `g = dgl.add_self_loop(g)` will resolve " "the issue. Setting ``allow_zero_in_degree`` " "to be `True` when constructing this module will " "suppress the check and let the code run." ) bipartite = isinstance(nfeat, (list, tuple)) _graph = self.get_cugraph_ops_CSC( g, is_bipartite=bipartite, max_in_degree=max_in_degree ) if bipartite: nfeat = (self.feat_drop(nfeat[0]), self.feat_drop(nfeat[1])) nfeat_dst_orig = nfeat[1] else: nfeat = self.feat_drop(nfeat) nfeat_dst_orig = nfeat[: g.num_dst_nodes()] if efeat is not None: if self.lin_edge is None: raise RuntimeError( f"{self.__class__.__name__}.edge_feats must be set to " f"accept edge features." ) efeat = self.lin_edge(efeat) if bipartite: if not hasattr(self, "lin_src"): raise RuntimeError( f"{self.__class__.__name__}.in_feats must be a pair of " f"integers to allow bipartite node features, but got " f"{self.in_feats}." ) nfeat_src = self.lin_src(nfeat[0]) nfeat_dst = self.lin_dst(nfeat[1]) else: if not hasattr(self, "lin"): raise RuntimeError( f"{self.__class__.__name__}.in_feats is expected to be an " f"integer, but got {self.in_feats}." ) nfeat = self.lin(nfeat) out = ops_torch.operators.mha_gat_n2n( (nfeat_src, nfeat_dst) if bipartite else nfeat, self.attn_weights, _graph, num_heads=self.num_heads, activation="LeakyReLU", negative_slope=self.negative_slope, concat_heads=self.concat, edge_feat=efeat, )[: g.num_dst_nodes()] if self.concat: out = out.view(-1, self.num_heads, self.out_feats) if self.residual: res = self.lin_res(nfeat_dst_orig).view(-1, self.num_heads, self.out_feats) if not self.concat: res = res.mean(dim=1) out = out + res if self.bias is not None: out = out + self.bias return out
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/relgraphconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import Optional, Union from cugraph_dgl.nn.conv.base import BaseConv, SparseGraph from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") nn = import_optional("torch.nn") ops_torch = import_optional("pylibcugraphops.pytorch") class RelGraphConv(BaseConv): r"""An accelerated relational graph convolution layer from `Modeling Relational Data with Graph Convolutional Networks <https://arxiv.org/abs/1703.06103>`__, with the sparse aggregation accelerated by cugraph-ops. Parameters ---------- in_feats : int Input feature size. out_feats : int Output feature size. num_rels : int Number of relations. regularizer : str, optional Which weight regularizer to use ("basis" or ``None``): - "basis" is for basis-decomposition. - ``None`` applies no regularization. Default: ``None``. num_bases : int, optional Number of bases. It comes into effect when a regularizer is applied. Default: ``None``. bias : bool, optional True if bias is added. Default: ``True``. self_loop : bool, optional True to include self loop message. Default: ``True``. dropout : float, optional Dropout rate. Default: ``0.0``. apply_norm : bool, optional True to normalize aggregation output by the in-degree of the destination node per edge type, i.e. :math:`|\mathcal{N}^r_i|`. Default: ``True``. Examples -------- >>> import dgl >>> import torch >>> from cugraph_dgl.nn import RelGraphConv ... >>> device = 'cuda' >>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3])).to(device) >>> feat = torch.ones(6, 10).to(device) >>> conv = RelGraphConv( ... 10, 2, 3, regularizer='basis', num_bases=2).to(device) >>> etypes = torch.tensor([0,1,2,0,1,2]).to(device) >>> res = conv(g, feat, etypes) >>> res tensor([[-1.7774, -2.0184], [-1.4335, -2.3758], [-1.7774, -2.0184], [-0.4698, -3.0876], [-1.4335, -2.3758], [-1.4331, -2.3295]], device='cuda:0', grad_fn=<AddBackward0>) """ def __init__( self, in_feats: int, out_feats: int, num_rels: int, regularizer: Optional[str] = None, num_bases: Optional[int] = None, bias: bool = True, self_loop: bool = True, dropout: float = 0.0, apply_norm: bool = False, ): super().__init__() self.in_feats = in_feats self.out_feats = out_feats self.num_rels = num_rels self.apply_norm = apply_norm self.dropout = nn.Dropout(dropout) dim_self_loop = 1 if self_loop else 0 self.self_loop = self_loop if regularizer is None: self.W = nn.Parameter( torch.Tensor(num_rels + dim_self_loop, in_feats, out_feats) ) self.coeff = None elif regularizer == "basis": if num_bases is None: raise ValueError('Missing "num_bases" for basis regularization.') self.W = nn.Parameter( torch.Tensor(num_bases + dim_self_loop, in_feats, out_feats) ) self.coeff = nn.Parameter(torch.Tensor(num_rels, num_bases)) self.num_bases = num_bases else: raise ValueError( f"Supported regularizer options: 'basis' or None, but got " f"'{regularizer}'." ) self.regularizer = regularizer if bias: self.bias = nn.Parameter(torch.Tensor(out_feats)) else: self.register_parameter("bias", None) self.reset_parameters() def reset_parameters(self): r"""Reinitialize learnable parameters.""" bound = 1 / math.sqrt(self.in_feats) end = -1 if self.self_loop else None nn.init.uniform_(self.W[:end], -bound, bound) if self.regularizer == "basis": nn.init.xavier_uniform_(self.coeff, gain=nn.init.calculate_gain("relu")) if self.self_loop: nn.init.xavier_uniform_(self.W[-1], nn.init.calculate_gain("relu")) if self.bias is not None: nn.init.zeros_(self.bias) def forward( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], feat: torch.Tensor, etypes: torch.Tensor, max_in_degree: Optional[int] = None, ) -> torch.Tensor: r"""Forward computation. Parameters ---------- g : DGLGraph The graph. feat : torch.Tensor A 2D tensor of node features. Shape: :math:`(|V|, D_{in})`. etypes : torch.Tensor A 1D integer tensor of edge types. Shape: :math:`(|E|,)`. Note that cugraph-ops only accepts edge type tensors in int32, so any input of other integer types will be casted into int32, thus introducing some overhead. Pass in int32 tensors directly for best performance. max_in_degree : int Maximum in-degree of destination nodes. When :attr:`g` is generated from a neighbor sampler, the value should be set to the corresponding :attr:`fanout`. This option is used to invoke the MFG-variant of cugraph-ops kernel. Returns ------- torch.Tensor New node features. Shape: :math:`(|V|, D_{out})`. """ _graph = self.get_cugraph_ops_HeteroCSC( g, num_edge_types=self.num_rels, etypes=etypes, is_bipartite=False, max_in_degree=max_in_degree, ) h = ops_torch.operators.agg_hg_basis_n2n_post( feat, self.coeff, _graph, concat_own=self.self_loop, norm_by_out_degree=self.apply_norm, )[: g.num_dst_nodes()] h = h @ self.W.view(-1, self.out_feats) if self.bias is not None: h = h + self.bias h = self.dropout(h) return h
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/gatv2conv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Tuple, Union from cugraph_dgl.nn.conv.base import BaseConv, SparseGraph from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") nn = import_optional("torch.nn") ops_torch = import_optional("pylibcugraphops.pytorch") class GATv2Conv(BaseConv): r"""GATv2 from `How Attentive are Graph Attention Networks? <https://arxiv.org/pdf/2105.14491.pdf>`__, with the sparse aggregation accelerated by cugraph-ops. Parameters ---------- in_feats : int, or pair of ints Input feature size; i.e, the number of dimensions of :math:`h_i^{(l)}`. If the layer is to be applied to a unidirectional bipartite graph, `in_feats` specifies the input feature size on both the source and destination nodes. If a scalar is given, the source and destination node feature size would take the same value. out_feats : int Output feature size; i.e, the number of dimensions of :math:`h_i^{(l+1)}`. num_heads : int Number of heads in Multi-Head Attention. feat_drop : float, optional Dropout rate on feature. Defaults: ``0``. concat : bool, optional If False, the multi-head attentions are averaged instead of concatenated. Default: ``True``. edge_feats : int, optional Edge feature size. Default: ``None``. negative_slope : float, optional LeakyReLU angle of negative slope. Defaults: ``0.2``. residual : bool, optional If True, use residual connection. Defaults: ``False``. allow_zero_in_degree : bool, optional If there are 0-in-degree nodes in the graph, output for those nodes will be invalid since no message will be passed to those nodes. This is harmful for some applications causing silent performance regression. This module will raise a DGLError if it detects 0-in-degree nodes in input graph. By setting ``True``, it will suppress the check and let the users handle it by themselves. Defaults: ``False``. bias : bool, optional If set to :obj:`False`, the layer will not learn an additive bias. (default: :obj:`True`) share_weights : bool, optional If set to :obj:`True`, the same matrix for :math:`W_{left}` and :math:`W_{right}` in the above equations, will be applied to the source and the target node of every edge. (default: :obj:`False`) """ def __init__( self, in_feats: Union[int, Tuple[int, int]], out_feats: int, num_heads: int, feat_drop: float = 0.0, concat: bool = True, edge_feats: Optional[int] = None, negative_slope: float = 0.2, residual: bool = False, allow_zero_in_degree: bool = False, bias: bool = True, share_weights: bool = False, ): super().__init__() self.in_feats = in_feats self.out_feats = out_feats self.in_feats_src, self.in_feats_dst = dgl.utils.expand_as_pair(in_feats) self.num_heads = num_heads self.feat_drop = nn.Dropout(feat_drop) self.concat = concat self.edge_feats = edge_feats self.negative_slope = negative_slope self.allow_zero_in_degree = allow_zero_in_degree self.share_weights = share_weights self.lin_src = nn.Linear(self.in_feats_src, num_heads * out_feats, bias=bias) if share_weights: if self.in_feats_src != self.in_feats_dst: raise ValueError( f"Input feature size of source and destination " f"nodes must be identical when share_weights is enabled, " f"but got {self.in_feats_src} and {self.in_feats_dst}." ) self.lin_dst = self.lin_src else: self.lin_dst = nn.Linear( self.in_feats_dst, num_heads * out_feats, bias=bias ) self.attn = nn.Parameter(torch.Tensor(num_heads * out_feats)) if edge_feats is not None: self.lin_edge = nn.Linear(edge_feats, num_heads * out_feats, bias=False) else: self.register_parameter("lin_edge", None) if bias and concat: self.bias = nn.Parameter(torch.Tensor(num_heads, out_feats)) elif bias and not concat: self.bias = nn.Parameter(torch.Tensor(out_feats)) else: self.register_buffer("bias", None) self.residual = residual and self.in_feats_dst != out_feats * num_heads if self.residual: self.lin_res = nn.Linear( self.in_feats_dst, num_heads * out_feats, bias=bias ) else: self.register_buffer("lin_res", None) self.reset_parameters() def reset_parameters(self): r"""Reinitialize learnable parameters.""" gain = nn.init.calculate_gain("relu") nn.init.xavier_normal_(self.lin_src.weight, gain=gain) nn.init.xavier_normal_(self.lin_dst.weight, gain=gain) nn.init.xavier_normal_( self.attn.view(-1, self.num_heads, self.out_feats), gain=gain ) if self.lin_edge is not None: self.lin_edge.reset_parameters() if self.lin_res is not None: self.lin_res.reset_parameters() if self.bias is not None: nn.init.zeros_(self.bias) def forward( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], nfeat: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], efeat: Optional[torch.Tensor] = None, max_in_degree: Optional[int] = None, ) -> torch.Tensor: r"""Forward computation. Parameters ---------- graph : DGLGraph or SparseGraph The graph. nfeat : torch.Tensor Input features of shape :math:`(N, D_{in})`. efeat: torch.Tensor, optional Optional edge features. max_in_degree : int Maximum in-degree of destination nodes. When :attr:`g` is generated from a neighbor sampler, the value should be set to the corresponding :attr:`fanout`. This option is used to invoke the MFG-variant of cugraph-ops kernel. Returns ------- torch.Tensor The output feature of shape :math:`(N, H, D_{out})` where :math:`H` is the number of heads, and :math:`D_{out}` is size of output feature. """ if isinstance(g, dgl.DGLHeteroGraph): if not self.allow_zero_in_degree: if (g.in_degrees() == 0).any(): raise dgl.base.DGLError( "There are 0-in-degree nodes in the graph, " "output for those nodes will be invalid. " "This is harmful for some applications, " "causing silent performance regression. " "Adding self-loop on the input graph by " "calling `g = dgl.add_self_loop(g)` will resolve " "the issue. Setting ``allow_zero_in_degree`` " "to be `True` when constructing this module will " "suppress the check and let the code run." ) nfeat_bipartite = isinstance(nfeat, (list, tuple)) graph_bipartite = nfeat_bipartite or self.share_weights is False _graph = self.get_cugraph_ops_CSC( g, is_bipartite=graph_bipartite, max_in_degree=max_in_degree ) if nfeat_bipartite: nfeat = (self.feat_drop(nfeat[0]), self.feat_drop(nfeat[1])) nfeat_dst_orig = nfeat[1] else: nfeat = self.feat_drop(nfeat) nfeat_dst_orig = nfeat[: g.num_dst_nodes()] if efeat is not None: if self.lin_edge is None: raise RuntimeError( f"{self.__class__.__name__}.edge_feats must be set to " f"accept edge features." ) efeat = self.lin_edge(efeat) if nfeat_bipartite: nfeat = (self.lin_src(nfeat[0]), self.lin_dst(nfeat[1])) elif graph_bipartite: nfeat = (self.lin_src(nfeat), self.lin_dst(nfeat[: g.num_dst_nodes()])) else: nfeat = self.lin_src(nfeat) out = ops_torch.operators.mha_gat_v2_n2n( nfeat, self.attn, _graph, num_heads=self.num_heads, activation="LeakyReLU", negative_slope=self.negative_slope, concat_heads=self.concat, edge_feat=efeat, )[: g.num_dst_nodes()] if self.concat: out = out.view(-1, self.num_heads, self.out_feats) if self.residual: res = self.lin_res(nfeat_dst_orig).view(-1, self.num_heads, self.out_feats) if not self.concat: res = res.mean(dim=1) out = out + res if self.bias is not None: out = out + self.bias return out
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/sageconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Tuple, Union from cugraph_dgl.nn.conv.base import BaseConv, SparseGraph from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") nn = import_optional("torch.nn") ops_torch = import_optional("pylibcugraphops.pytorch") class SAGEConv(BaseConv): r"""An accelerated GraphSAGE layer from `Inductive Representation Learning on Large Graphs <https://arxiv.org/pdf/1706.02216.pdf>`, with the sparse aggregation accelerated by cugraph-ops. Parameters ---------- in_feats : int or tuple Input feature size. If a scalar is given, the source and destination nodes are required to be the same. out_feats : int Output feature size. aggregator_type : str Aggregator type to use ("mean", "sum", "min", "max", "pool", "gcn"). feat_drop : float Dropout rate on features, default: ``0``. bias : bool If True, adds a learnable bias to the output. Default: ``True``. Examples -------- >>> import dgl >>> import torch >>> from cugraph_dgl.nn import SAGEConv ... >>> device = 'cuda' >>> g = dgl.graph(([0,1,2,3,2,5], [1,2,3,4,0,3])).to(device) >>> g = dgl.add_self_loop(g) >>> feat = torch.ones(6, 10).to(device) >>> conv = SAGEConv(10, 2, 'mean').to(device) >>> res = conv(g, feat) >>> res tensor([[-1.1690, 0.1952], [-1.1690, 0.1952], [-1.1690, 0.1952], [-1.1690, 0.1952], [-1.1690, 0.1952], [-1.1690, 0.1952]], device='cuda:0', grad_fn=<AddmmBackward0>) """ valid_aggr_types = {"mean", "sum", "min", "max", "pool", "gcn"} def __init__( self, in_feats: Union[int, Tuple[int, int]], out_feats: int, aggregator_type: str = "mean", feat_drop: float = 0.0, bias: bool = True, ): super().__init__() if aggregator_type not in self.valid_aggr_types: raise ValueError( f"Invalid aggregator_type. Must be one of {self.valid_aggr_types}. " f"But got '{aggregator_type}' instead." ) self.aggregator_type = aggregator_type self._aggr = aggregator_type self.in_feats = in_feats self.out_feats = out_feats self.in_feats_src, self.in_feats_dst = dgl.utils.expand_as_pair(in_feats) self.feat_drop = nn.Dropout(feat_drop) if self.aggregator_type == "gcn": self._aggr = "mean" self.lin = nn.Linear(self.in_feats_src, out_feats, bias=bias) else: self.lin = nn.Linear( self.in_feats_src + self.in_feats_dst, out_feats, bias=bias ) if self.aggregator_type == "pool": self._aggr = "max" self.pre_lin = nn.Linear(self.in_feats_src, self.in_feats_src) else: self.register_parameter("pre_lin", None) self.reset_parameters() def reset_parameters(self): r"""Reinitialize learnable parameters.""" self.lin.reset_parameters() if self.pre_lin is not None: self.pre_lin.reset_parameters() def forward( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], feat: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], max_in_degree: Optional[int] = None, ) -> torch.Tensor: r"""Forward computation. Parameters ---------- g : DGLGraph or SparseGraph The graph. feat : torch.Tensor or tuple Node features. Shape: :math:`(|V|, D_{in})`. max_in_degree : int Maximum in-degree of destination nodes. When :attr:`g` is generated from a neighbor sampler, the value should be set to the corresponding :attr:`fanout`. This option is used to invoke the MFG-variant of cugraph-ops kernel. Returns ------- torch.Tensor Output node features. Shape: :math:`(|V|, D_{out})`. """ feat_bipartite = isinstance(feat, (list, tuple)) graph_bipartite = feat_bipartite or self.aggregator_type == "pool" _graph = self.get_cugraph_ops_CSC( g, is_bipartite=graph_bipartite, max_in_degree=max_in_degree ) if feat_bipartite: feat = (self.feat_drop(feat[0]), self.feat_drop(feat[1])) else: feat = self.feat_drop(feat) if self.aggregator_type == "pool": if feat_bipartite: feat = (self.pre_lin(feat[0]).relu(), feat[1]) else: feat = (self.pre_lin(feat).relu(), feat[: g.num_dst_nodes()]) # force ctx.needs_input_grad=True in cugraph-ops autograd function feat[0].requires_grad_() feat[1].requires_grad_() out = ops_torch.operators.agg_concat_n2n(feat, _graph, self._aggr)[ : g.num_dst_nodes() ] if self.aggregator_type == "gcn": out = out[:, : self.in_feats_src] out = self.lin(out) return out
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/transformerconv.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Tuple, Union from cugraph_dgl.nn.conv.base import BaseConv, SparseGraph from cugraph.utilities.utils import import_optional dgl = import_optional("dgl") torch = import_optional("torch") nn = import_optional("torch.nn") ops_torch = import_optional("pylibcugraphops.pytorch") class TransformerConv(BaseConv): r"""The graph transformer layer from the `"Masked Label Prediction: Unified Message Passing Model for Semi-Supervised Classification" <https://arxiv.org/abs/2009.03509>`_ paper. Parameters ---------- in_node_feats : int or pair of ints Input feature size. A pair denotes feature sizes of source and destination nodes. out_node_feats : int Output feature size. num_heads : int Number of multi-head-attentions. concat : bool, optional If False, the multi-head attentions are averaged instead of concatenated. Default: ``True``. beta : bool, optional If True, use a gated residual connection. Default: ``True``. edge_feats: int, optional Edge feature size. Default: ``None``. bias: bool, optional If True, learns a bias term. Default: ``True``. root_weight: bool, optional If False, will skip to learn a root weight matrix. Default: ``True``. """ def __init__( self, in_node_feats: Union[int, Tuple[int, int]], out_node_feats: int, num_heads: int, concat: bool = True, beta: bool = False, edge_feats: Optional[int] = None, bias: bool = True, root_weight: bool = True, ): super().__init__() self.in_node_feats = in_node_feats self.out_node_feats = out_node_feats self.num_heads = num_heads self.concat = concat self.beta = beta self.edge_feats = edge_feats self.bias = bias self.root_weight = root_weight if isinstance(in_node_feats, int): in_node_feats = (in_node_feats, in_node_feats) self.lin_key = nn.Linear(in_node_feats[0], num_heads * out_node_feats) self.lin_query = nn.Linear(in_node_feats[1], num_heads * out_node_feats) self.lin_value = nn.Linear(in_node_feats[0], num_heads * out_node_feats) if edge_feats is not None: self.lin_edge = nn.Linear( edge_feats, num_heads * out_node_feats, bias=False ) else: self.lin_edge = self.register_parameter("lin_edge", None) if concat: self.lin_skip = nn.Linear( in_node_feats[1], num_heads * out_node_feats, bias=bias ) if self.beta: self.lin_beta = nn.Linear(3 * num_heads * out_node_feats, 1, bias=bias) else: self.lin_beta = self.register_parameter("lin_beta", None) else: self.lin_skip = nn.Linear(in_node_feats[1], out_node_feats, bias=bias) if self.beta: self.lin_beta = nn.Linear(3 * out_node_feats, 1, bias=False) else: self.lin_beta = self.register_parameter("lin_beta", None) self.reset_parameters() def reset_parameters(self): self.lin_key.reset_parameters() self.lin_query.reset_parameters() self.lin_value.reset_parameters() if self.lin_edge is not None: self.lin_edge.reset_parameters() if self.lin_skip is not None: self.lin_skip.reset_parameters() if self.lin_beta is not None: self.lin_beta.reset_parameters() def forward( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], nfeat: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], efeat: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Forward computation. Parameters ---------- g: DGLGraph The graph. nfeat: torch.Tensor or a pair of torch.Tensor Node feature tensor. A pair denotes features for source and destination nodes, respectively. efeat: torch.Tensor, optional Edge feature tensor. Default: ``None``. """ feat_bipartite = isinstance(nfeat, (list, tuple)) if not feat_bipartite: nfeat = (nfeat, nfeat) _graph = self.get_cugraph_ops_CSC(g, is_bipartite=True) query = self.lin_query(nfeat[1][: g.num_dst_nodes()]) key = self.lin_key(nfeat[0]) value = self.lin_value(nfeat[0]) if efeat is not None: if self.lin_edge is None: raise RuntimeError( f"{self.__class__.__name__}.edge_feats must be set to allow " f"edge features." ) efeat = self.lin_edge(efeat) out = ops_torch.operators.mha_simple_n2n( key_emb=key, query_emb=query, value_emb=value, graph=_graph, num_heads=self.num_heads, concat_heads=self.concat, edge_emb=efeat, norm_by_dim=True, score_bias=None, )[: g.num_dst_nodes()] if self.root_weight: res = self.lin_skip(nfeat[1][: g.num_dst_nodes()]) if self.lin_beta is not None: beta = self.lin_beta(torch.cat([out, res, out - res], dim=-1)) beta = beta.sigmoid() out = beta * res + (1 - beta) * out else: out = out + res return out
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .base import SparseGraph from .gatconv import GATConv from .gatv2conv import GATv2Conv from .relgraphconv import RelGraphConv from .sageconv import SAGEConv from .transformerconv import TransformerConv __all__ = [ "SparseGraph", "GATConv", "GATv2Conv", "RelGraphConv", "SAGEConv", "TransformerConv", ]
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/nn/conv/base.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, Tuple, Union from cugraph.utilities.utils import import_optional torch = import_optional("torch") ops_torch = import_optional("pylibcugraphops.pytorch") dgl = import_optional("dgl") def compress_ids(ids: torch.Tensor, size: int) -> torch.Tensor: return torch._convert_indices_from_coo_to_csr( ids, size, out_int32=ids.dtype == torch.int32 ) def decompress_ids(c_ids: torch.Tensor) -> torch.Tensor: ids = torch.arange(c_ids.numel() - 1, dtype=c_ids.dtype, device=c_ids.device) return ids.repeat_interleave(c_ids[1:] - c_ids[:-1]) class SparseGraph(object): r"""A class to create and store different sparse formats needed by cugraph-ops. It always creates a CSC representation and can provide COO- or CSR-format if needed. Parameters ---------- size: tuple of int Size of the adjacency matrix: (num_src_nodes, num_dst_nodes). src_ids: torch.Tensor Source indices of the edges. dst_ids: torch.Tensor, optional Destination indices of the edges. csrc_ids: torch.Tensor, optional Compressed source indices. It is a monotonically increasing array of size (num_src_nodes + 1,). For the k-th source node, its neighborhood consists of the destinations between `dst_indices[csrc_indices[k]]` and `dst_indices[csrc_indices[k+1]]`. cdst_ids: torch.Tensor, optional Compressed destination indices. It is a monotonically increasing array of size (num_dst_nodes + 1,). For the k-th destination node, its neighborhood consists of the sources between `src_indices[cdst_indices[k]]` and `src_indices[cdst_indices[k+1]]`. values: torch.Tensor, optional Values on the edges. is_sorted: bool Whether the COO inputs (src_ids, dst_ids, values) have been sorted by `dst_ids` in an ascending order. CSC layout creation is much faster when sorted. formats: str or tuple of str, optional The desired sparse formats to create for the graph. The formats tuple must include "csc". Default: "csc". reduce_memory: bool, optional When set, the tensors are not required by the desired formats will be set to `None`. Default: True. Notes ----- For MFGs (sampled graphs), the node ids must have been renumbered. """ supported_formats = { "coo": ("_src_ids", "_dst_ids"), "csc": ("_cdst_ids", "_src_ids"), "csr": ("_csrc_ids", "_dst_ids", "_perm_csc2csr"), } all_tensors = set( [ "_src_ids", "_dst_ids", "_csrc_ids", "_cdst_ids", "_perm_coo2csc", "_perm_csc2csr", ] ) def __init__( self, size: Tuple[int, int], src_ids: torch.Tensor, dst_ids: Optional[torch.Tensor] = None, csrc_ids: Optional[torch.Tensor] = None, cdst_ids: Optional[torch.Tensor] = None, values: Optional[torch.Tensor] = None, is_sorted: bool = False, formats: Union[str, Tuple[str]] = "csc", reduce_memory: bool = True, ): self._num_src_nodes, self._num_dst_nodes = size self._is_sorted = is_sorted if dst_ids is None and cdst_ids is None: raise ValueError( "One of 'dst_ids' and 'cdst_ids' must be given " "to create a SparseGraph." ) if src_ids is not None: src_ids = src_ids.contiguous() if dst_ids is not None: dst_ids = dst_ids.contiguous() if csrc_ids is not None: if csrc_ids.numel() != self._num_src_nodes + 1: raise RuntimeError( f"Size mismatch for 'csrc_ids': expected ({size[0]+1},), " f"but got {tuple(csrc_ids.size())}" ) csrc_ids = csrc_ids.contiguous() if cdst_ids is not None: if cdst_ids.numel() != self._num_dst_nodes + 1: raise RuntimeError( f"Size mismatch for 'cdst_ids': expected ({size[1]+1},), " f"but got {tuple(cdst_ids.size())}" ) cdst_ids = cdst_ids.contiguous() if values is not None: values = values.contiguous() self._src_ids = src_ids self._dst_ids = dst_ids self._csrc_ids = csrc_ids self._cdst_ids = cdst_ids self._values = values self._perm_coo2csc = None self._perm_csc2csr = None if isinstance(formats, str): formats = (formats,) self._formats = formats if "csc" not in formats: raise ValueError( f"{self.__class__.__name__}.formats must contain " f"'csc', but got {formats}." ) # always create csc first if self._cdst_ids is None: if not self._is_sorted: self._dst_ids, self._perm_coo2csc = torch.sort(self._dst_ids) self._src_ids = self._src_ids[self._perm_coo2csc] if self._values is not None: self._values = self._values[self._perm_coo2csc] self._cdst_ids = compress_ids(self._dst_ids, self._num_dst_nodes) for format_ in formats: assert format_ in SparseGraph.supported_formats self.__getattribute__(f"{format_}")() self._reduce_memory = reduce_memory if reduce_memory: self.reduce_memory() def reduce_memory(self): """Remove the tensors that are not necessary to create the desired sparse formats to reduce memory footprint.""" if self._formats is None: return tensors_needed = [] for f in self._formats: tensors_needed += SparseGraph.supported_formats[f] for t in SparseGraph.all_tensors.difference(set(tensors_needed)): self.__dict__[t] = None def src_ids(self) -> torch.Tensor: return self._src_ids def cdst_ids(self) -> torch.Tensor: return self._cdst_ids def dst_ids(self) -> torch.Tensor: if self._dst_ids is None: self._dst_ids = decompress_ids(self._cdst_ids) return self._dst_ids def csrc_ids(self) -> torch.Tensor: if self._csrc_ids is None: src_ids, self._perm_csc2csr = torch.sort(self._src_ids) self._csrc_ids = compress_ids(src_ids, self._num_src_nodes) return self._csrc_ids def num_src_nodes(self): return self._num_src_nodes def num_dst_nodes(self): return self._num_dst_nodes def values(self): return self._values def formats(self): return self._formats def coo(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: if "coo" not in self.formats(): raise RuntimeError( "The SparseGraph did not create a COO layout. " "Set 'formats' list to include 'coo' when creating the graph." ) return self.src_ids(), self.dst_ids(), self._values def csc(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: if "csc" not in self.formats(): raise RuntimeError( "The SparseGraph did not create a CSC layout. " "Set 'formats' list to include 'csc' when creating the graph." ) return self.cdst_ids(), self.src_ids(), self._values def csr(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: if "csr" not in self.formats(): raise RuntimeError( "The SparseGraph did not create a CSR layout. " "Set 'formats' list to include 'csr' when creating the graph." ) csrc_ids = self.csrc_ids() dst_ids = self.dst_ids()[self._perm_csc2csr] value = self._values if value is not None: value = value[self._perm_csc2csr] return csrc_ids, dst_ids, value def __repr__(self) -> str: return ( f"{self.__class__.__name__}(num_src_nodes={self._num_src_nodes}, " f"num_dst_nodes={self._num_dst_nodes}, " f"num_edges={self._src_ids.size(0)}, formats={self._formats})" ) class BaseConv(torch.nn.Module): r"""An abstract base class for cugraph-ops nn module.""" def __init__(self): super().__init__() def reset_parameters(self): r"""Resets all learnable parameters of the module.""" raise NotImplementedError def forward(self, *args): r"""Runs the forward pass of the module.""" raise NotImplementedError def get_cugraph_ops_CSC( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], is_bipartite: bool = False, max_in_degree: Optional[int] = None, ) -> ops_torch.CSC: """Create CSC structure needed by cugraph-ops.""" if not isinstance(g, (SparseGraph, dgl.DGLHeteroGraph)): raise TypeError( f"The graph has to be either a 'cugraph_dgl.nn.SparseGraph' or " f"'dgl.DGLHeteroGraph', but got '{type(g)}'." ) # TODO: max_in_degree should default to None in pylibcugraphops if max_in_degree is None: max_in_degree = -1 if isinstance(g, SparseGraph): offsets, indices, _ = g.csc() else: offsets, indices, _ = g.adj_tensors("csc") graph = ops_torch.CSC( offsets=offsets, indices=indices, num_src_nodes=g.num_src_nodes(), dst_max_in_degree=max_in_degree, is_bipartite=is_bipartite, ) return graph def get_cugraph_ops_HeteroCSC( self, g: Union[SparseGraph, dgl.DGLHeteroGraph], num_edge_types: int, etypes: Optional[torch.Tensor] = None, is_bipartite: bool = False, max_in_degree: Optional[int] = None, ) -> ops_torch.HeteroCSC: """Create HeteroCSC structure needed by cugraph-ops.""" if not isinstance(g, (SparseGraph, dgl.DGLHeteroGraph)): raise TypeError( f"The graph has to be either a 'cugraph_dgl.nn.SparseGraph' or " f"'dgl.DGLHeteroGraph', but got '{type(g)}'." ) # TODO: max_in_degree should default to None in pylibcugraphops if max_in_degree is None: max_in_degree = -1 if isinstance(g, SparseGraph): offsets, indices, etypes = g.csc() if etypes is None: raise ValueError( "SparseGraph must have 'values' to create HeteroCSC. " "Pass in edge types as 'values' when creating the SparseGraph." ) etypes = etypes.int() else: if etypes is None: raise ValueError( "'etypes' is required when creating HeteroCSC " "from dgl.DGLHeteroGraph." ) offsets, indices, perm = g.adj_tensors("csc") etypes = etypes[perm].int() graph = ops_torch.HeteroCSC( offsets=offsets, indices=indices, edge_types=etypes, num_src_nodes=g.num_src_nodes(), num_edge_types=num_edge_types, dst_max_in_degree=max_in_degree, is_bipartite=is_bipartite, ) return graph
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/dataset.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Tuple, Dict, Optional, List, Union import os import cudf from cugraph.utilities.utils import import_optional from cugraph_dgl.dataloading.utils.sampling_helpers import ( create_homogeneous_sampled_graphs_from_dataframe, create_heterogeneous_sampled_graphs_from_dataframe, create_homogeneous_sampled_graphs_from_dataframe_csc, ) dgl = import_optional("dgl") torch = import_optional("torch") # Todo: maybe should switch to __iter__ class HomogenousBulkSamplerDataset(torch.utils.data.Dataset): def __init__( self, total_number_of_nodes: int, edge_dir: str, return_type: str = "dgl.Block", sparse_format: str = "coo", ): if return_type not in ["dgl.Block", "cugraph_dgl.nn.SparseGraph"]: raise ValueError( "return_type must be either 'dgl.Block' or " "'cugraph_dgl.nn.SparseGraph'." ) # TODO: Deprecate `total_number_of_nodes` # as it is no longer needed # in the next release self.total_number_of_nodes = total_number_of_nodes self.edge_dir = edge_dir self.sparse_format = sparse_format self._current_batch_fn = None self._input_files = None self._return_type = return_type def __len__(self): return self.num_batches def __getitem__(self, idx: int): if self._input_files is None: raise dgl.DGLError( "Please set input files by calling `set_input_files` " "before trying to fetch a sample" ) fn, batch_offset = self._batch_to_fn_d[idx] if fn != self._current_batch_fn: if self.sparse_format == "csc": df = _load_sampled_file(dataset_obj=self, fn=fn, skip_rename=True) self._current_batches = ( create_homogeneous_sampled_graphs_from_dataframe_csc(df) ) else: df = _load_sampled_file(dataset_obj=self, fn=fn) self._current_batches = ( create_homogeneous_sampled_graphs_from_dataframe( sampled_df=df, edge_dir=self.edge_dir, return_type=self._return_type, ) ) current_offset = idx - batch_offset return self._current_batches[current_offset] def set_input_files( self, input_directory: Optional[str] = None, input_file_paths: Optional[List[str]] = None, ): """ Set input files that have been created by the `cugraph.gnn.BulkSampler` Parameters ---------- input_directory: str input_directory which contains all the files that will be loaded by HomogenousBulkSamplerDataset input_file_paths: List[str] File paths that will be loaded by the HomogenousBulkSamplerDataset """ _set_input_files( self, input_directory=input_directory, input_file_paths=input_file_paths ) class HeterogenousBulkSamplerDataset(torch.utils.data.Dataset): def __init__( self, num_nodes_dict: Dict[str, int], etype_id_dict: Dict[int, Tuple[str, str, str]], etype_offset_dict: Dict[Tuple[str, str, str], int], ntype_offset_dict: Dict[str, int], edge_dir: str = "in", ): self.num_nodes_dict = num_nodes_dict self.etype_id_dict = etype_id_dict self.etype_offset_dict = etype_offset_dict self.ntype_offset_dict = ntype_offset_dict self.edge_dir = edge_dir self._current_batch_fn = None self._input_files = None def __len__(self): return self.num_batches def __getitem__(self, idx): if self._input_files is None: raise dgl.DGLError( "Please set input files by calling `set_input_files` " "before trying to fetch a sample" ) fn, batch_offset = self._batch_to_fn_d[idx] if fn != self._current_batch_fn: df = _load_sampled_file(dataset_obj=self, fn=fn) self._current_batches = create_heterogeneous_sampled_graphs_from_dataframe( sampled_df=df, num_nodes_dict=self.num_nodes_dict, etype_id_dict=self.etype_id_dict, etype_offset_dict=self.etype_offset_dict, ntype_offset_dict=self.ntype_offset_dict, edge_dir=self.edge_dir, ) del df current_offset = idx - batch_offset return self._current_batches[current_offset] def set_input_files( self, input_directory: Optional[str] = None, input_file_paths: Optional[List[str]] = None, ): """ Set input files that have been created by the `cugraph.gnn.BulkSampler` Parameters ---------- input_directory: str input_directory which contains all the files that will be loaded by HeterogenousBulkSamplerDataset input_file_paths: List[str] File names that will be loaded by the HeterogenousBulkSamplerDataset """ _set_input_files( self, input_directory=input_directory, input_file_paths=input_file_paths ) def _load_sampled_file(dataset_obj, fn, skip_rename=False): df = cudf.read_parquet(os.path.join(fn)) if dataset_obj.edge_dir == "in" and not skip_rename: df.rename( columns={"sources": "destinations", "destinations": "sources"}, inplace=True, ) dataset_obj._current_batch_fn = fn return df def get_batch_start_end(fn): batch_str = fn.split("batch=")[1] batch_start, batch_end = batch_str.split("-") batch_end = batch_end.split(".parquet")[0] return int(batch_start), int(batch_end) def get_batch_to_fn_d(files): batch_to_fn_d = {} batch_id = 0 for fn in files: start, end = get_batch_start_end(fn) batch_offset = batch_id for _ in range(start, end + 1): batch_to_fn_d[batch_id] = fn, batch_offset batch_id += 1 return batch_to_fn_d def _set_input_files( dataset_obj: Union[HomogenousBulkSamplerDataset, HeterogenousBulkSamplerDataset], input_directory: Optional[str] = None, input_file_paths: Optional[List[str]] = None, ) -> None: if input_directory is None and input_file_paths is None: raise ValueError("input_files or input_file_paths must be set") if (input_directory is not None) and (input_file_paths is not None): raise ValueError("Only one of input_directory or input_file_paths must be set") if input_file_paths: dataset_obj._input_files = input_file_paths if input_directory: dataset_obj._input_files = [fp.path for fp in os.scandir(input_directory)] dataset_obj._batch_to_fn_d = get_batch_to_fn_d(dataset_obj._input_files) dataset_obj.num_batches = len(dataset_obj._batch_to_fn_d) dataset_obj._current_batch_fn = None
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/neighbor_sampler.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Sequence class NeighborSampler: """Sampler that builds computational dependency of node representations via neighbor sampling for multilayer GNN. This sampler will make every node gather messages from a fixed number of neighbors per edge type. The neighbors are picked uniformly. Parameters ---------- fanouts_per_layer : int List of neighbors to sample for each GNN layer, with the i-th element being the fanout for the i-th GNN layer. If -1 is provided then all inbound/outbound edges of that edge type will be included. edge_dir : str, default ``'in'`` Can be either ``'in' `` where the neighbors will be sampled according to incoming edges, or ``'out'`` for outgoing edges replace : bool, default False Whether to sample with replacement Examples -------- **Node classification** To train a 3-layer GNN for node classification on a set of nodes ``train_nid`` on a homogeneous graph where each node takes messages from 5, 10, 15 neighbors for the first, second, and third layer respectively (assuming the backend is PyTorch): >>> sampler = cugraph_dgl.dataloading.NeighborSampler([5, 10, 15]) >>> dataloader = cugraph_dgl.dataloading.DataLoader( ... g, train_nid, sampler, ... batch_size=1024, shuffle=True) >>> for input_nodes, output_nodes, blocks in dataloader: ... train_on(blocks) """ def __init__( self, fanouts_per_layer: Sequence[int], edge_dir: str = "in", replace: bool = False, ): self.fanouts = fanouts_per_layer reverse_fanouts = fanouts_per_layer.copy() reverse_fanouts.reverse() self._reversed_fanout_vals = reverse_fanouts self.edge_dir = edge_dir self.replace = replace
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/__init__.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cugraph_dgl.dataloading.dataset import ( HomogenousBulkSamplerDataset, HeterogenousBulkSamplerDataset, ) from cugraph_dgl.dataloading.neighbor_sampler import NeighborSampler from cugraph_dgl.dataloading.dataloader import DataLoader
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/dataloader.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import shutil import cugraph_dgl import cupy as cp import cudf from cugraph.utilities.utils import import_optional from cugraph.experimental import BulkSampler from dask.distributed import default_client, Event from cugraph_dgl.dataloading import ( HomogenousBulkSamplerDataset, HeterogenousBulkSamplerDataset, ) from cugraph_dgl.dataloading.utils.extract_graph_helpers import ( create_cugraph_graph_from_edges_dict, ) dgl = import_optional("dgl") torch = import_optional("torch") class DataLoader(torch.utils.data.DataLoader): """ Sampled graph data loader. Wrap a :class:`~cugraph_dgl.CuGraphStorage` and a :class:`~cugraph_dgl.dataloading.NeighborSampler` into an iterable over mini-batches of samples. cugraph_dgl's ``DataLoader`` extends PyTorch's ``DataLoader`` by handling creation and transmission of graph samples. """ def __init__( self, graph: cugraph_dgl.CuGraphStorage, indices: torch.Tensor, graph_sampler: cugraph_dgl.dataloading.NeighborSampler, sampling_output_dir: str, batches_per_partition: int = 50, seeds_per_call: int = 200_000, device: torch.device = None, use_ddp: bool = False, ddp_seed: int = 0, batch_size: int = 1024, drop_last: bool = False, shuffle: bool = False, sparse_format: str = "coo", **kwargs, ): """ Constructor for CuGraphStorage: ------------------------------- graph : CuGraphStorage The graph. indices : Tensor or dict[ntype, Tensor] The set of indices. It can either be a tensor of integer indices or a dictionary of types and indices. The actual meaning of the indices is defined by the :meth:`sample` method of :attr:`graph_sampler`. graph_sampler : cugraph_dgl.dataloading.NeighborSampler The subgraph sampler. sampling_output_dir: str Output directory to share sampling results in batches_per_partition: int The number of batches of sampling results to write/read seeds_per_call: int The number of seeds to sample at once device : device context, optional The device of the generated MFGs in each iteration, which should be a PyTorch device object (e.g., ``torch.device``). By default this returns the tenors on device with the current cuda context use_ddp : boolean, optional If True, tells the DataLoader to split the training set for each participating process appropriately using :class:`torch.utils.data.distributed.DistributedSampler`. Overrides the :attr:`sampler` argument of :class:`torch.utils.data.DataLoader`. ddp_seed : int, optional The seed for shuffling the dataset in :class:`torch.utils.data.distributed.DistributedSampler`. Only effective when :attr:`use_ddp` is True. batch_size: int Batch size. sparse_format: str, default = "coo" The sparse format of the emitted sampled graphs. Choose between "csc" and "coo". When using "csc", the graphs are of type cugraph_dgl.nn.SparseGraph. kwargs : dict Key-word arguments to be passed to the parent PyTorch :py:class:`torch.utils.data.DataLoader` class. Common arguments are: - ``batch_size`` (int): The number of indices in each batch. - ``drop_last`` (bool): Whether to drop the last incomplete batch. - ``shuffle`` (bool): Whether to randomly shuffle the indices at each epoch Examples -------- To train a 3-layer GNN for node classification on a set of nodes ``train_nid`` on a homogeneous graph where each node takes messages from 15 neighbors on the first layer, 10 neighbors on the second, and 5 neighbors on the third: >>> sampler = cugraph_dgl.dataloading.NeighborSampler([15, 10, 5]) >>> dataloader = cugraph_dgl.dataloading.DataLoader( ... g, train_nid, sampler, ... batch_size=1024, shuffle=True, drop_last=False, num_workers=0) >>> for input_nodes, output_nodes, blocks in dataloader: ... train_on(input_nodes, output_nodes, blocks) **Using with Distributed Data Parallel** If you are using PyTorch's distributed training (e.g. when using :mod:`torch.nn.parallel.DistributedDataParallel`), you can train the model by turning on the `use_ddp` option: >>> sampler = cugraph_dgl.dataloading.NeighborSampler([15, 10, 5]) >>> dataloader = cugraph_dgl.dataloading.DataLoader( ... g, train_nid, sampler, use_ddp=True, ... batch_size=1024, shuffle=True, drop_last=False, num_workers=0) >>> for epoch in range(start_epoch, n_epochs): ... for input_nodes, output_nodes, blocks in dataloader: ... """ if sparse_format not in ["coo", "csc"]: raise ValueError( f"sparse_format must be one of 'coo', 'csc', " f"but got {sparse_format}." ) self.sparse_format = sparse_format self.ddp_seed = ddp_seed self.use_ddp = use_ddp self.shuffle = shuffle self.drop_last = drop_last self.graph_sampler = graph_sampler worker_init_fn = dgl.dataloading.WorkerInitWrapper( kwargs.get("worker_init_fn", None) ) self.other_storages = {} self.epoch_number = 0 self._batch_size = batch_size self._sampling_output_dir = sampling_output_dir self._batches_per_partition = batches_per_partition self._seeds_per_call = seeds_per_call self._rank = None indices = _dgl_idx_to_cugraph_idx(indices, graph) self.tensorized_indices_ds = dgl.dataloading.create_tensorized_dataset( indices, batch_size, drop_last, use_ddp, ddp_seed, shuffle, kwargs.get("persistent_workers", False), ) if len(graph.ntypes) <= 1: self.cugraph_dgl_dataset = HomogenousBulkSamplerDataset( total_number_of_nodes=graph.total_number_of_nodes, edge_dir=self.graph_sampler.edge_dir, sparse_format=sparse_format, ) else: etype_id_to_etype_str_dict = {v: k for k, v in graph._etype_id_dict.items()} self.cugraph_dgl_dataset = HeterogenousBulkSamplerDataset( num_nodes_dict=graph.num_nodes_dict, etype_id_dict=etype_id_to_etype_str_dict, etype_offset_dict=graph._etype_offset_d, ntype_offset_dict=graph._ntype_offset_d, edge_dir=self.graph_sampler.edge_dir, ) if use_ddp: rank = torch.distributed.get_rank() client = default_client() self._graph_creation_event = Event("cugraph_dgl_load_mg_graph_event") if rank == 0: G = create_cugraph_graph_from_edges_dict( edges_dict=graph._edges_dict, etype_id_dict=graph._etype_id_dict, edge_dir=graph_sampler.edge_dir, ) client.publish_dataset(cugraph_dgl_mg_graph_ds=G) self._graph_creation_event.set() else: if self._graph_creation_event.wait(timeout=1000): G = client.get_dataset("cugraph_dgl_mg_graph_ds") else: raise RuntimeError( f"Fetch cugraph_dgl_mg_graph_ds to worker_id {rank}", "from worker_id 0 failed", ) else: rank = 0 G = create_cugraph_graph_from_edges_dict( edges_dict=graph._edges_dict, etype_id_dict=graph._etype_id_dict, edge_dir=graph_sampler.edge_dir, ) self._rank = rank self._cugraph_graph = G super().__init__( self.cugraph_dgl_dataset, batch_size=None, worker_init_fn=worker_init_fn, collate_fn=lambda x: x, # Hack to prevent collating **kwargs, ) def __iter__(self): output_dir = os.path.join( self._sampling_output_dir, "epoch_" + str(self.epoch_number) ) kwargs = {} if isinstance(self.cugraph_dgl_dataset, HomogenousBulkSamplerDataset): kwargs["deduplicate_sources"] = True kwargs["prior_sources_behavior"] = "carryover" kwargs["renumber"] = True if self.sparse_format == "csc": kwargs["compression"] = "CSR" kwargs["compress_per_hop"] = True # The following kwargs will be deprecated in uniform sampler. kwargs["use_legacy_names"] = False kwargs["include_hop_column"] = False else: kwargs["deduplicate_sources"] = False kwargs["prior_sources_behavior"] = None kwargs["renumber"] = False bs = BulkSampler( output_path=output_dir, batch_size=self._batch_size, graph=self._cugraph_graph, batches_per_partition=self._batches_per_partition, seeds_per_call=self._seeds_per_call, fanout_vals=self.graph_sampler._reversed_fanout_vals, with_replacement=self.graph_sampler.replace, **kwargs, ) if self.shuffle: self.tensorized_indices_ds.shuffle() batch_df = create_batch_df(self.tensorized_indices_ds) bs.add_batches(batch_df, start_col_name="start", batch_col_name="batch_id") bs.flush() self.cugraph_dgl_dataset.set_input_files(input_directory=output_dir) self.epoch_number = self.epoch_number + 1 return super().__iter__() def __del__(self): if self.use_ddp: torch.distributed.barrier() if self._rank == 0: if self.use_ddp: client = default_client() client.unpublish_dataset("cugraph_dgl_mg_graph_ds") self._graph_creation_event.clear() _clean_directory(self._sampling_output_dir) def get_batch_id_series(n_output_rows: int, batch_size: int): num_batches = (n_output_rows + batch_size - 1) // batch_size print(f"Number of batches = {num_batches}".format(num_batches)) batch_ar = cp.arange(0, num_batches).repeat(batch_size) batch_ar = batch_ar[0:n_output_rows].astype(cp.int32) return cudf.Series(batch_ar) def create_batch_df(dataset: torch.Tensor): batch_id_ls = [] indices_ls = [] for batch_id, b_indices in enumerate(dataset): if isinstance(b_indices, dict): b_indices = torch.cat(list(b_indices.values())) batch_id_ar = cp.full(shape=len(b_indices), fill_value=batch_id, dtype=cp.int32) batch_id_ls.append(batch_id_ar) indices_ls.append(b_indices) batch_id_ar = cp.concatenate(batch_id_ls) indices_ar = cp.asarray(torch.concat(indices_ls)) batches_df = cudf.DataFrame( { "start": indices_ar, "batch_id": batch_id_ar, } ) return batches_df def _dgl_idx_to_cugraph_idx(idx, cugraph_gs): if not isinstance(idx, dict): if len(cugraph_gs.ntypes) > 1: raise dgl.DGLError( "Must specify node type when the graph is not homogeneous." ) return idx else: return {k: cugraph_gs.dgl_n_id_to_cugraph_id(n, k) for k, n in idx.items()} def _clean_directory(path): """param <path> could either be relative or absolute.""" if os.path.isfile(path): os.remove(path) # remove the file elif os.path.isdir(path): shutil.rmtree(path) # remove dir and all contains
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/utils/sampling_helpers.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import List, Tuple, Dict, Optional from collections import defaultdict import cudf from cugraph.utilities.utils import import_optional from cugraph_dgl.nn import SparseGraph dgl = import_optional("dgl") torch = import_optional("torch") cugraph_dgl = import_optional("cugraph_dgl") def cast_to_tensor(ser: cudf.Series): if len(ser) == 0: # Empty series can not be converted to pytorch cuda tensor t = torch.from_numpy(ser.values.get()) return t.to("cuda") return torch.as_tensor(ser.values, device="cuda") def _split_tensor(t, split_indices): """ Split a tensor into a list of tensors based on split_indices. """ # TODO: Switch to something below # return [t[i:j] for i, j in zip(split_indices[:-1], split_indices[1:])] if split_indices.device.type != "cpu": split_indices = split_indices.to("cpu") return torch.tensor_split(t, split_indices) def _get_source_destination_range(sampled_df): o = sampled_df.groupby(["batch_id", "hop_id"], as_index=True).agg( {"sources": "max", "destinations": "max"} ) o.rename( columns={"sources": "sources_range", "destinations": "destinations_range"}, inplace=True, ) d = o.to_dict(orient="index") return d def _create_split_dict(tensor): min_value = tensor.min() max_value = tensor.max() indices = torch.arange( start=min_value + 1, end=max_value + 1, device=tensor.device, ) split_dict = {i: {} for i in range(min_value, max_value + 1)} return split_dict, indices def _get_renumber_map(df): map = df["map"] df.drop(columns=["map"], inplace=True) map_starting_offset = map.iloc[0] renumber_map = map[map_starting_offset:].dropna().reset_index(drop=True) renumber_map_batch_indices = map[1 : map_starting_offset - 1].reset_index(drop=True) renumber_map_batch_indices = renumber_map_batch_indices - map_starting_offset map_end_offset = map_starting_offset + len(renumber_map) # We only need to drop rows if the length of dataframe is determined by the map # that is if map_length > sampled edges length if map_end_offset == len(df): df.dropna(axis=0, how="all", inplace=True) df.reset_index(drop=True, inplace=True) return df, cast_to_tensor(renumber_map), cast_to_tensor(renumber_map_batch_indices) def _get_tensor_d_from_sampled_df(df): """ Converts a sampled cuDF DataFrame into a list of tensors. Args: df (cudf.DataFrame): The sampled cuDF DataFrame containing columns Returns: dict: A dictionary of tensors, keyed by batch_id and hop_id. """ range_d = _get_source_destination_range(df) df, renumber_map, renumber_map_batch_indices = _get_renumber_map(df) batch_id_tensor = cast_to_tensor(df["batch_id"]) split_d, batch_indices = _create_split_dict(batch_id_tensor) batch_split_indices = torch.searchsorted(batch_id_tensor, batch_indices).to("cpu") for column in df.columns: if column != "batch_id": t = cast_to_tensor(df[column]) split_t = _split_tensor(t, batch_split_indices) for bid, batch_t in zip(split_d.keys(), split_t): split_d[bid][column] = batch_t split_t = _split_tensor(renumber_map, renumber_map_batch_indices) for bid, batch_t in zip(split_d.keys(), split_t): split_d[bid]["map"] = batch_t del df result_tensor_d = {} # Cache hop_split_d, hop_indices hop_split_empty_d, hop_indices = None, None for batch_id, batch_d in split_d.items(): hop_id_tensor = batch_d["hop_id"] if hop_split_empty_d is None: hop_split_empty_d, hop_indices = _create_split_dict(hop_id_tensor) hop_split_d = {k: {} for k in hop_split_empty_d.keys()} hop_split_indices = torch.searchsorted(hop_id_tensor, hop_indices).to("cpu") for column, t in batch_d.items(): if column not in ["hop_id", "map"]: split_t = _split_tensor(t, hop_split_indices) for hid, ht in zip(hop_split_d.keys(), split_t): hop_split_d[hid][column] = ht for hid in hop_split_d.keys(): hop_split_d[hid]["sources_range"] = range_d[(batch_id, hid)][ "sources_range" ] hop_split_d[hid]["destinations_range"] = range_d[(batch_id, hid)][ "destinations_range" ] result_tensor_d[batch_id] = hop_split_d result_tensor_d[batch_id]["map"] = batch_d["map"] return result_tensor_d def create_homogeneous_sampled_graphs_from_dataframe( sampled_df: cudf.DataFrame, edge_dir: str = "in", return_type: str = "dgl.Block", ): """ This helper function creates DGL MFGS for homogeneous graphs from cugraph sampled dataframe Args: sampled_df (cudf.DataFrame): The sampled cuDF DataFrame containing columns `sources`, `destinations`, `edge_id`, `batch_id` and `hop_id`. edge_dir (str): Direction of edges from samples Returns: list: A list containing three elements: - input_nodes: The input nodes for the batch. - output_nodes: The output nodes for the batch. - graph_per_hop_ls: A list of DGL MFGS for each hop. """ if return_type not in ["dgl.Block", "cugraph_dgl.nn.SparseGraph"]: raise ValueError( "return_type must be either dgl.Block or cugraph_dgl.nn.SparseGraph" ) result_tensor_d = _get_tensor_d_from_sampled_df(sampled_df) del sampled_df result_mfgs = [ _create_homogeneous_sampled_graphs_from_tensors_perhop( tensors_batch_d, edge_dir, return_type ) for tensors_batch_d in result_tensor_d.values() ] del result_tensor_d return result_mfgs def _create_homogeneous_sampled_graphs_from_tensors_perhop( tensors_batch_d, edge_dir, return_type ): """ This helper function creates sampled DGL MFGS for homogeneous graphs from tensors per hop for a single batch Args: tensors_batch_d (dict): A dictionary of tensors, keyed by hop_id. edge_dir (str): Direction of edges from samples metagraph (dgl.metagraph): The metagraph for the sampled graph return_type (str): The type of graph to return Returns: tuple: A tuple of three elements: - input_nodes: The input nodes for the batch. - output_nodes: The output nodes for the batch. - graph_per_hop_ls: A list of MFGS for each hop. """ if edge_dir not in ["in", "out"]: raise ValueError(f"Invalid edge_dir {edge_dir} provided") if edge_dir == "out": raise ValueError("Outwards edges not supported yet") graph_per_hop_ls = [] seednodes_range = None for hop_id, tensor_per_hop_d in tensors_batch_d.items(): if hop_id != "map": if return_type == "dgl.Block": mfg = _create_homogeneous_dgl_block_from_tensor_d( tensor_d=tensor_per_hop_d, renumber_map=tensors_batch_d["map"], seednodes_range=seednodes_range, ) elif return_type == "cugraph_dgl.nn.SparseGraph": mfg = _create_homogeneous_cugraph_dgl_nn_sparse_graph( tensor_d=tensor_per_hop_d, seednodes_range=seednodes_range ) else: raise ValueError(f"Invalid return_type {return_type} provided") seednodes_range = max( tensor_per_hop_d["sources_range"], tensor_per_hop_d["destinations_range"], ) graph_per_hop_ls.append(mfg) # default DGL behavior if edge_dir == "in": graph_per_hop_ls.reverse() if return_type == "dgl.Block": input_nodes = graph_per_hop_ls[0].srcdata[dgl.NID] output_nodes = graph_per_hop_ls[-1].dstdata[dgl.NID] else: map = tensors_batch_d["map"] input_nodes = map[0 : graph_per_hop_ls[0].num_src_nodes()] output_nodes = map[0 : graph_per_hop_ls[-1].num_dst_nodes()] return input_nodes, output_nodes, graph_per_hop_ls def _create_homogeneous_dgl_block_from_tensor_d( tensor_d, renumber_map, seednodes_range=None, ): rs = tensor_d["sources"] rd = tensor_d["destinations"] max_src_nodes = tensor_d["sources_range"] max_dst_nodes = tensor_d["destinations_range"] if seednodes_range is not None: # If we have vertices without outgoing edges, then # sources can be missing from seednodes # so we add them # to ensure all the blocks are # lined up correctly max_dst_nodes = max(max_dst_nodes, seednodes_range) data_dict = {("_N", "_E", "_N"): (rs, rd)} num_src_nodes = {"_N": max_src_nodes + 1} num_dst_nodes = {"_N": max_dst_nodes + 1} block = dgl.create_block( data_dict=data_dict, num_src_nodes=num_src_nodes, num_dst_nodes=num_dst_nodes ) if "edge_id" in tensor_d: block.edata[dgl.EID] = tensor_d["edge_id"] # Below adds run time overhead block.srcdata[dgl.NID] = renumber_map[0 : max_src_nodes + 1] block.dstdata[dgl.NID] = renumber_map[0 : max_dst_nodes + 1] return block def _create_homogeneous_cugraph_dgl_nn_sparse_graph(tensor_d, seednodes_range): max_src_nodes = tensor_d["sources_range"] max_dst_nodes = tensor_d["destinations_range"] if seednodes_range is not None: max_dst_nodes = max(max_dst_nodes, seednodes_range) size = (max_src_nodes + 1, max_dst_nodes + 1) sparse_graph = cugraph_dgl.nn.SparseGraph( size=size, src_ids=tensor_d["sources"], dst_ids=tensor_d["destinations"], formats=["csc"], reduce_memory=True, ) return sparse_graph def create_heterogeneous_sampled_graphs_from_dataframe( sampled_df: cudf.DataFrame, num_nodes_dict: Dict[str, int], etype_id_dict: Dict[int, Tuple[str, str, str]], etype_offset_dict: Dict[Tuple[str, str, str], int], ntype_offset_dict: Dict[str, int], edge_dir: str = "in", ): """ This helper function creates DGL MFGS from cugraph sampled dataframe """ sampled_df["batch_id"] = sampled_df["batch_id"] - sampled_df["batch_id"].min() result_df_ls = sampled_df[ ["sources", "destinations", "edge_id", "hop_id", "edge_type"] ].scatter_by_map(sampled_df["batch_id"], keep_index=False) del sampled_df result_df_ls = [ batch_df[["sources", "destinations", "edge_id", "edge_type"]].scatter_by_map( batch_df["hop_id"], keep_index=False ) for batch_df in result_df_ls ] result_tensor_ls = [ [ _get_edges_dict_from_perhop_df( h_df, etype_id_dict, etype_offset_dict, ntype_offset_dict ) for h_df in per_batch_ls ] for per_batch_ls in result_df_ls ] del result_df_ls result_mfgs = [ _create_heterogenous_sampled_graphs_from_tensors_perhop( tensors_perhop_ls, num_nodes_dict, edge_dir ) for tensors_perhop_ls in result_tensor_ls ] return result_mfgs def _get_edges_dict_from_perhop_df( df, etype_id_dict, etype_offset_dict, ntype_offset_dict ): # Optimize below function # based on _get_tensor_ls_from_sampled_df edges_per_type_ls = df[["sources", "destinations", "edge_id"]].scatter_by_map( df["edge_type"], map_size=len(etype_id_dict), keep_index=False ) del df per_type_df_d = {etype_id_dict[i]: df for i, df in enumerate(edges_per_type_ls)} del edges_per_type_ls # reverse src,dst here per_type_tensor_d = { etype: ( cast_to_tensor(etype_df["sources"]) - ntype_offset_dict[etype[0]], cast_to_tensor(etype_df["destinations"]) - ntype_offset_dict[etype[2]], cast_to_tensor(etype_df["edge_id"]) - etype_offset_dict[etype], ) for etype, etype_df in per_type_df_d.items() } return per_type_tensor_d def _create_heterogenous_sampled_graphs_from_tensors_perhop( tensors_perhop_ls, num_nodes_dict, edge_dir ): if edge_dir not in ["in", "out"]: raise ValueError(f"Invalid edge_dir {edge_dir} provided") if edge_dir == "out": raise ValueError("Outwards edges not supported yet") graph_per_hop_ls = [] output_nodes = None seed_nodes = None for hop_edges_dict in tensors_perhop_ls: block = create_heterogenous_dgl_block_from_tensors_dict( hop_edges_dict, num_nodes_dict, seed_nodes ) seed_nodes = block.srcdata[dgl.NID] if output_nodes is None: output_nodes = block.dstdata[dgl.NID] graph_per_hop_ls.append(block) # default DGL behavior if edge_dir == "in": graph_per_hop_ls.reverse() return seed_nodes, output_nodes, graph_per_hop_ls def create_heterogenous_dgl_block_from_tensors_dict( edges_dict: Dict[Tuple(str, str, str), (torch.Tensor, torch.Tensor, torch.Tensor)], num_nodes_dict: Dict[str, torch.Tensor], seed_nodes: Optional[Dict[str, torch.Tensor]], ): data_dict = {k: (s, d) for k, (s, d, _) in edges_dict.items()} edge_ids_dict = {k: eid for k, (_, _, eid) in edges_dict.items()} sampled_graph = dgl.heterograph( data_dict=data_dict, num_nodes_dict=num_nodes_dict, ) sampled_graph.edata[dgl.EID] = edge_ids_dict src_d = defaultdict(list) dst_d = defaultdict(list) for (s, _, d), (src_id, dst_id) in data_dict.items(): src_d[s].append(src_id) dst_d[d].append(dst_id) src_d = {k: torch.cat(v).unique() for k, v in src_d.items() if len(v) > 0} if seed_nodes is None: seed_nodes = {k: torch.cat(v).unique() for k, v in dst_d.items() if len(v) > 0} block = dgl.to_block(sampled_graph, dst_nodes=seed_nodes, src_nodes=src_d) block.edata[dgl.EID] = sampled_graph.edata[dgl.EID] return block def _process_sampled_df_csc( df: cudf.DataFrame, reverse_hop_id: bool = True, ) -> Tuple[ Dict[int, Dict[int, Dict[str, torch.Tensor]]], List[torch.Tensor], List[List[int, int]], ]: """ Convert a dataframe generated by BulkSampler to a dictionary of tensors, to facilitate MFG creation. The sampled graphs in the dataframe use CSC-format. Parameters ---------- df: cudf.DataFrame The output from BulkSampler compressed in CSC format. The dataframe should be generated with `compression="CSR"` in BulkSampler, since the sampling routine treats seed nodes as sources. reverse_hop_id: bool (default=True) Reverse hop id. Returns ------- tensors_dict: dict A nested dictionary keyed by batch id and hop id. `tensor_dict[batch_id][hop_id]` holds "minors" and "major_offsets" values for CSC MFGs. renumber_map_list: list List of renumbering maps for looking up global indices of nodes. One map for each batch. mfg_sizes: list List of the number of nodes in each message passing layer. For the k-th hop, mfg_sizes[k] and mfg_sizes[k+1] is the number of sources and destinations, respectively. """ # dropna major_offsets = cast_to_tensor(df.major_offsets.dropna()) label_hop_offsets = cast_to_tensor(df.label_hop_offsets.dropna()) renumber_map_offsets = cast_to_tensor(df.renumber_map_offsets.dropna()) renumber_map = cast_to_tensor(df.map.dropna()) minors = cast_to_tensor(df.minors.dropna()) n_batches = len(renumber_map_offsets) - 1 n_hops = int((len(label_hop_offsets) - 1) / n_batches) # make global offsets local # Have to make a clone as pytorch does not allow # in-place operations on tensors major_offsets -= major_offsets[0].clone() label_hop_offsets -= label_hop_offsets[0].clone() renumber_map_offsets -= renumber_map_offsets[0].clone() # get the sizes of each adjacency matrix (for MFGs) mfg_sizes = (label_hop_offsets[1:] - label_hop_offsets[:-1]).reshape( (n_batches, n_hops) ) n_nodes = renumber_map_offsets[1:] - renumber_map_offsets[:-1] mfg_sizes = torch.hstack((mfg_sizes, n_nodes.reshape(n_batches, -1))) if reverse_hop_id: mfg_sizes = mfg_sizes.flip(1) tensors_dict = {} renumber_map_list = [] # Note: minors and major_offsets from BulkSampler are of type int32 # and int64 respectively. Since pylibcugraphops binding code doesn't # support distinct node and edge index type, we simply casting both # to int32 for now. minors = minors.int() major_offsets = major_offsets.int() # Note: We transfer tensors to CPU here to avoid the overhead of # transferring them in each iteration of the for loop below. major_offsets_cpu = major_offsets.to("cpu").numpy() label_hop_offsets_cpu = label_hop_offsets.to("cpu").numpy() for batch_id in range(n_batches): batch_dict = {} for hop_id in range(n_hops): hop_dict = {} idx = batch_id * n_hops + hop_id # idx in label_hop_offsets major_offsets_start = label_hop_offsets_cpu[idx] major_offsets_end = label_hop_offsets_cpu[idx + 1] minors_start = major_offsets_cpu[major_offsets_start] minors_end = major_offsets_cpu[major_offsets_end] hop_dict["minors"] = minors[minors_start:minors_end] hop_dict["major_offsets"] = ( major_offsets[major_offsets_start : major_offsets_end + 1] - major_offsets[major_offsets_start] ) if reverse_hop_id: batch_dict[n_hops - 1 - hop_id] = hop_dict else: batch_dict[hop_id] = hop_dict tensors_dict[batch_id] = batch_dict renumber_map_list.append( renumber_map[ renumber_map_offsets[batch_id] : renumber_map_offsets[batch_id + 1] ], ) return tensors_dict, renumber_map_list, mfg_sizes.tolist() def _create_homogeneous_sparse_graphs_from_csc( tensors_dict: Dict[int, Dict[int, Dict[str, torch.Tensor]]], renumber_map_list: List[torch.Tensor], mfg_sizes: List[int, int], ) -> List[List[torch.Tensor, torch.Tensor, List[SparseGraph]]]: """Create mini-batches of MFGs. The input arguments are the outputs of the function `_process_sampled_df_csc`. Returns ------- output: list A list of mini-batches. Each mini-batch is a list that consists of `input_nodes` tensor, `output_nodes` tensor and a list of MFGs. """ n_batches, n_hops = len(mfg_sizes), len(mfg_sizes[0]) - 1 output = [] for b_id in range(n_batches): output_batch = [] output_batch.append(renumber_map_list[b_id]) output_batch.append(renumber_map_list[b_id][: mfg_sizes[b_id][-1]]) mfgs = [ SparseGraph( size=(mfg_sizes[b_id][h_id], mfg_sizes[b_id][h_id + 1]), src_ids=tensors_dict[b_id][h_id]["minors"], cdst_ids=tensors_dict[b_id][h_id]["major_offsets"], formats=["csc"], reduce_memory=True, ) for h_id in range(n_hops) ] output_batch.append(mfgs) output.append(output_batch) return output def create_homogeneous_sampled_graphs_from_dataframe_csc(sampled_df: cudf.DataFrame): """Public API to create mini-batches of MFGs using a dataframe output by BulkSampler, where the sampled graph is compressed in CSC format.""" return _create_homogeneous_sparse_graphs_from_csc( *(_process_sampled_df_csc(sampled_df)) )
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/utils/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading
rapidsai_public_repos/cugraph/python/cugraph-dgl/cugraph_dgl/dataloading/utils/extract_graph_helpers.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Tuple, Dict, Union import cugraph import cudf import dask_cudf import numpy as np def create_cugraph_graph_from_edges_dict( edges_dict: Dict[Tuple(str, str, str), Union[dask_cudf.DataFrame, cudf.DataFrame]], etype_id_dict: Dict[Dict[Tuple(str, str, str)] : int], edge_dir: str, ): if edge_dir == "in": edges_dict = {k: reverse_edges(df) for k, df in edges_dict.items()} if len(edges_dict) > 1: has_multiple_etypes = True edges_dict = { k: add_etype_id(df, etype_id_dict[k]) for k, df in edges_dict.items() } else: has_multiple_etypes = False edges_dfs = list(edges_dict.values()) del edges_dict if isinstance(edges_dfs[0], dask_cudf.DataFrame): edges_df = dask_cudf.concat(edges_dfs, ignore_index=True) else: edges_df = cudf.concat(edges_dfs, ignore_index=True) del edges_dfs G = cugraph.MultiGraph(directed=True) if isinstance(edges_df, dask_cudf.DataFrame): g_creation_f = G.from_dask_cudf_edgelist else: g_creation_f = G.from_cudf_edgelist if has_multiple_etypes: edge_etp = "etp" else: edge_etp = None g_creation_f( edges_df, source="_SRC_", destination="_DST_", weight=None, edge_id="_EDGE_ID_", edge_type=edge_etp, renumber=True, ) return G def reverse_edges(df: Union[dask_cudf.DataFrame, cudf.DataFrame]): return df.rename(columns={"_SRC_": "_DST_", "_DST_": "_SRC_"}) def add_etype_id(df: Union[dask_cudf.DataFrame, cudf.DataFrame], etype_id: int): df["etp"] = np.int32(etype_id) return df
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/conda/cugraph_dgl_dev_cuda-118.yaml
# This file is generated by `rapids-dependency-file-generator`. # To make changes, edit ../../../dependencies.yaml and run `rapids-dependency-file-generator`. channels: - rapidsai - rapidsai-nightly - dask/label/dev - pytorch - pyg - dglteam/label/cu118 - conda-forge - nvidia dependencies: - cugraph==23.12.* - dgl>=1.1.0.cu* - pandas - pre-commit - pylibcugraphops==23.12.* - pytest - pytest-benchmark - pytest-cov - pytest-xdist - pytorch-cuda==11.8 - pytorch>=2.0 - scipy name: cugraph_dgl_dev_cuda-118
0
rapidsai_public_repos/cugraph/python/cugraph-dgl
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples/dataset_from_disk_cudf.ipynb
import os os.environ["CUDA_VISIBLE_DEVICES"]="4" import cudf import rmm import torch from rmm.allocators.torch import rmm_torch_allocator rmm.reinitialize(initial_pool_size=15e9) #Switch to async pool in case of memory issues due to fragmentation of the pool #rmm.mr.set_current_device_resource(rmm.mr.CudaAsyncMemoryResource(initial_pool_size=15e9)) torch.cuda.memory.change_current_allocator(rmm_torch_allocator)single_gpu = Truedef load_dgl_dataset(dataset_name='ogbn-products'): from ogb.nodeproppred import DglNodePropPredDataset dataset_root = '/raid/vjawa/gnn/' dataset = DglNodePropPredDataset(name = dataset_name, root=dataset_root) split_idx = dataset.get_idx_split() train_idx, valid_idx, test_idx = split_idx["train"], split_idx["valid"], split_idx["test"] g, label = dataset[0] g.ndata['label'] = label g = g.add_self_loop() g = g.to('cpu') return g, train_idximport cugraph_dgl import tempfileg, train_idx = load_dgl_dataset() g = cugraph_dgl.cugraph_storage_from_heterograph(g, single_gpu=single_gpu) batch_size = 1024*2 fanout_vals=[25, 25] sampler = cugraph_dgl.dataloading.NeighborSampler(fanout_vals) dataloader = cugraph_dgl.dataloading.DataLoader( g, train_idx.to('cuda'), # train_nid must be on GPU. sampler, sampling_output_dir="/raid/vjawa/obgn_products_sampling/", # Path to save sampling results to, Change to the fastest IO path available device=torch.device('cuda'), # The device argument must be GPU. num_workers=0, # Number of workers must be 0. batch_size=batch_size, batches_per_partition=50, seeds_per_call=50*batch_size, drop_last=False, shuffle=False)%%timeit batch_stats = {} for batch_id,(input_nodes, output_nodes, blocks) in enumerate(dataloader): batch_stats[batch_id]={'input_nodes':len(input_nodes),'output_nodes':len(output_nodes)}del dataloader del gfrom dgl.dataloading import DataLoader, NeighborSampler import dglg, train_idx = load_dgl_dataset() batch_size = 1024*2 fanout_vals = [25, 25] sampler = dgl.dataloading.MultiLayerNeighborSampler(fanout_vals) dataloader = dgl.dataloading.DataLoader( g, train_idx.to(g.device), # train_nid must be on GPU. sampler, device=torch.device('cuda'), # The device argument must be GPU. num_workers=0, # Number of workers must be 0. use_uva=False, batch_size=batch_size, drop_last=False, shuffle=False)%%timeit dgl_batch_stats = {} for batch_id,(input_nodes, output_nodes, blocks) in enumerate(dataloader): dgl_batch_stats[batch_id]={'input_nodes':len(input_nodes),'output_nodes':len(output_nodes)}del dataloader del g
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples/multi_trainer_MG_example/workflow.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import dgl import torch import time from distributed import Client, Event as Dask_Event import tempfile from cugraph.dask.comms import comms as Comms def enable_spilling(): import cudf cudf.set_option("spill", True) def setup_cluster(dask_worker_devices): dask_worker_devices_str = ",".join([str(i) for i in dask_worker_devices]) from dask_cuda import LocalCUDACluster cluster = LocalCUDACluster( protocol="tcp", CUDA_VISIBLE_DEVICES=dask_worker_devices_str, rmm_pool_size="25GB", ) client = Client(cluster) client.wait_for_workers(n_workers=len(dask_worker_devices)) client.run(enable_spilling) print("Dask Cluster Setup Complete") del client return cluster def create_dask_client(scheduler_address): from cugraph.dask.comms import comms as Comms client = Client(scheduler_address) Comms.initialize(p2p=True) return client def initalize_pytorch_worker(dev_id): import cupy as cp import rmm from rmm.allocators.torch import rmm_torch_allocator from rmm.allocators.cupy import rmm_cupy_allocator dev = cp.cuda.Device( dev_id ) # Create cuda context on the right gpu, defaults to gpu-0 dev.use() rmm.reinitialize( pool_allocator=True, initial_pool_size=10e9, maximum_pool_size=15e9, devices=[dev_id], ) if dev_id == 0: torch.cuda.memory.change_current_allocator(rmm_torch_allocator) torch.cuda.set_device(dev_id) cp.cuda.set_allocator(rmm_cupy_allocator) enable_spilling() print("device_id", dev_id, flush=True) def load_dgl_dataset(dataset_name="ogbn-products"): from ogb.nodeproppred import DglNodePropPredDataset dataset = DglNodePropPredDataset(name=dataset_name) split_idx = dataset.get_idx_split() train_idx, valid_idx, test_idx = ( split_idx["train"], split_idx["valid"], split_idx["test"], ) g, label = dataset[0] g.ndata["label"] = label if len(g.etypes) <= 1: g = dgl.add_self_loop(g) else: for etype in g.etypes: if etype[0] == etype[2]: # only add self loops for src->dst g = dgl.add_self_loop(g, etype=etype) g = g.int() train_idx = train_idx.int() valid_idx = valid_idx.int() test_idx = test_idx.int() return g, train_idx, valid_idx, test_idx, dataset.num_classes def create_cugraph_graphstore_from_dgl_dataset( dataset_name="ogbn-products", single_gpu=False ): from cugraph_dgl import cugraph_storage_from_heterograph dgl_g, train_idx, valid_idx, test_idx, num_classes = load_dgl_dataset(dataset_name) cugraph_gs = cugraph_storage_from_heterograph(dgl_g, single_gpu=single_gpu) return cugraph_gs, train_idx, valid_idx, test_idx, num_classes def create_dataloader(gs, train_idx, device): import cugraph_dgl temp_dir = tempfile.TemporaryDirectory() sampler = cugraph_dgl.dataloading.NeighborSampler([10, 20]) dataloader = cugraph_dgl.dataloading.DataLoader( gs, train_idx, sampler, sampling_output_dir=temp_dir.name, batches_per_partition=10, device=device, # Put the sampled MFGs on CPU or GPU use_ddp=True, # Make it work with distributed data parallel batch_size=1024, shuffle=False, # Whether to shuffle the nodes for every epoch drop_last=False, num_workers=0, ) return dataloader def run_workflow(rank, devices, scheduler_address): from model import Sage, train_model # Below sets gpu_number dev_id = devices[rank] initalize_pytorch_worker(dev_id) device = torch.device(f"cuda:{dev_id}") # cugraph dask client initialization client = create_dask_client(scheduler_address) # Pytorch training worker initialization dist_init_method = "tcp://{master_ip}:{master_port}".format( master_ip="127.0.0.1", master_port="12346" ) torch.distributed.init_process_group( backend="nccl", init_method=dist_init_method, world_size=len(devices), rank=rank, ) print(f"rank {rank}.", flush=True) print("Initalized across GPUs.") event = Dask_Event("cugraph_gs_creation_event") if rank == 0: ( gs, train_idx, valid_idx, test_idx, num_classes, ) = create_cugraph_graphstore_from_dgl_dataset( "ogbn-products", single_gpu=False ) client.publish_dataset(cugraph_gs=gs) client.publish_dataset(train_idx=train_idx) client.publish_dataset(valid_idx=valid_idx) client.publish_dataset(test_idx=test_idx) client.publish_dataset(num_classes=num_classes) event.set() else: if event.wait(timeout=1000): gs = client.get_dataset("cugraph_gs") train_idx = client.get_dataset("train_idx") valid_idx = client.get_dataset("valid_idx") test_idx = client.get_dataset("test_idx") num_classes = client.get_dataset("num_classes") else: raise RuntimeError(f"Fetch cugraph_gs to worker_id {rank} failed") torch.distributed.barrier() print(f"Loading cugraph_store to worker {rank} is complete", flush=True) dataloader = create_dataloader(gs, train_idx, device) print("Data Loading Complete", flush=True) num_feats = gs.ndata["feat"]["_N"].shape[1] hid_size = 256 # Load Training example model = Sage(num_feats, hid_size, num_classes).to(device) model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[device], output_device=device, ) torch.distributed.barrier() n_epochs = 10 total_st = time.time() opt = torch.optim.Adam(model.parameters(), lr=0.01) train_model(model, gs, opt, dataloader, n_epochs, rank, valid_idx) torch.distributed.barrier() total_et = time.time() print( f"Total time taken on n_epochs {n_epochs} = {total_et-total_st} s", f"measured by worker = {rank}", ) # cleanup dask cluster if rank == 0: client.unpublish_dataset("cugraph_gs") client.unpublish_dataset("train_idx") client.unpublish_dataset("valid_idx") client.unpublish_dataset("test_idx") event.clear() print("Workflow completed") print("---" * 10) Comms.destroy() if __name__ == "__main__": # Load dummy first # because new environments # require dataset download load_dgl_dataset() dask_worker_devices = [5, 6] cluster = setup_cluster(dask_worker_devices) trainer_devices = [0, 1, 2] import torch.multiprocessing as mp mp.spawn( run_workflow, args=(trainer_devices, cluster.scheduler_address), nprocs=len(trainer_devices), ) Comms.destroy() cluster.close()
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples/multi_trainer_MG_example/model.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # A graphsage GNN model using dgl for node classification # with three layers and mean aggregation import time import dgl import torch import torch.nn as nn import torch.nn.functional as F import torchmetrics.functional as MF from cugraph_dgl.nn import SAGEConv import tqdm class Sage(nn.Module): def __init__(self, in_size, hid_size, out_size): super().__init__() self.layers = nn.ModuleList() # 2-layer GraphSAGE-mean self.layers.append(SAGEConv(in_size, hid_size, "mean")) self.layers.append(SAGEConv(hid_size, out_size, "mean")) self.dropout = nn.Dropout(0.5) self.hid_size = hid_size self.out_size = out_size def forward(self, blocks, x): h = x for l_id, (layer, block) in enumerate(zip(self.layers, blocks)): h = layer(block, h) if l_id != len(self.layers) - 1: h = F.relu(h) h = self.dropout(h) return h def inference(self, g, batch_size, device): """ Inference with the GraphSAGE model on full neighbors (i.e. without neighbor sampling). g : the entire graph. batch_size : the node number of each inference output device : the inference device """ # During inference with sampling, # multi-layer blocks are very inefficient because # lots of computations in the first few layers are repeated. # Therefore, we compute the representation of all nodes layer by layer. # The nodes on each layer are of course splitted in batches. all_node_ids = torch.arange(0, g.num_nodes()).to(device) feat = g.get_node_storage(key="feat", ntype="_N").fetch( all_node_ids, device=device ) sampler = dgl.dataloading.MultiLayerFullNeighborSampler( 1, prefetch_node_feats=["feat"] ) dataloader = dgl.dataloading.DataLoader( g, torch.arange(g.num_nodes(), dtype=torch.int32).to(g.device), sampler, device=device, batch_size=batch_size, shuffle=False, drop_last=False, num_workers=0, ) buffer_device = torch.device("cpu") pin_memory = buffer_device != device for l_id, layer in enumerate(self.layers): y = torch.empty( g.num_nodes(), self.hid_size if l_id != len(self.layers) - 1 else self.out_size, device=buffer_device, pin_memory=pin_memory, ) feat = feat.to(device) for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader): x = feat[input_nodes] h = layer(blocks[0], x) # len(blocks) = 1 if l_id != len(self.layers) - 1: h = F.relu(h) h = self.dropout(h) # by design, our output nodes are contiguous y[output_nodes[0] : output_nodes[-1] + 1] = h.to(buffer_device) feat = y return y def layerwise_infer(graph, nid, model, batch_size, device): model.eval() with torch.no_grad(): pred = model.module.inference( graph, batch_size, device ) # pred in buffer_device pred = pred[nid] label = graph.ndata["label"] if isinstance(label, dict): label = label["_N"] label = label[nid].to(pred.device) num_classes = pred.shape[1] label = label.squeeze(1) return MF.accuracy(pred, label, task="multiclass", num_classes=num_classes) def train_model(model, g, opt, train_dataloader, num_epochs, rank, val_nid): g.ndata["feat"]["_N"] = g.ndata["feat"]["_N"].to("cuda") g.ndata["label"]["_N"] = g.ndata["label"]["_N"].to("cuda") st = time.time() model.train() for epoch in range(num_epochs): total_loss = 0 for _, (input_nodes, output_nodes, blocks) in enumerate(train_dataloader): x = g.ndata["feat"]["_N"][input_nodes] y = g.ndata["label"]["_N"][output_nodes] y_hat = model(blocks, x) y = y.squeeze(1) loss = F.cross_entropy(y_hat, y) opt.zero_grad() loss.backward() opt.step() total_loss += loss.item() print( f"total loss: {total_loss} for epoch = {epoch} for rank = {rank}", flush=True, ) et = time.time() print( f"Total time taken for num_epochs {num_epochs} " f"with batch_size {train_dataloader._batch_size} = {et-st} s on rank ={rank}" ) if rank == 0: val_acc = layerwise_infer(g, val_nid, model, 1024 * 5, "cuda") print("---" * 30) print("Validation Accuracy {:.4f}".format(val_acc))
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples/graphsage/README.MD
Inductive Representation Learning on Large Graphs (GraphSAGE) ============ - Paper link: [http://papers.nips.cc/paper/6703-inductive-representation-learning-on-large-graphs.pdf](http://papers.nips.cc/paper/6703-inductive-representation-learning-on-large-graphs.pdf) - Author's code repo: [https://github.com/williamleif/graphsage-simple](https://github.com/williamleif/graphsage-simple) For advanced usages, including training with multi-gpu/multi-node, and PyTorch Lightning, etc., more examples can be found in [advanced](https://github.com/dmlc/dgl/tree/master/examples/pytorch/graphsage/advanced) and [dist](https://github.com/dmlc/dgl/tree/master/examples/pytorch/graphsage/dist) directory. Requirements ------------ ```bash mamba install ogb torchmetrics -c conda-forge ``` How to run ------- ### Minibatch training for node classification Train w/ mini-batch sampling with cugraph_storage backend for node classification on "ogbn-products" ```bash python3 node_classification.py --mode=gpu_cugraph_dgl ```
0
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples
rapidsai_public_repos/cugraph/python/cugraph-dgl/examples/graphsage/node-classification.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Example modified from: # https://github.com/dmlc/dgl/blob/master/examples/pytorch/graphsage/node_classification.py # Ignore Warning import warnings import time import cugraph_dgl import torch import torch.nn as nn import torch.nn.functional as F import torchmetrics.functional as MF import dgl import dgl.nn as dglnn from dgl.data import AsNodePredDataset from dgl.dataloading import ( DataLoader, NeighborSampler, MultiLayerFullNeighborSampler, ) from ogb.nodeproppred import DglNodePropPredDataset import tqdm import argparse warnings.filterwarnings("ignore") def set_allocators(): import rmm import cudf import cupy from rmm.allocators.torch import rmm_torch_allocator from rmm.allocators.cupy import rmm_cupy_allocator mr = rmm.mr.CudaAsyncMemoryResource() rmm.mr.set_current_device_resource(mr) torch.cuda.memory.change_current_allocator(rmm_torch_allocator) cupy.cuda.set_allocator(rmm_cupy_allocator) cudf.set_option("spill", True) class SAGE(nn.Module): def __init__(self, in_size, hid_size, out_size): super().__init__() self.layers = nn.ModuleList() # three-layer GraphSAGE-mean self.layers.append(dglnn.SAGEConv(in_size, hid_size, "mean")) self.layers.append(dglnn.SAGEConv(hid_size, hid_size, "mean")) self.layers.append(dglnn.SAGEConv(hid_size, out_size, "mean")) self.dropout = nn.Dropout(0.5) self.hid_size = hid_size self.out_size = out_size def forward(self, blocks, x): h = x for l_id, (layer, block) in enumerate(zip(self.layers, blocks)): h = layer(block, h) if l_id != len(self.layers) - 1: h = F.relu(h) h = self.dropout(h) return h def inference(self, g, device, batch_size): """Conduct layer-wise inference to get all the node embeddings.""" all_node_ids = torch.arange(0, g.num_nodes()).to(device) feat = g.get_node_storage(key="feat", ntype="_N").fetch( all_node_ids, device=device ) sampler = MultiLayerFullNeighborSampler(1, prefetch_node_feats=["feat"]) dataloader = DataLoader( g, torch.arange(g.num_nodes()).to(g.device), sampler, device=device, batch_size=batch_size, shuffle=False, drop_last=False, num_workers=0, ) buffer_device = torch.device("cpu") pin_memory = buffer_device != device for l_id, layer in enumerate(self.layers): y = torch.empty( g.num_nodes(), self.hid_size if l_id != len(self.layers) - 1 else self.out_size, device=buffer_device, pin_memory=pin_memory, ) feat = feat.to(device) for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader): x = feat[input_nodes] h = layer(blocks[0], x) # len(blocks) = 1 if l_id != len(self.layers) - 1: h = F.relu(h) h = self.dropout(h) # by design, our output nodes are contiguous y[output_nodes[0] : output_nodes[-1] + 1] = h.to(buffer_device) feat = y return y def evaluate(model, graph, dataloader): model.eval() ys = [] y_hats = [] for it, (input_nodes, output_nodes, blocks) in enumerate(dataloader): with torch.no_grad(): if isinstance(graph.ndata["feat"], dict): x = graph.ndata["feat"]["_N"][input_nodes] label = graph.ndata["label"]["_N"][output_nodes] else: x = graph.ndata["feat"][input_nodes] label = graph.ndata["label"][output_nodes] ys.append(label) y_hats.append(model(blocks, x)) num_classes = y_hats[0].shape[1] return MF.accuracy( torch.cat(y_hats), torch.cat(ys), task="multiclass", num_classes=num_classes, ) def layerwise_infer(device, graph, nid, model, batch_size): model.eval() with torch.no_grad(): pred = model.inference(graph, device, batch_size) # pred in buffer_device pred = pred[nid] label = graph.ndata["label"] if isinstance(label, dict): label = label["_N"] label = label[nid].to(device).to(pred.device) num_classes = pred.shape[1] return MF.accuracy(pred, label, task="multiclass", num_classes=num_classes) def train(args, device, g, dataset, model): # create sampler & dataloader train_idx = dataset.train_idx.to(device) val_idx = dataset.val_idx.to(device) use_uva = args.mode == "mixed" batch_size = 1024 fanouts = [5, 10, 15] sampler = NeighborSampler(fanouts) train_dataloader = DataLoader( g, train_idx, sampler, device=device, batch_size=batch_size, shuffle=True, drop_last=False, num_workers=0, use_uva=use_uva, ) val_dataloader = DataLoader( g, val_idx, sampler, device=device, batch_size=batch_size, shuffle=True, drop_last=False, num_workers=0, use_uva=use_uva, ) opt = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=5e-4) for epoch in range(10): model.train() total_loss = 0 st = time.time() for it, (input_nodes, output_nodes, blocks) in enumerate(train_dataloader): if isinstance(g.ndata["feat"], dict): x = g.ndata["feat"]["_N"][input_nodes] y = g.ndata["label"]["_N"][output_nodes] else: x = g.ndata["feat"][input_nodes] y = g.ndata["label"][output_nodes] y_hat = model(blocks, x) loss = F.cross_entropy(y_hat, y) opt.zero_grad() loss.backward() opt.step() total_loss += loss.item() et = time.time() print(f"Time taken for epoch {epoch} with batch_size {batch_size} = {et-st} s") acc = evaluate(model, g, val_dataloader) print( "Epoch {:05d} | Loss {:.4f} | Accuracy {:.4f} ".format( epoch, total_loss / (it + 1), acc.item() ) ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--mode", default="gpu_cugraph_dgl", choices=["cpu", "mixed", "gpu_dgl", "gpu_cugraph_dgl"], help="Training mode." " 'cpu' for CPU training," " 'mixed' for CPU-GPU mixed training, " " 'gpu_dgl' for pure-GPU training, " " 'gpu_cugraph_dgl' for pure-GPU training.", ) args = parser.parse_args() if not torch.cuda.is_available(): args.mode = "cpu" if args.mode == "gpu_cugraph_dgl": set_allocators() print(f"Training in {args.mode} mode.") # load and preprocess dataset print("Loading data") dataset = AsNodePredDataset(DglNodePropPredDataset("ogbn-products")) g = dataset[0] g = dgl.add_self_loop(g) if args.mode == "gpu_cugraph_dgl": g = cugraph_dgl.cugraph_storage_from_heterograph(g.to("cuda")) del dataset.g else: g = g.to("cuda" if args.mode == "gpu_dgl" else "cpu") device = torch.device( "cpu" if args.mode == "cpu" or args.mode == "mixed" else "cuda" ) # create GraphSAGE model feat_shape = ( g.get_node_storage(key="feat", ntype="_N") .fetch(torch.LongTensor([0]).to(device), device=device) .shape[1] ) # no ndata in cugraph storage object in_size = feat_shape out_size = dataset.num_classes model = SAGE(in_size, 256, out_size).to(device) # model training print("Training...") train(args, device, g, dataset, model) # test the model print("Testing...") acc = layerwise_infer(device, g, dataset.test_idx, model, batch_size=4096) print("Test Accuracy {:.4f}".format(acc.item()))
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/run_nx_tests.sh
#!/usr/bin/env bash # # Copyright (c) 2023, NVIDIA CORPORATION. # # NETWORKX_GRAPH_CONVERT=cugraph # Used by networkx versions 3.0 and 3.1 # Must be set to "cugraph" to test the nx-cugraph backend. # # NETWORKX_TEST_BACKEND=cugraph # Replaces NETWORKX_GRAPH_CONVERT for networkx versions >=3.2 # Must be set to "cugraph" to test the nx-cugraph backend. # # NETWORKX_FALLBACK_TO_NX=True (optional) # Used by networkx versions >=3.2. With this set, input graphs will not be # converted to nx-cugraph and the networkx algorithm will be called for # algorithms that we don't implement or if we raise NotImplementedError. # This is sometimes helpful to get increased testing and coverage, but # testing takes longer. Without it, tests will xfail when encountering a # function that we don't implement. # # Coverage of `nx_cugraph.algorithms` is reported and is a good sanity check # that algorithms run. # Warning: cugraph has a .coveragerc file in the <repo root>/python directory, # so be mindful of its contents and the CWD when running. # FIXME: should something be added to detect/prevent the above? NETWORKX_GRAPH_CONVERT=cugraph \ NETWORKX_TEST_BACKEND=cugraph \ NETWORKX_FALLBACK_TO_NX=True \ pytest \ --pyargs networkx \ --cov=nx_cugraph.algorithms \ --cov-report term-missing \ --no-cov-on-fail \ "$@"
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/pyproject.toml
# Copyright (c) 2023, NVIDIA CORPORATION. [build-system] requires = [ "setuptools>=61.0.0", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. build-backend = "setuptools.build_meta" [project] name = "nx-cugraph" dynamic = ["version"] description = "cugraph backend for NetworkX" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" classifiers = [ "Development Status :: 3 - Alpha", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3 :: Only", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ "cupy-cuda11x>=12.0.0", "networkx>=3.0", "numpy>=1.21", "pylibcugraph==23.12.*", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.optional-dependencies] test = [ "packaging>=21", "pandas", "pytest", "pytest-benchmark", "pytest-cov", "pytest-mpl", "pytest-xdist", "scipy", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cugraph" Documentation = "https://docs.rapids.ai/api/cugraph/stable/" [project.entry-points."networkx.plugins"] cugraph = "nx_cugraph.interface:BackendInterface" [project.entry-points."networkx.plugin_info"] cugraph = "_nx_cugraph:get_info" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "nx_cugraph/VERSION"} [tool.setuptools.packages.find] include = [ "nx_cugraph*", "nx_cugraph.*", "_nx_cugraph*", "_nx_cugraph.*", ] [tool.black] line-length = 88 target-version = ["py39", "py310", "py311"] [tool.isort] sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"] profile = "black" skip_gitignore = true float_to_top = true default_section = "THIRDPARTY" known_first_party = "nx_cugraph" line_length = 88 extend_skip_glob = [ "nx_cugraph/__init__.py", "nx_cugraph/classes/__init__.py", ] [tool.pytest.ini_options] minversion = "6.0" testpaths = "nx_cugraph/tests" xfail_strict = true markers = [ "slow: Skipped unless --runslow passed", ] log_cli_level = "info" filterwarnings = [ # See: https://docs.python.org/3/library/warnings.html#describing-warning-filters # and: https://docs.pytest.org/en/7.2.x/how-to/capture-warnings.html#controlling-warnings # "error", ] python_files = [ "bench_*.py", "test_*.py", ] python_functions = [ "bench_*", "test_*", ] addopts = [ "--strict-config", # Force error if config is mispelled "--strict-markers", # Force error if marker is mispelled (must be defined in config) # "-ra", # Print summary of all fails/errors "--benchmark-warmup=off", "--benchmark-max-time=0", "--benchmark-min-rounds=1", "--benchmark-columns=min,median,max", ] [tool.coverage.run] branch = true source = ["nx_cugraph"] omit = [] [tool.coverage.report] ignore_errors = false precision = 1 fail_under = 0 skip_covered = false # Nice to see fully covered files when running `run_nx_tests.sh` skip_empty = true exclude_lines = [ "pragma: no cover", "raise AssertionError", "raise NotImplementedError", ] [tool.ruff] # https://github.com/charliermarsh/ruff/ line-length = 88 target-version = "py39" unfixable = [ "F841", # unused-variable (Note: can leave useless expression) ] select = [ "ALL", ] external = [ # noqa codes that ruff doesn't know about: https://github.com/charliermarsh/ruff#external ] ignore = [ # Would be nice to fix these "D100", # Missing docstring in public module "D101", # Missing docstring in public class "D102", # Missing docstring in public method "D103", # Missing docstring in public function "D104", # Missing docstring in public package "D105", # Missing docstring in magic method # Maybe consider # "SIM300", # Yoda conditions are discouraged, use ... instead (Note: we're not this picky) # "SIM401", # Use dict.get ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer) # "TRY004", # Prefer `TypeError` exception for invalid type (Note: good advice, but not worth the nuisance) "B904", # Bare `raise` inside exception clause (like TRY200; sometimes okay) "TRY200", # Use `raise from` to specify exception cause (Note: sometimes okay to raise original exception) # Intentionally ignored "A003", # Class attribute ... is shadowing a python builtin "ANN101", # Missing type annotation for `self` in method "ARG004", # Unused static method argument: `...` "COM812", # Trailing comma missing "D203", # 1 blank line required before class docstring (Note: conflicts with D211, which is preferred) "D400", # First line should end with a period (Note: prefer D415, which also allows "?" and "!") "F403", # `from .classes import *` used; unable to detect undefined names (Note: used to match networkx) "N801", # Class name ... should use CapWords convention (Note:we have a few exceptions to this) "N802", # Function name ... should be lowercase "N803", # Argument name ... should be lowercase (Maybe okay--except in tests) "N806", # Variable ... in function should be lowercase "N807", # Function name should not start and end with `__` "N818", # Exception name ... should be named with an Error suffix (Note: good advice) "PLR0911", # Too many return statements "PLR0912", # Too many branches "PLR0913", # Too many arguments to function call "PLR0915", # Too many statements "PLR2004", # Magic number used in comparison, consider replacing magic with a constant variable "PLW2901", # Outer for loop variable ... overwritten by inner assignment target (Note: good advice, but too strict) "RET502", # Do not implicitly `return None` in function able to return non-`None` value "RET503", # Missing explicit `return` at the end of function able to return non-`None` value "RET504", # Unnecessary variable assignment before `return` statement "S110", # `try`-`except`-`pass` detected, consider logging the exception (Note: good advice, but we don't log) "S112", # `try`-`except`-`continue` detected, consider logging the exception (Note: good advice, but we don't log) "SIM102", # Use a single `if` statement instead of nested `if` statements (Note: often necessary) "SIM105", # Use contextlib.suppress(...) instead of try-except-pass (Note: try-except-pass is much faster) "SIM108", # Use ternary operator ... instead of if-else-block (Note: if-else better for coverage and sometimes clearer) "TRY003", # Avoid specifying long messages outside the exception class (Note: why?) # Ignored categories "C90", # mccabe (Too strict, but maybe we should make things less complex) "I", # isort (Should we replace `isort` with this?) "ANN", # flake8-annotations "BLE", # flake8-blind-except (Maybe consider) "FBT", # flake8-boolean-trap (Why?) "DJ", # flake8-django (We don't use django) "EM", # flake8-errmsg (Perhaps nicer, but too much work) # "ICN", # flake8-import-conventions (Doesn't allow "_" prefix such as `_np`) "PYI", # flake8-pyi (We don't have stub files yet) "SLF", # flake8-self (We can use our own private variables--sheesh!) "TID", # flake8-tidy-imports (Rely on isort and our own judgement) # "TCH", # flake8-type-checking "ARG", # flake8-unused-arguments (Sometimes helpful, but too strict) "TD", # flake8-todos (Maybe okay to add some of these) "FIX", # flake8-fixme (like flake8-todos) "ERA", # eradicate (We like code in comments!) "PD", # pandas-vet (Intended for scripts that use pandas, not libraries) ] [tool.ruff.per-file-ignores] "__init__.py" = ["F401"] # Allow unused imports (w/o defining `__all__`) # Allow assert, print, RNG, and no docstring "nx_cugraph/**/tests/*py" = ["S101", "S311", "T201", "D103", "D100"] "_nx_cugraph/__init__.py" = ["E501"] "nx_cugraph/algorithms/**/*py" = ["D205", "D401"] # Allow flexible docstrings for algorithms [tool.ruff.flake8-annotations] mypy-init-return = true [tool.ruff.flake8-builtins] builtins-ignorelist = ["copyright"] [tool.ruff.flake8-pytest-style] fixture-parentheses = false mark-parentheses = false [tool.ruff.pydocstyle] convention = "numpy"
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/.flake8
# Copyright (c) 2023, NVIDIA CORPORATION. [flake8] max-line-length = 88 inline-quotes = " extend-ignore = E203, SIM105, SIM401, # E203 whitespace before ':' (to be compatible with black) per-file-ignores = nx_cugraph/tests/*.py:T201, __init__.py:F401,F403, _nx_cugraph/__init__.py:E501,
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/README.md
# nx-cugraph ## Description [RAPIDS](https://rapids.ai) nx-cugraph is a [backend to NetworkX](https://networkx.org/documentation/stable/reference/utils.html#backends) to run supported algorithms with GPU acceleration. ## System Requirements nx-cugraph requires the following: * NVIDIA GPU, Pascal architecture or later * CUDA 11.2, 11.4, 11.5, 11.8, or 12.0 * Python versions 3.9, 3.10, or 3.11 * NetworkX >= version 3.2 More details about system requirements can be found in the [RAPIDS System Requirements documentation](https://docs.rapids.ai/install#system-req). ## Installation nx-cugraph can be installed using either conda or pip. ### conda ``` conda install -c rapidsai-nightly -c conda-forge -c nvidia nx-cugraph ``` ### pip ``` python -m pip install nx-cugraph-cu11 --extra-index-url https://pypi.nvidia.com ``` Notes: * Nightly wheel builds will not be available until the 23.12 release, therefore the index URL for the stable release version is being used in the pip install command above. * Additional information relevant to installing any RAPIDS package can be found [here](https://rapids.ai/#quick-start). ## Enabling nx-cugraph NetworkX will use nx-cugraph as the graph analytics backend if any of the following are used: ### `NETWORKX_AUTOMATIC_BACKENDS` environment variable. The `NETWORKX_AUTOMATIC_BACKENDS` environment variable can be used to have NetworkX automatically dispatch to specified backends an API is called that the backend supports. Set `NETWORKX_AUTOMATIC_BACKENDS=cugraph` to use nx-cugraph to GPU accelerate supported APIs with no code changes. Example: ``` bash> NETWORKX_AUTOMATIC_BACKENDS=cugraph python my_networkx_script.py ``` ### `backend=` keyword argument To explicitly specify a particular backend for an API, use the `backend=` keyword argument. This argument takes precedence over the `NETWORKX_AUTOMATIC_BACKENDS` environment variable. This requires anyone running code that uses the `backend=` keyword argument to have the specified backend installed. Example: ``` nx.betweenness_centrality(cit_patents_graph, k=k, backend="cugraph") ``` ### Type-based dispatching NetworkX also supports automatically dispatching to backends associated with specific graph types. Like the `backend=` keyword argument example above, this requires the user to write code for a specific backend, and therefore requires the backend to be installed, but has the advantage of ensuring a particular behavior without the potential for runtime conversions. To use type-based dispatching with nx-cugraph, the user must import the backend directly in their code to access the utilities provided to create a Graph instance specifically for the nx-cugraph backend. Example: ``` import networkx as nx import nx_cugraph as nxcg G = nx.Graph() ... nxcg_G = nxcg.from_networkx(G) # conversion happens once here nx.betweenness_centrality(nxcg_G, k=1000) # nxcg Graph type causes cugraph backend # to be used, no conversion necessary ``` ## Supported Algorithms The nx-cugraph backend to NetworkX connects [pylibcugraph](../../readme_pages/pylibcugraph.md) (cuGraph's low-level python interface to its CUDA-based graph analytics library) and [CuPy](https://cupy.dev/) (a GPU-accelerated array library) to NetworkX's familiar and easy-to-use API. Below is the list of algorithms (many listed using pylibcugraph names), available today in pylibcugraph or implemented using CuPy, that are or will be supported in nx-cugraph. | feature/algo | release/target version | | ----- | ----- | | analyze_clustering_edge_cut | ? | | analyze_clustering_modularity | ? | | analyze_clustering_ratio_cut | ? | | balanced_cut_clustering | ? | | betweenness_centrality | 23.10 | | bfs | ? | | connected_components | 23.12 | | core_number | ? | | degree_centrality | 23.12 | | ecg | ? | | edge_betweenness_centrality | 23.10 | | ego_graph | ? | | eigenvector_centrality | 23.12 | | get_two_hop_neighbors | ? | | hits | 23.12 | | in_degree_centrality | 23.12 | | induced_subgraph | ? | | jaccard_coefficients | ? | | katz_centrality | 23.12 | | k_core | ? | | k_truss_subgraph | 23.12 | | leiden | ? | | louvain | 23.10 | | node2vec | ? | | out_degree_centrality | 23.12 | | overlap_coefficients | ? | | pagerank | 23.12 | | personalized_pagerank | ? | | sorensen_coefficients | ? | | spectral_modularity_maximization | ? | | sssp | 23.12 | | strongly_connected_components | ? | | triangle_count | ? | | uniform_neighbor_sample | ? | | uniform_random_walks | ? | | weakly_connected_components | ? | To request nx-cugraph backend support for a NetworkX API that is not listed above, visit the [cuGraph GitHub repo](https://github.com/rapidsai/cugraph).
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/lint.yaml
# Copyright (c) 2023, NVIDIA CORPORATION. # # https://pre-commit.com/ # # Before first use: `pre-commit install` # To run: `make lint` # To update: `make lint-update` # - &flake8_dependencies below needs updated manually fail_fast: false default_language_version: python: python3 repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-added-large-files - id: check-case-conflict - id: check-merge-conflict - id: check-symlinks - id: check-ast - id: check-toml - id: check-yaml - id: debug-statements - id: end-of-file-fixer exclude_types: [svg] - id: mixed-line-ending - id: trailing-whitespace - repo: https://github.com/abravalheri/validate-pyproject rev: v0.15 hooks: - id: validate-pyproject name: Validate pyproject.toml - repo: https://github.com/PyCQA/autoflake rev: v2.2.1 hooks: - id: autoflake args: [--in-place] - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py39-plus] - repo: https://github.com/psf/black rev: 23.10.1 hooks: - id: black # - id: black-jupyter - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.3 hooks: - id: ruff args: [--fix-only, --show-fixes] # --unsafe-fixes] - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 args: ['--per-file-ignores=_nx_cugraph/__init__.py:E501', '--extend-ignore=SIM105'] # Why is this necessary? additional_dependencies: &flake8_dependencies # These versions need updated manually - flake8==6.1.0 - flake8-bugbear==23.9.16 - flake8-simplify==0.21.0 - repo: https://github.com/asottile/yesqa rev: v1.5.0 hooks: - id: yesqa additional_dependencies: *flake8_dependencies - repo: https://github.com/codespell-project/codespell rev: v2.2.6 hooks: - id: codespell types_or: [python, rst, markdown] additional_dependencies: [tomli] files: ^(nx_cugraph|docs)/ - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.3 hooks: - id: ruff - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: no-commit-to-branch args: [-p, "^branch-2....$"]
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/conftest.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def pytest_addoption(parser): parser.addoption( "--bench", action="store_true", default=False, help="Run benchmarks (sugar for --benchmark-enable) and skip other tests" " (to run both benchmarks AND tests, use --all)", ) parser.addoption( "--all", action="store_true", default=False, help="Run benchmarks AND tests (unlike --bench, which only runs benchmarks)", )
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/Makefile
# Copyright (c) 2023, NVIDIA CORPORATION. SHELL= /bin/bash .PHONY: all all: plugin-info lint .PHONY: lint lint: git ls-files | xargs pre-commit run --config lint.yaml --files .PHONY: lint-update lint-update: pre-commit autoupdate --config lint.yaml .PHONY: plugin-info plugin-info: python _nx_cugraph/__init__.py
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/setup.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import find_packages, setup packages = find_packages(include=["nx_cugraph*"]) setup( package_data={key: ["VERSION"] for key in packages}, )
0
rapidsai_public_repos/cugraph/python
rapidsai_public_repos/cugraph/python/nx-cugraph/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/convert_matrix.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cupy as cp import networkx as nx import numpy as np from .generators._utils import _create_using_class from .utils import index_dtype, networkx_algorithm __all__ = [ "from_pandas_edgelist", "from_scipy_sparse_array", ] @networkx_algorithm def from_pandas_edgelist( df, source="source", target="target", edge_attr=None, create_using=None, edge_key=None, ): """cudf.DataFrame inputs also supported.""" graph_class, inplace = _create_using_class(create_using) src_array = df[source].to_numpy() dst_array = df[target].to_numpy() # Renumber step 0: node keys nodes = np.unique(np.concatenate([src_array, dst_array])) N = nodes.size kwargs = {} if N > 0 and ( nodes[0] != 0 or nodes[N - 1] != N - 1 or ( nodes.dtype.kind not in {"i", "u"} and not (nodes == np.arange(N, dtype=np.int64)).all() ) ): # We need to renumber indices--np.searchsorted to the rescue! kwargs["id_to_key"] = nodes.tolist() src_indices = cp.array(np.searchsorted(nodes, src_array), index_dtype) dst_indices = cp.array(np.searchsorted(nodes, dst_array), index_dtype) else: src_indices = cp.array(src_array) dst_indices = cp.array(dst_array) if not graph_class.is_directed(): # Symmetrize the edges mask = src_indices != dst_indices if mask.all(): mask = None src_indices, dst_indices = ( cp.hstack( (src_indices, dst_indices[mask] if mask is not None else dst_indices) ), cp.hstack( (dst_indices, src_indices[mask] if mask is not None else src_indices) ), ) if edge_attr is not None: # Additional columns requested for edge data if edge_attr is True: attr_col_headings = df.columns.difference({source, target}).to_list() elif isinstance(edge_attr, (list, tuple)): attr_col_headings = edge_attr else: attr_col_headings = [edge_attr] if len(attr_col_headings) == 0: raise nx.NetworkXError( "Invalid edge_attr argument: No columns found with name: " f"{attr_col_headings}" ) try: edge_values = { key: cp.array(val.to_numpy()) for key, val in df[attr_col_headings].items() } except (KeyError, TypeError) as exc: raise nx.NetworkXError(f"Invalid edge_attr argument: {edge_attr}") from exc if not graph_class.is_directed(): # Symmetrize the edges edge_values = { key: cp.hstack((val, val[mask] if mask is not None else val)) for key, val in edge_values.items() } kwargs["edge_values"] = edge_values if graph_class.is_multigraph() and edge_key is not None: try: edge_keys = df[edge_key].to_list() except (KeyError, TypeError) as exc: raise nx.NetworkXError( f"Invalid edge_key argument: {edge_key}" ) from exc if not graph_class.is_directed(): # Symmetrize the edges edge_keys = cp.hstack( (edge_keys, edge_keys[mask] if mask is not None else edge_keys) ) kwargs["edge_keys"] = edge_keys G = graph_class.from_coo(N, src_indices, dst_indices, **kwargs) if inplace: return create_using._become(G) return G @networkx_algorithm def from_scipy_sparse_array( A, parallel_edges=False, create_using=None, edge_attribute="weight" ): graph_class, inplace = _create_using_class(create_using) m, n = A.shape if m != n: raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}") if A.format != "coo": A = A.tocoo() if A.dtype.kind in {"i", "u"} and graph_class.is_multigraph() and parallel_edges: src_indices = cp.array(np.repeat(A.row, A.data), index_dtype) dst_indices = cp.array(np.repeat(A.col, A.data), index_dtype) weight = cp.empty(src_indices.size, A.data.dtype) weight[:] = 1 else: src_indices = cp.array(A.row, index_dtype) dst_indices = cp.array(A.col, index_dtype) weight = cp.array(A.data) G = graph_class.from_coo( n, src_indices, dst_indices, edge_values={"weight": weight} ) if inplace: return create_using._become(G) return G
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import importlib.resources # Read VERSION file from the module that is symlinked to VERSION file # in the root of the repo at build time or copied to the moudle at # installation. VERSION is a separate file that allows CI build-time scripts # to update version info (including commit hashes) without modifying # source files. __version__ = ( importlib.resources.files("nx_cugraph").joinpath("VERSION").read_text().strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/convert.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import itertools import operator as op from collections import Counter from collections.abc import Mapping from typing import TYPE_CHECKING import cupy as cp import networkx as nx import numpy as np import nx_cugraph as nxcg from .utils import index_dtype if TYPE_CHECKING: # pragma: no cover from nx_cugraph.typing import AttrKey, Dtype, EdgeValue, NodeValue, any_ndarray __all__ = [ "from_networkx", "to_networkx", ] concat = itertools.chain.from_iterable # A "required" attribute is one that all edges or nodes must have or KeyError is raised REQUIRED = ... def from_networkx( graph: nx.Graph, edge_attrs: AttrKey | dict[AttrKey, EdgeValue | None] | None = None, edge_dtypes: Dtype | dict[AttrKey, Dtype | None] | None = None, *, node_attrs: AttrKey | dict[AttrKey, NodeValue | None] | None = None, node_dtypes: Dtype | dict[AttrKey, Dtype | None] | None = None, preserve_all_attrs: bool = False, preserve_edge_attrs: bool = False, preserve_node_attrs: bool = False, preserve_graph_attrs: bool = False, as_directed: bool = False, name: str | None = None, graph_name: str | None = None, ) -> nxcg.Graph: """Convert a networkx graph to nx_cugraph graph; can convert all attributes. Parameters ---------- G : networkx.Graph edge_attrs : str or dict, optional Dict that maps edge attributes to default values if missing in ``G``. If None, then no edge attributes will be converted. If default value is None, then missing values are handled with a mask. A default value of ``nxcg.convert.REQUIRED`` or ``...`` indicates that all edges have data for this attribute, and raise `KeyError` if not. For convenience, `edge_attrs` may be a single attribute with default 1; for example ``edge_attrs="weight"``. edge_dtypes : dtype or dict, optional node_attrs : str or dict, optional Dict that maps node attributes to default values if missing in ``G``. If None, then no node attributes will be converted. If default value is None, then missing values are handled with a mask. A default value of ``nxcg.convert.REQUIRED`` or ``...`` indicates that all edges have data for this attribute, and raise `KeyError` if not. For convenience, `node_attrs` may be a single attribute with no default; for example ``node_attrs="weight"``. node_dtypes : dtype or dict, optional preserve_all_attrs : bool, default False If True, then equivalent to setting preserve_edge_attrs, preserve_node_attrs, and preserve_graph_attrs to True. preserve_edge_attrs : bool, default False Whether to preserve all edge attributes. preserve_node_attrs : bool, default False Whether to preserve all node attributes. preserve_graph_attrs : bool, default False Whether to preserve all graph attributes. as_directed : bool, default False If True, then the returned graph will be directed regardless of input. If False, then the returned graph type is determined by input graph. name : str, optional The name of the algorithm when dispatched from networkx. graph_name : str, optional The name of the graph argument geing converted when dispatched from networkx. Returns ------- nx_cugraph.Graph Notes ----- For optimal performance, be as specific as possible about what is being converted: 1. Do you need edge values? Creating a graph with just the structure is the fastest. 2. Do you know the edge attribute(s) you need? Specify with `edge_attrs`. 3. Do you know the default values? Specify with ``edge_attrs={weight: default}``. 4. Do you know if all edges have values? Specify with ``edge_attrs={weight: ...}``. 5. Do you know the dtype of attributes? Specify with `edge_dtypes`. Conversely, using ``preserve_edge_attrs=True`` or ``preserve_all_attrs=True`` are the slowest, but are also the most flexible and generic. See Also -------- to_networkx : The opposite; convert nx_cugraph graph to networkx graph """ # This uses `graph._adj` and `graph._node`, which are private attributes in NetworkX if not isinstance(graph, nx.Graph): if isinstance(graph, nx.classes.reportviews.NodeView): # Convert to a Graph with only nodes (no edges) G = nx.Graph() G.add_nodes_from(graph.items()) graph = G else: raise TypeError(f"Expected networkx.Graph; got {type(graph)}") if preserve_all_attrs: preserve_edge_attrs = True preserve_node_attrs = True preserve_graph_attrs = True if edge_attrs is not None: if isinstance(edge_attrs, Mapping): # Copy so we don't mutate the original edge_attrs = dict(edge_attrs) else: edge_attrs = {edge_attrs: 1} if node_attrs is not None: if isinstance(node_attrs, Mapping): # Copy so we don't mutate the original node_attrs = dict(node_attrs) else: node_attrs = {node_attrs: None} if graph.__class__ in {nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph}: # This is a NetworkX private attribute, but is much faster to use adj = graph._adj else: adj = graph.adj if isinstance(adj, nx.classes.coreviews.FilterAdjacency): adj = {k: dict(v) for k, v in adj.items()} N = len(adj) if ( not preserve_edge_attrs and not edge_attrs # Faster than graph.number_of_edges() == 0 or next(concat(rowdata.values() for rowdata in adj.values()), None) is None ): # Either we weren't asked to preserve edge attributes, or there are no edges edge_attrs = None elif preserve_edge_attrs: # Using comprehensions should be just as fast starting in Python 3.11 it = concat(map(dict.values, adj.values())) if graph.is_multigraph(): it = concat(map(dict.values, it)) # PERF: should we add `filter(None, ...)` to remove empty data dicts? attr_sets = set(map(frozenset, it)) attrs = frozenset.union(*attr_sets) edge_attrs = dict.fromkeys(attrs, REQUIRED) if len(attr_sets) > 1: # Determine which edges have missing data for attr, count in Counter(concat(attr_sets)).items(): if count != len(attr_sets): edge_attrs[attr] = None elif None in edge_attrs.values(): # Required edge attributes have a default of None in `edge_attrs` # Verify all edge attributes are present! required = frozenset( attr for attr, default in edge_attrs.items() if default is None ) if len(required) == 1: # Fast path for the common case of a single attribute with no default [attr] = required if graph.is_multigraph(): it = ( attr in edgedata for rowdata in adj.values() for multiedges in rowdata.values() for edgedata in multiedges.values() ) else: it = ( attr in edgedata for rowdata in adj.values() for edgedata in rowdata.values() ) if next(it): if all(it): # All edges have data edge_attrs[attr] = REQUIRED # Else some edges have attribute (default already None) elif not any(it): # No edges have attribute del edge_attrs[attr] # Else some edges have attribute (default already None) else: it = concat(map(dict.values, adj.values())) if graph.is_multigraph(): it = concat(map(dict.values, it)) attr_sets = set(map(required.intersection, it)) for attr in required - frozenset.union(*attr_sets): # No edges have these attributes del edge_attrs[attr] for attr in frozenset.intersection(*attr_sets): # All edges have these attributes edge_attrs[attr] = REQUIRED if N == 0: node_attrs = None elif preserve_node_attrs: attr_sets = set(map(frozenset, graph._node.values())) attrs = frozenset.union(*attr_sets) node_attrs = dict.fromkeys(attrs, REQUIRED) if len(attr_sets) > 1: # Determine which nodes have missing data for attr, count in Counter(concat(attr_sets)).items(): if count != len(attr_sets): node_attrs[attr] = None elif node_attrs and None in node_attrs.values(): # Required node attributes have a default of None in `node_attrs` # Verify all node attributes are present! required = frozenset( attr for attr, default in node_attrs.items() if default is None ) if len(required) == 1: # Fast path for the common case of a single attribute with no default [attr] = required it = (attr in nodedata for nodedata in graph._node.values()) if next(it): if all(it): # All nodes have data node_attrs[attr] = REQUIRED # Else some nodes have attribute (default already None) elif not any(it): # No nodes have attribute del node_attrs[attr] # Else some nodes have attribute (default already None) else: attr_sets = set(map(required.intersection, graph._node.values())) for attr in required - frozenset.union(*attr_sets): # No nodes have these attributes del node_attrs[attr] for attr in frozenset.intersection(*attr_sets): # All nodes have these attributes node_attrs[attr] = REQUIRED key_to_id = dict(zip(adj, range(N))) dst_iter = concat(adj.values()) try: no_renumber = all(k == v for k, v in key_to_id.items()) except Exception: no_renumber = False if no_renumber: key_to_id = None else: dst_iter = map(key_to_id.__getitem__, dst_iter) if graph.is_multigraph(): dst_indices = np.fromiter(dst_iter, index_dtype) num_multiedges = np.fromiter( map(len, concat(map(dict.values, adj.values()))), index_dtype ) # cp.repeat is slow to use here, so use numpy instead dst_indices = cp.array(np.repeat(dst_indices, num_multiedges)) # Determine edge keys and edge ids for multigraphs edge_keys = list(concat(concat(map(dict.values, adj.values())))) edge_indices = cp.fromiter( concat(map(range, map(len, concat(map(dict.values, adj.values()))))), index_dtype, ) if edge_keys == edge_indices.tolist(): edge_keys = None # Prefer edge_indices else: dst_indices = cp.fromiter(dst_iter, index_dtype) edge_values = {} edge_masks = {} if edge_attrs: if edge_dtypes is None: edge_dtypes = {} elif not isinstance(edge_dtypes, Mapping): edge_dtypes = dict.fromkeys(edge_attrs, edge_dtypes) for edge_attr, edge_default in edge_attrs.items(): dtype = edge_dtypes.get(edge_attr) if edge_default is None: vals = [] append = vals.append if graph.is_multigraph(): iter_mask = ( append( edgedata[edge_attr] if (present := edge_attr in edgedata) else False ) or present for rowdata in adj.values() for multiedges in rowdata.values() for edgedata in multiedges.values() ) else: iter_mask = ( append( edgedata[edge_attr] if (present := edge_attr in edgedata) else False ) or present for rowdata in adj.values() for edgedata in rowdata.values() ) edge_masks[edge_attr] = cp.fromiter(iter_mask, bool) edge_values[edge_attr] = cp.array(vals, dtype) # if vals.ndim > 1: ... else: if edge_default is REQUIRED: # Using comprehensions should be fast starting in Python 3.11 # iter_values = ( # edgedata[edge_attr] # for rowdata in adj.values() # for edgedata in rowdata.values() # ) it = concat(map(dict.values, adj.values())) if graph.is_multigraph(): it = concat(map(dict.values, it)) iter_values = map(op.itemgetter(edge_attr), it) elif graph.is_multigraph(): iter_values = ( edgedata.get(edge_attr, edge_default) for rowdata in adj.values() for multiedges in rowdata.values() for edgedata in multiedges.values() ) else: iter_values = ( edgedata.get(edge_attr, edge_default) for rowdata in adj.values() for edgedata in rowdata.values() ) if dtype is None: edge_values[edge_attr] = cp.array(list(iter_values)) else: edge_values[edge_attr] = cp.fromiter(iter_values, dtype) # if vals.ndim > 1: ... # cp.repeat is slow to use here, so use numpy instead src_indices = np.repeat( np.arange(N, dtype=index_dtype), np.fromiter(map(len, adj.values()), index_dtype), ) if graph.is_multigraph(): src_indices = np.repeat(src_indices, num_multiedges) src_indices = cp.array(src_indices) node_values = {} node_masks = {} if node_attrs: nodes = graph._node if node_dtypes is None: node_dtypes = {} elif not isinstance(node_dtypes, Mapping): node_dtypes = dict.fromkeys(node_attrs, node_dtypes) for node_attr, node_default in node_attrs.items(): # Iterate over `adj` to ensure consistent order dtype = node_dtypes.get(node_attr) if node_default is None: vals = [] append = vals.append iter_mask = ( append( nodedata[node_attr] if (present := node_attr in (nodedata := nodes[node_id])) else False ) or present for node_id in adj ) # Node values may be numpy or cupy arrays (useful for str, object, etc). # Someday we'll let the user choose np or cp, and support edge values. node_mask = np.fromiter(iter_mask, bool) node_value = np.array(vals, dtype) try: node_value = cp.array(node_value) except ValueError: pass else: node_mask = cp.array(node_mask) node_values[node_attr] = node_value node_masks[node_attr] = node_mask # if vals.ndim > 1: ... else: if node_default is REQUIRED: iter_values = (nodes[node_id][node_attr] for node_id in adj) else: iter_values = ( nodes[node_id].get(node_attr, node_default) for node_id in adj ) # Node values may be numpy or cupy arrays (useful for str, object, etc). # Someday we'll let the user choose np or cp, and support edge values. if dtype is None: node_value = np.array(list(iter_values)) else: node_value = np.fromiter(iter_values, dtype) try: node_value = cp.array(node_value) except ValueError: pass node_values[node_attr] = node_value # if vals.ndim > 1: ... if graph.is_multigraph(): if graph.is_directed() or as_directed: klass = nxcg.MultiDiGraph else: klass = nxcg.MultiGraph rv = klass.from_coo( N, src_indices, dst_indices, edge_indices, edge_values, edge_masks, node_values, node_masks, key_to_id=key_to_id, edge_keys=edge_keys, ) else: if graph.is_directed() or as_directed: klass = nxcg.DiGraph else: klass = nxcg.Graph rv = klass.from_coo( N, src_indices, dst_indices, edge_values, edge_masks, node_values, node_masks, key_to_id=key_to_id, ) if preserve_graph_attrs: rv.graph.update(graph.graph) # deepcopy? return rv def _iter_attr_dicts( values: dict[AttrKey, any_ndarray[EdgeValue | NodeValue]], masks: dict[AttrKey, any_ndarray[bool]], ): full_attrs = list(values.keys() - masks.keys()) if full_attrs: full_dicts = ( dict(zip(full_attrs, vals)) for vals in zip(*(values[attr].tolist() for attr in full_attrs)) ) partial_attrs = list(values.keys() & masks.keys()) if partial_attrs: partial_dicts = ( {k: v for k, (v, m) in zip(partial_attrs, vals_masks) if m} for vals_masks in zip( *( zip(values[attr].tolist(), masks[attr].tolist()) for attr in partial_attrs ) ) ) if full_attrs and partial_attrs: full_dicts = (d1.update(d2) or d1 for d1, d2 in zip(full_dicts, partial_dicts)) elif partial_attrs: full_dicts = partial_dicts return full_dicts def to_networkx(G: nxcg.Graph, *, sort_edges: bool = False) -> nx.Graph: """Convert a nx_cugraph graph to networkx graph. All edge and node attributes and ``G.graph`` properties are converted. Parameters ---------- G : nx_cugraph.Graph sort_edges : bool, default False Whether to sort the edge data of the input graph by (src, dst) indices before converting. This can be useful to convert to networkx graphs that iterate over edges consistently since edges are stored in dicts in the order they were added. Returns ------- networkx.Graph See Also -------- from_networkx : The opposite; convert networkx graph to nx_cugraph graph """ rv = G.to_networkx_class()() id_to_key = G.id_to_key if sort_edges: G._sort_edge_indices() node_values = G.node_values node_masks = G.node_masks if node_values: node_iter = range(len(G)) if id_to_key is not None: node_iter = map(id_to_key.__getitem__, node_iter) full_node_dicts = _iter_attr_dicts(node_values, node_masks) rv.add_nodes_from(zip(node_iter, full_node_dicts)) elif id_to_key is not None: rv.add_nodes_from(id_to_key) else: rv.add_nodes_from(range(len(G))) src_indices = G.src_indices dst_indices = G.dst_indices edge_values = G.edge_values edge_masks = G.edge_masks if not G.is_directed(): # Only add upper triangle of the adjacency matrix so we don't double-add edges mask = src_indices <= dst_indices src_indices = src_indices[mask] dst_indices = dst_indices[mask] if edge_values: edge_values = {k: v[mask] for k, v in edge_values.items()} if edge_masks: edge_masks = {k: v[mask] for k, v in edge_masks.items()} src_indices = src_iter = src_indices.tolist() dst_indices = dst_iter = dst_indices.tolist() if id_to_key is not None: src_iter = map(id_to_key.__getitem__, src_indices) dst_iter = map(id_to_key.__getitem__, dst_indices) if G.is_multigraph() and (G.edge_keys is not None or G.edge_indices is not None): if G.edge_keys is not None: edge_keys = G.edge_keys else: edge_keys = G.edge_indices.tolist() if edge_values: full_edge_dicts = _iter_attr_dicts(edge_values, edge_masks) rv.add_edges_from(zip(src_iter, dst_iter, edge_keys, full_edge_dicts)) else: rv.add_edges_from(zip(src_iter, dst_iter, edge_keys)) elif edge_values: full_edge_dicts = _iter_attr_dicts(edge_values, edge_masks) rv.add_edges_from(zip(src_iter, dst_iter, full_edge_dicts)) else: rv.add_edges_from(zip(src_iter, dst_iter)) rv.graph.update(G.graph) return rv def _to_graph( G, edge_attr: AttrKey | None = None, edge_default: EdgeValue | None = 1, edge_dtype: Dtype | None = None, ) -> nxcg.Graph | nxcg.DiGraph: """Ensure that input type is a nx_cugraph graph, and convert if necessary. Directed and undirected graphs are both allowed. This is an internal utility function and may change or be removed. """ if isinstance(G, nxcg.Graph): return G if isinstance(G, nx.Graph): return from_networkx( G, {edge_attr: edge_default} if edge_attr is not None else None, edge_dtype ) # TODO: handle cugraph.Graph raise TypeError def _to_directed_graph( G, edge_attr: AttrKey | None = None, edge_default: EdgeValue | None = 1, edge_dtype: Dtype | None = None, ) -> nxcg.DiGraph: """Ensure that input type is a nx_cugraph DiGraph, and convert if necessary. Undirected graphs will be converted to directed. This is an internal utility function and may change or be removed. """ if isinstance(G, nxcg.DiGraph): return G if isinstance(G, nxcg.Graph): return G.to_directed() if isinstance(G, nx.Graph): return from_networkx( G, {edge_attr: edge_default} if edge_attr is not None else None, edge_dtype, as_directed=True, ) # TODO: handle cugraph.Graph raise TypeError def _to_undirected_graph( G, edge_attr: AttrKey | None = None, edge_default: EdgeValue | None = 1, edge_dtype: Dtype | None = None, ) -> nxcg.Graph: """Ensure that input type is a nx_cugraph Graph, and convert if necessary. Only undirected graphs are allowed. Directed graphs will raise ValueError. This is an internal utility function and may change or be removed. """ if isinstance(G, nxcg.Graph): if G.is_directed(): raise ValueError("Only undirected graphs supported; got a directed graph") return G if isinstance(G, nx.Graph): return from_networkx( G, {edge_attr: edge_default} if edge_attr is not None else None, edge_dtype ) # TODO: handle cugraph.Graph raise TypeError
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from networkx.exception import * from . import utils from . import classes from .classes import * from . import convert from .convert import * from . import convert_matrix from .convert_matrix import * from . import generators from .generators import * from . import algorithms from .algorithms import * from nx_cugraph._version import __git_commit__, __version__
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/VERSION
23.12.00
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/typing.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from collections.abc import Hashable from typing import TypeVar import cupy as cp import numpy as np AttrKey = TypeVar("AttrKey", bound=Hashable) EdgeKey = TypeVar("EdgeKey", bound=Hashable) NodeKey = TypeVar("NodeKey", bound=Hashable) EdgeTuple = tuple[NodeKey, NodeKey] EdgeValue = TypeVar("EdgeValue") NodeValue = TypeVar("NodeValue") IndexValue = TypeVar("IndexValue") Dtype = TypeVar("Dtype") class any_ndarray: def __class_getitem__(cls, item): return cp.ndarray[item] | np.ndarray[item]
0
rapidsai_public_repos/cugraph/python/nx-cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/interface.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import sys import networkx as nx import nx_cugraph as nxcg class BackendInterface: # Required conversions @staticmethod def convert_from_nx(graph, *args, edge_attrs=None, weight=None, **kwargs): if weight is not None: # MAINT: networkx 3.0, 3.1 # For networkx 3.0 and 3.1 compatibility if edge_attrs is not None: raise TypeError( "edge_attrs and weight arguments should not both be given" ) edge_attrs = {weight: 1} return nxcg.from_networkx(graph, *args, edge_attrs=edge_attrs, **kwargs) @staticmethod def convert_to_nx(obj, *, name: str | None = None): if isinstance(obj, nxcg.Graph): return nxcg.to_networkx(obj) return obj @staticmethod def on_start_tests(items): """Modify pytest items after tests have been collected. This is called during ``pytest_collection_modifyitems`` phase of pytest. We use this to set `xfail` on tests we expect to fail. See: https://docs.pytest.org/en/stable/reference/reference.html#std-hook-pytest_collection_modifyitems """ try: import pytest except ModuleNotFoundError: return def key(testpath): filename, path = testpath.split(":") *names, testname = path.split(".") if names: [classname] = names return (testname, frozenset({classname, filename})) return (testname, frozenset({filename})) # Reasons for xfailing no_weights = "weighted implementation not currently supported" no_multigraph = "multigraphs not currently supported" louvain_different = "Louvain may be different due to RNG" no_string_dtype = "string edge values not currently supported" xfail = {} from packaging.version import parse nxver = parse(nx.__version__) if nxver.major == 3 and nxver.minor <= 2: # Networkx versions prior to 3.2.1 have tests written to expect # sp.sparse.linalg.ArpackNoConvergence exceptions raised on no # convergence in HITS. Newer versions since the merge of # https://github.com/networkx/networkx/pull/7084 expect # nx.PowerIterationFailedConvergence, which is what nx_cugraph.hits # raises, so we mark them as xfail for previous versions of NX. xfail.update( { key( "test_hits.py:TestHITS.test_hits_not_convergent" ): "nx_cugraph.hits raises updated exceptions not caught in " "these tests", } ) if nxver.major == 3 and nxver.minor <= 1: # MAINT: networkx 3.0, 3.1 # NetworkX 3.2 added the ability to "fallback to nx" if backend algorithms # raise NotImplementedError or `can_run` returns False. The tests below # exercise behavior we have not implemented yet, so we mark them as xfail # for previous versions of NX. xfail.update( { key( "test_agraph.py:TestAGraph.test_no_warnings_raised" ): "pytest.warn(None) deprecated", key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_K5" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_P3_normalized" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_P3" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_krackhardt_kite_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality." "test_krackhardt_kite_graph_normalized" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality." "test_florentine_families_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_les_miserables_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_ladder_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_G" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_G2" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_G3" ): no_multigraph, key( "test_betweenness_centrality.py:" "TestWeightedBetweennessCentrality.test_G4" ): no_multigraph, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_K5" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_C4" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_P4" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_balanced_tree" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_weighted_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality." "test_normalized_weighted_graph" ): no_weights, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality.test_weighted_multigraph" ): no_multigraph, key( "test_betweenness_centrality.py:" "TestWeightedEdgeBetweennessCentrality." "test_normalized_weighted_multigraph" ): no_multigraph, } ) else: xfail.update( { key( "test_louvain.py:test_karate_club_partition" ): louvain_different, key("test_louvain.py:test_none_weight_param"): louvain_different, key("test_louvain.py:test_multigraph"): louvain_different, # See networkx#6630 key( "test_louvain.py:test_undirected_selfloops" ): "self-loops not handled in Louvain", } ) if sys.version_info[:2] == (3, 9): # This test is sensitive to RNG, which depends on Python version xfail[ key("test_louvain.py:test_threshold") ] = "Louvain does not support seed parameter" if nxver.major == 3 and nxver.minor >= 2: xfail.update( { key( "test_convert_pandas.py:TestConvertPandas." "test_from_edgelist_multi_attr_incl_target" ): no_string_dtype, key( "test_convert_pandas.py:TestConvertPandas." "test_from_edgelist_multidigraph_and_edge_attr" ): no_string_dtype, key( "test_convert_pandas.py:TestConvertPandas." "test_from_edgelist_int_attr_name" ): no_string_dtype, } ) if nxver.minor == 2: different_iteration_order = "Different graph data iteration order" xfail.update( { key( "test_cycles.py:TestMinimumCycleBasis." "test_gh6787_and_edge_attribute_names" ): different_iteration_order, key( "test_euler.py:TestEulerianCircuit." "test_eulerian_circuit_cycle" ): different_iteration_order, key( "test_gml.py:TestGraph.test_special_float_label" ): different_iteration_order, } ) too_slow = "Too slow to run" maybe_oom = "out of memory in CI" skip = { key("test_tree_isomorphism.py:test_positive"): too_slow, key("test_tree_isomorphism.py:test_negative"): too_slow, key("test_efficiency.py:TestEfficiency.test_using_ego_graph"): maybe_oom, } for item in items: kset = set(item.keywords) for (test_name, keywords), reason in xfail.items(): if item.name == test_name and keywords.issubset(kset): item.add_marker(pytest.mark.xfail(reason=reason)) for (test_name, keywords), reason in skip.items(): if item.name == test_name and keywords.issubset(kset): item.add_marker(pytest.mark.skip(reason=reason)) @classmethod def can_run(cls, name, args, kwargs): """Can this backend run the specified algorithms with the given arguments? This is a proposed API to add to networkx dispatching machinery and may change. """ return hasattr(cls, name) and getattr(cls, name).can_run(*args, **kwargs)
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/utils/decorators.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from functools import partial, update_wrapper from textwrap import dedent from networkx.utils.decorators import nodes_or_number, not_implemented_for from nx_cugraph.interface import BackendInterface try: from networkx.utils.backends import _registered_algorithms except ModuleNotFoundError: from networkx.classes.backends import _registered_algorithms __all__ = ["not_implemented_for", "nodes_or_number", "networkx_algorithm"] def networkx_class(api): def inner(func): func.__doc__ = getattr(api, func.__name__).__doc__ return func return inner class networkx_algorithm: name: str extra_doc: str | None extra_params: dict[str, str] | None def __new__( cls, func=None, *, name: str | None = None, extra_params: dict[str, str] | str | None = None, ): if func is None: return partial(networkx_algorithm, name=name, extra_params=extra_params) instance = object.__new__(cls) # update_wrapper sets __wrapped__, which will be used for the signature update_wrapper(instance, func) instance.__defaults__ = func.__defaults__ instance.__kwdefaults__ = func.__kwdefaults__ instance.name = func.__name__ if name is None else name if extra_params is None: pass elif isinstance(extra_params, str): extra_params = {extra_params: ""} elif not isinstance(extra_params, dict): raise TypeError( f"extra_params must be dict, str, or None; got {type(extra_params)}" ) instance.extra_params = extra_params # The docstring on our function is added to the NetworkX docstring. instance.extra_doc = ( dedent(func.__doc__.lstrip("\n").rstrip()) if func.__doc__ else None ) # Copy __doc__ from NetworkX if instance.name in _registered_algorithms: instance.__doc__ = _registered_algorithms[instance.name].__doc__ instance.can_run = _default_can_run setattr(BackendInterface, instance.name, instance) # Set methods so they are in __dict__ instance._can_run = instance._can_run return instance def _can_run(self, func): """Set the `can_run` attribute to the decorated function.""" self.can_run = func def __call__(self, /, *args, **kwargs): return self.__wrapped__(*args, **kwargs) def __reduce__(self): return _restore_networkx_dispatched, (self.name,) def _default_can_run(*args, **kwargs): return True def _restore_networkx_dispatched(name): return getattr(BackendInterface, name)
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/utils/misc.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import itertools import operator as op import sys from random import Random from typing import TYPE_CHECKING, SupportsIndex import cupy as cp import numpy as np if TYPE_CHECKING: from ..typing import Dtype try: from itertools import pairwise # Python >=3.10 except ImportError: def pairwise(it): it = iter(it) for prev in it: for cur in it: yield (prev, cur) prev = cur __all__ = [ "index_dtype", "_groupby", "_seed_to_int", "_get_int_dtype", "_get_float_dtype", "_dtype_param", ] # This may switch to np.uint32 at some point index_dtype = np.int32 # To add to `extra_params=` of `networkx_algorithm` _dtype_param = { "dtype : dtype or None, optional": ( "The data type (np.float32, np.float64, or None) to use for the edge weights " "in the algorithm. If None, then dtype is determined by the edge values." ), } def _groupby( groups: cp.ndarray, values: cp.ndarray, groups_are_canonical: bool = False ) -> dict[int, cp.ndarray]: """Perform a groupby operation given an array of group IDs and array of values. Parameters ---------- groups : cp.ndarray Array that holds the group IDs. values : cp.ndarray Array of values to be grouped according to groups. Must be the same size as groups array. groups_are_canonical : bool, default False Whether the group IDs are consecutive integers beginning with 0. Returns ------- dict with group IDs as keys and cp.ndarray as values. """ if groups.size == 0: return {} sort_indices = cp.argsort(groups) sorted_groups = groups[sort_indices] sorted_values = values[sort_indices] prepend = 1 if groups_are_canonical else sorted_groups[0] + 1 left_bounds = cp.nonzero(cp.diff(sorted_groups, prepend=prepend))[0] boundaries = pairwise(itertools.chain(left_bounds.tolist(), [groups.size])) if groups_are_canonical: it = enumerate(boundaries) else: it = zip(sorted_groups[left_bounds].tolist(), boundaries) return {group: sorted_values[start:end] for group, (start, end) in it} def _seed_to_int(seed: int | Random | None) -> int: """Handle any valid seed argument and convert it to an int if necessary.""" if seed is None: return if isinstance(seed, Random): return seed.randint(0, sys.maxsize) return op.index(seed) # Ensure seed is integral def _get_int_dtype( val: SupportsIndex, *, signed: bool | None = None, unsigned: bool | None = None ): """Determine the smallest integer dtype that can store the integer ``val``. If signed or unsigned are unspecified, then signed integers are preferred unless the value can be represented by a smaller unsigned integer. Raises ------ ValueError : If the value cannot be represented with an int dtype. """ # This is similar in spirit to `np.min_scalar_type` if signed is not None: if unsigned is not None and (not signed) is (not unsigned): raise TypeError( f"signed (={signed}) and unsigned (={unsigned}) keyword arguments " "are incompatible." ) signed = bool(signed) unsigned = not signed elif unsigned is not None: unsigned = bool(unsigned) signed = not unsigned val = op.index(val) # Ensure val is integral if val < 0: if unsigned: raise ValueError(f"Value is incompatible with unsigned int: {val}.") signed = True unsigned = False if signed is not False: # Number of bytes (and a power of two) signed_nbytes = (val + (val < 0)).bit_length() // 8 + 1 signed_nbytes = next( filter( signed_nbytes.__le__, itertools.accumulate(itertools.repeat(2), op.mul, initial=1), ) ) if unsigned is not False: # Number of bytes (and a power of two) unsigned_nbytes = (val.bit_length() + 7) // 8 unsigned_nbytes = next( filter( unsigned_nbytes.__le__, itertools.accumulate(itertools.repeat(2), op.mul, initial=1), ) ) if signed is None and unsigned is None: # Prefer signed int if same size signed = signed_nbytes <= unsigned_nbytes if signed: dtype_string = f"i{signed_nbytes}" else: dtype_string = f"u{unsigned_nbytes}" try: return np.dtype(dtype_string) except TypeError as exc: raise ValueError("Value is too large to store as integer: {val}") from exc def _get_float_dtype(dtype: Dtype): """Promote dtype to float32 or float64 as appropriate.""" if dtype is None: return np.dtype(np.float32) rv = np.promote_types(dtype, np.float32) if np.float32 != rv != np.float64: raise TypeError( f"Dtype {dtype} cannot be safely promoted to float32 or float64" ) return rv
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/utils/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .decorators import * from .misc import *
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_multigraph.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import networkx as nx import pytest import nx_cugraph as nxcg @pytest.mark.parametrize("test_nxcugraph", [False, True]) def test_get_edge_data(test_nxcugraph): G = nx.MultiGraph() G.add_edge(0, 1, 0, x=10) G.add_edge(0, 1, 1, y=20) G.add_edge(0, 2, "a", x=100) G.add_edge(0, 2, "b", y=200) G.add_edge(0, 3) G.add_edge(0, 3) if test_nxcugraph: G = nxcg.MultiGraph(G) default = object() assert G.get_edge_data(0, 0, default=default) is default assert G.get_edge_data("a", "b", default=default) is default assert G.get_edge_data(0, 1, 2, default=default) is default assert G.get_edge_data(-1, 1, default=default) is default assert G.get_edge_data(0, 1, 0, default=default) == {"x": 10} assert G.get_edge_data(0, 1, 1, default=default) == {"y": 20} assert G.get_edge_data(0, 1, default=default) == {0: {"x": 10}, 1: {"y": 20}} assert G.get_edge_data(0, 2, "a", default=default) == {"x": 100} assert G.get_edge_data(0, 2, "b", default=default) == {"y": 200} assert G.get_edge_data(0, 2, default=default) == {"a": {"x": 100}, "b": {"y": 200}} assert G.get_edge_data(0, 3, 0, default=default) == {} assert G.get_edge_data(0, 3, 1, default=default) == {} assert G.get_edge_data(0, 3, 2, default=default) is default assert G.get_edge_data(0, 3, default=default) == {0: {}, 1: {}} assert G.has_edge(0, 1) assert G.has_edge(0, 1, 0) assert G.has_edge(0, 1, 1) assert not G.has_edge(0, 1, 2) assert not G.has_edge(0, 1, "a") assert not G.has_edge(0, -1) assert G.has_edge(0, 2) assert G.has_edge(0, 2, "a") assert G.has_edge(0, 2, "b") assert not G.has_edge(0, 2, "c") assert not G.has_edge(0, 2, 0) assert G.has_edge(0, 3) assert not G.has_edge(0, 0) assert not G.has_edge(0, 0, 0) G = nx.MultiGraph() G.add_edge(0, 1) if test_nxcugraph: G = nxcg.MultiGraph(G) assert G.get_edge_data(0, 1, default=default) == {0: {}} assert G.get_edge_data(0, 1, 0, default=default) == {} assert G.get_edge_data(0, 1, 1, default=default) is default assert G.get_edge_data(0, 1, "b", default=default) is default assert G.get_edge_data(-1, 2, default=default) is default assert G.has_edge(0, 1) assert G.has_edge(0, 1, 0) assert not G.has_edge(0, 1, 1) assert not G.has_edge(0, 1, "a")
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_generators.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import networkx as nx import numpy as np import pytest from packaging.version import parse import nx_cugraph as nxcg nxver = parse(nx.__version__) def assert_graphs_equal(Gnx, Gcg): assert isinstance(Gnx, nx.Graph) assert isinstance(Gcg, nxcg.Graph) assert Gnx.number_of_nodes() == Gcg.number_of_nodes() assert Gnx.number_of_edges() == Gcg.number_of_edges() assert Gnx.is_directed() == Gcg.is_directed() assert Gnx.is_multigraph() == Gcg.is_multigraph() G = nxcg.to_networkx(Gcg) rv = nx.utils.graphs_equal(G, Gnx) if not rv: print("GRAPHS ARE NOT EQUAL!") assert sorted(G) == sorted(Gnx) assert sorted(G._adj) == sorted(Gnx._adj) assert sorted(G._node) == sorted(Gnx._node) for k in sorted(G._adj): print(k, sorted(G._adj[k]), sorted(Gnx._adj[k])) print(nx.to_scipy_sparse_array(G).todense()) print(nx.to_scipy_sparse_array(Gnx).todense()) print(G.graph) print(Gnx.graph) assert rv if nxver.major == 3 and nxver.minor < 2: pytest.skip("Need NetworkX >=3.2 to test generators", allow_module_level=True) def compare(name, create_using, *args, is_vanilla=False): exc1 = exc2 = None func = getattr(nx, name) if isinstance(create_using, nxcg.Graph): nx_create_using = nxcg.to_networkx(create_using) elif isinstance(create_using, type) and issubclass(create_using, nxcg.Graph): nx_create_using = create_using.to_networkx_class() elif isinstance(create_using, nx.Graph): nx_create_using = create_using.copy() else: nx_create_using = create_using try: if is_vanilla: G = func(*args) else: G = func(*args, create_using=nx_create_using) except Exception as exc: exc1 = exc try: if is_vanilla: Gcg = func(*args, backend="cugraph") else: Gcg = func(*args, create_using=create_using, backend="cugraph") except ZeroDivisionError: raise except NotImplementedError as exc: if name in {"complete_multipartite_graph"}: # nx.__version__[:3] <= "3.2" return exc2 = exc except Exception as exc: if exc1 is None: # pragma: no cover (debug) raise exc2 = exc if exc1 is not None or exc2 is not None: assert type(exc1) is type(exc2) else: assert_graphs_equal(G, Gcg) N = list(range(-1, 5)) CREATE_USING = [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph] COMPLETE_CREATE_USING = [ nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph, nxcg.Graph, nxcg.DiGraph, nxcg.MultiGraph, nxcg.MultiDiGraph, # These raise NotImplementedError # nx.Graph(), # nx.DiGraph(), # nx.MultiGraph(), # nx.MultiDiGraph(), nxcg.Graph(), nxcg.DiGraph(), nxcg.MultiGraph(), nxcg.MultiDiGraph(), None, object, # Bad input 7, # Bad input ] GENERATORS_NOARG = [ # classic "null_graph", "trivial_graph", # small "bull_graph", "chvatal_graph", "cubical_graph", "desargues_graph", "diamond_graph", "dodecahedral_graph", "frucht_graph", "heawood_graph", "house_graph", "house_x_graph", "icosahedral_graph", "krackhardt_kite_graph", "moebius_kantor_graph", "octahedral_graph", "petersen_graph", "sedgewick_maze_graph", "tetrahedral_graph", "truncated_cube_graph", "truncated_tetrahedron_graph", "tutte_graph", ] GENERATORS_NOARG_VANILLA = [ # classic "complete_multipartite_graph", # small "pappus_graph", # social "davis_southern_women_graph", "florentine_families_graph", "karate_club_graph", "les_miserables_graph", ] GENERATORS_N = [ # classic "circular_ladder_graph", "complete_graph", "cycle_graph", "empty_graph", "ladder_graph", "path_graph", "star_graph", "wheel_graph", ] GENERATORS_M_N = [ # classic "barbell_graph", "lollipop_graph", "tadpole_graph", # bipartite "complete_bipartite_graph", ] GENERATORS_M_N_VANILLA = [ # classic "complete_multipartite_graph", "turan_graph", # community "caveman_graph", ] @pytest.mark.parametrize("name", GENERATORS_NOARG) @pytest.mark.parametrize("create_using", COMPLETE_CREATE_USING) def test_generator_noarg(name, create_using): print(name, create_using, type(create_using)) if isinstance(create_using, nxcg.Graph) and name in { # fmt: off "bull_graph", "chvatal_graph", "cubical_graph", "diamond_graph", "house_graph", "house_x_graph", "icosahedral_graph", "krackhardt_kite_graph", "octahedral_graph", "petersen_graph", "truncated_cube_graph", "tutte_graph", # fmt: on }: # The _raise_on_directed decorator used in networkx doesn't like our graphs. if create_using.is_directed(): with pytest.raises(AssertionError): compare(name, create_using) else: with pytest.raises(TypeError): compare(name, create_using) else: compare(name, create_using) @pytest.mark.parametrize("name", GENERATORS_NOARG_VANILLA) def test_generator_noarg_vanilla(name): print(name) compare(name, None, is_vanilla=True) @pytest.mark.parametrize("name", GENERATORS_N) @pytest.mark.parametrize("n", N) @pytest.mark.parametrize("create_using", CREATE_USING) def test_generator_n(name, n, create_using): print(name, n, create_using) compare(name, create_using, n) @pytest.mark.parametrize("name", GENERATORS_N) @pytest.mark.parametrize("n", [1, 4]) @pytest.mark.parametrize("create_using", COMPLETE_CREATE_USING) def test_generator_n_complete(name, n, create_using): print(name, n, create_using) compare(name, create_using, n) @pytest.mark.parametrize("name", GENERATORS_M_N) @pytest.mark.parametrize("create_using", CREATE_USING) @pytest.mark.parametrize("m", N) @pytest.mark.parametrize("n", N) def test_generator_m_n(name, create_using, m, n): print(name, m, n, create_using) compare(name, create_using, m, n) @pytest.mark.parametrize("name", GENERATORS_M_N_VANILLA) @pytest.mark.parametrize("m", N) @pytest.mark.parametrize("n", N) def test_generator_m_n_vanilla(name, m, n): print(name, m, n) compare(name, None, m, n, is_vanilla=True) @pytest.mark.parametrize("name", GENERATORS_M_N) @pytest.mark.parametrize("create_using", COMPLETE_CREATE_USING) @pytest.mark.parametrize("m", [4]) @pytest.mark.parametrize("n", [4]) def test_generator_m_n_complete(name, create_using, m, n): print(name, m, n, create_using) compare(name, create_using, m, n) @pytest.mark.parametrize("name", GENERATORS_M_N_VANILLA) @pytest.mark.parametrize("m", [4]) @pytest.mark.parametrize("n", [4]) def test_generator_m_n_complete_vanilla(name, m, n): print(name, m, n) compare(name, None, m, n, is_vanilla=True) def test_bad_lollipop_graph(): compare("lollipop_graph", None, [0, 1], [1, 2]) def test_can_convert_karate_club(): # Karate club graph has string node values. # This really tests conversions, but it's here so we can use `assert_graphs_equal`. G = nx.karate_club_graph() G.add_node(0, foo="bar") # string dtype with a mask G.add_node(1, object=object()) # haha Gcg = nxcg.from_networkx(G, preserve_all_attrs=True) assert_graphs_equal(G, Gcg) Gnx = nxcg.to_networkx(Gcg) assert nx.utils.graphs_equal(G, Gnx) assert isinstance(Gcg.node_values["club"], np.ndarray) assert Gcg.node_values["club"].dtype.kind == "U" assert isinstance(Gcg.node_values["foo"], np.ndarray) assert isinstance(Gcg.node_masks["foo"], np.ndarray) assert Gcg.node_values["foo"].dtype.kind == "U" assert isinstance(Gcg.node_values["object"], np.ndarray) assert Gcg.node_values["object"].dtype.kind == "O" assert isinstance(Gcg.node_masks["object"], np.ndarray)
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_community.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import networkx as nx import pytest import nx_cugraph as nxcg def test_louvain_isolated_nodes(): is_nx_30_or_31 = hasattr(nx.classes, "backends") def check(left, right): assert len(left) == len(right) assert set(map(frozenset, left)) == set(map(frozenset, right)) # Empty graph (no nodes) G = nx.Graph() if is_nx_30_or_31: with pytest.raises(ZeroDivisionError): nx.community.louvain_communities(G) else: nx_result = nx.community.louvain_communities(G) cg_result = nxcg.community.louvain_communities(G) check(nx_result, cg_result) # Graph with no edges G.add_nodes_from(range(5)) if is_nx_30_or_31: with pytest.raises(ZeroDivisionError): nx.community.louvain_communities(G) else: nx_result = nx.community.louvain_communities(G) cg_result = nxcg.community.louvain_communities(G) check(nx_result, cg_result) # Graph with isolated nodes G.add_edge(1, 2) nx_result = nx.community.louvain_communities(G) cg_result = nxcg.community.louvain_communities(G) check(nx_result, cg_result) # Another one G.add_edge(4, 4) nx_result = nx.community.louvain_communities(G) cg_result = nxcg.community.louvain_communities(G) check(nx_result, cg_result)
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_match_api.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib import inspect import networkx as nx import nx_cugraph as nxcg from nx_cugraph.utils import networkx_algorithm def test_match_signature_and_names(): """Simple test to ensure our signatures and basic module layout match networkx.""" for name, func in vars(nxcg.interface.BackendInterface).items(): if not isinstance(func, networkx_algorithm): continue # nx version >=3.2 uses utils.backends, version >=3.0,<3.2 uses classes.backends is_nx_30_or_31 = hasattr(nx.classes, "backends") nx_backends = nx.classes.backends if is_nx_30_or_31 else nx.utils.backends if is_nx_30_or_31 and name in {"louvain_communities"}: continue if name not in nx_backends._registered_algorithms: print(f"{name} not dispatched from networkx") continue dispatchable_func = nx_backends._registered_algorithms[name] # nx version >=3.2 uses orig_func, version >=3.0,<3.2 uses _orig_func if is_nx_30_or_31: orig_func = dispatchable_func._orig_func else: orig_func = dispatchable_func.orig_func # Matching signatures? orig_sig = inspect.signature(orig_func) func_sig = inspect.signature(func) if not func.extra_params: assert orig_sig == func_sig else: # Ignore extra parameters added to nx-cugraph algorithm # The key of func.extra_params may be like "max_level : int, optional", # but we only want "max_level" here. extra_params = {name.split(" ")[0] for name in func.extra_params} assert orig_sig == func_sig.replace( parameters=[ p for name, p in func_sig.parameters.items() if name not in extra_params ] ) if func.can_run is not nxcg.utils.decorators._default_can_run: assert func_sig == inspect.signature(func.can_run) # Matching function names? assert func.__name__ == dispatchable_func.__name__ == orig_func.__name__ # Matching dispatch names? # nx version >=3.2 uses name, version >=3.0,<3.2 uses dispatchname if is_nx_30_or_31: dispatchname = dispatchable_func.dispatchname else: dispatchname = dispatchable_func.name assert func.name == dispatchname # Matching modules (i.e., where function defined)? assert ( "networkx." + func.__module__.split(".", 1)[1] == dispatchable_func.__module__ == orig_func.__module__ ) # Matching package layout (i.e., which modules have the function)? nxcg_path = func.__module__ name = func.__name__ while "." in nxcg_path: # This only walks up the module tree and does not check sibling modules nxcg_path, mod_name = nxcg_path.rsplit(".", 1) nx_path = nxcg_path.replace("nx_cugraph", "networkx") nxcg_mod = importlib.import_module(nxcg_path) nx_mod = importlib.import_module(nx_path) # Is the function present in the current module? present_in_nxcg = hasattr(nxcg_mod, name) present_in_nx = hasattr(nx_mod, name) if present_in_nxcg is not present_in_nx: # pragma: no cover (debug) if present_in_nxcg: raise AssertionError( f"{name} exists in {nxcg_path}, but not in {nx_path}" ) raise AssertionError( f"{name} exists in {nx_path}, but not in {nxcg_path}" ) # Is the nested module present in the current module? present_in_nxcg = hasattr(nxcg_mod, mod_name) present_in_nx = hasattr(nx_mod, mod_name) if present_in_nxcg is not present_in_nx: # pragma: no cover (debug) if present_in_nxcg: raise AssertionError( f"{mod_name} exists in {nxcg_path}, but not in {nx_path}" ) raise AssertionError( f"{mod_name} exists in {nx_path}, but not in {nxcg_path}" )
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/conftest.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def pytest_configure(config): if config.getoption("--all", False): # Run benchmarks AND tests config.option.benchmark_skip = False config.option.benchmark_enable = True elif config.getoption("--bench", False) or config.getoption( "--benchmark-enable", False ): # Run benchmarks (and only benchmarks) with `--bench` argument config.option.benchmark_skip = False config.option.benchmark_enable = True if not config.option.keyword: config.option.keyword = "bench_" else: # Run only tests config.option.benchmark_skip = True config.option.benchmark_enable = False if not config.option.keyword: config.option.keyword = "test_"
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_convert.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cupy as cp import networkx as nx import pytest import nx_cugraph as nxcg from nx_cugraph import interface @pytest.mark.parametrize( "graph_class", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph] ) @pytest.mark.parametrize( "kwargs", [ {}, {"preserve_edge_attrs": True}, {"preserve_node_attrs": True}, {"preserve_all_attrs": True}, {"edge_attrs": {"x": 0}}, {"edge_attrs": {"x": None}}, {"edge_attrs": {"x": nxcg.convert.REQUIRED}}, {"edge_attrs": {"x": ...}}, # sugar for REQUIRED {"edge_attrs": "x"}, {"node_attrs": {"x": 0}}, {"node_attrs": {"x": None}}, {"node_attrs": {"x": nxcg.convert.REQUIRED}}, {"node_attrs": {"x": ...}}, # sugar for REQUIRED {"node_attrs": "x"}, ], ) def test_convert_empty(graph_class, kwargs): G = graph_class() Gcg = nxcg.from_networkx(G, **kwargs) H = nxcg.to_networkx(Gcg) assert G.number_of_nodes() == Gcg.number_of_nodes() == H.number_of_nodes() == 0 assert G.number_of_edges() == Gcg.number_of_edges() == H.number_of_edges() == 0 assert Gcg.edge_values == Gcg.edge_masks == Gcg.node_values == Gcg.node_masks == {} assert G.graph == Gcg.graph == H.graph == {} @pytest.mark.parametrize("graph_class", [nx.Graph, nx.MultiGraph]) def test_convert(graph_class): # FIXME: can we break this into smaller tests? G = graph_class() G.add_edge(0, 1, x=2) G.add_node(0, foo=10) G.add_node(1, foo=20, bar=100) for kwargs in [ {"preserve_edge_attrs": True}, {"preserve_all_attrs": True}, {"edge_attrs": {"x": 0}}, {"edge_attrs": {"x": None}, "node_attrs": {"bar": None}}, {"edge_attrs": "x", "edge_dtypes": int}, { "edge_attrs": {"x": nxcg.convert.REQUIRED}, "node_attrs": {"foo": nxcg.convert.REQUIRED}, }, {"edge_attrs": {"x": ...}, "node_attrs": {"foo": ...}}, # sugar for REQUIRED ]: # All edges have "x" attribute, so all kwargs are equivalent Gcg = nxcg.from_networkx(G, **kwargs) cp.testing.assert_array_equal(Gcg.src_indices, [0, 1]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 0]) cp.testing.assert_array_equal(Gcg.edge_values["x"], [2, 2]) assert len(Gcg.edge_values) == 1 assert Gcg.edge_masks == {} H = nxcg.to_networkx(Gcg) assert G.number_of_nodes() == Gcg.number_of_nodes() == H.number_of_nodes() == 2 assert G.number_of_edges() == Gcg.number_of_edges() == H.number_of_edges() == 1 assert G.adj == H.adj with pytest.raises(KeyError, match="bar"): nxcg.from_networkx(G, node_attrs={"bar": ...}) # Structure-only graph (no edge attributes) Gcg = nxcg.from_networkx(G, preserve_node_attrs=True) cp.testing.assert_array_equal(Gcg.src_indices, [0, 1]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 0]) cp.testing.assert_array_equal(Gcg.node_values["foo"], [10, 20]) assert Gcg.edge_values == Gcg.edge_masks == {} H = nxcg.to_networkx(Gcg) if G.is_multigraph(): assert set(G.edges) == set(H.edges) == {(0, 1, 0)} else: assert set(G.edges) == set(H.edges) == {(0, 1)} assert G.nodes == H.nodes # Fill completely missing attribute with default value Gcg = nxcg.from_networkx(G, edge_attrs={"y": 0}) cp.testing.assert_array_equal(Gcg.src_indices, [0, 1]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 0]) cp.testing.assert_array_equal(Gcg.edge_values["y"], [0, 0]) assert len(Gcg.edge_values) == 1 assert Gcg.edge_masks == Gcg.node_values == Gcg.node_masks == {} H = nxcg.to_networkx(Gcg) assert list(H.edges(data=True)) == [(0, 1, {"y": 0})] if Gcg.is_multigraph(): assert set(H.edges) == {(0, 1, 0)} # If attribute is completely missing (and no default), then just ignore it Gcg = nxcg.from_networkx(G, edge_attrs={"y": None}) cp.testing.assert_array_equal(Gcg.src_indices, [0, 1]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 0]) assert sorted(Gcg.edge_values) == sorted(Gcg.edge_masks) == [] H = nxcg.to_networkx(Gcg) assert list(H.edges(data=True)) == [(0, 1, {})] if Gcg.is_multigraph(): assert set(H.edges) == {(0, 1, 0)} G.add_edge(0, 2) # Some edges are missing 'x' attribute; need to use a mask for kwargs in [{"preserve_edge_attrs": True}, {"edge_attrs": {"x": None}}]: Gcg = nxcg.from_networkx(G, **kwargs) cp.testing.assert_array_equal(Gcg.src_indices, [0, 0, 1, 2]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 2, 0, 0]) assert sorted(Gcg.edge_values) == sorted(Gcg.edge_masks) == ["x"] cp.testing.assert_array_equal(Gcg.edge_masks["x"], [True, False, True, False]) cp.testing.assert_array_equal(Gcg.edge_values["x"][Gcg.edge_masks["x"]], [2, 2]) H = nxcg.to_networkx(Gcg) assert list(H.edges(data=True)) == [(0, 1, {"x": 2}), (0, 2, {})] if Gcg.is_multigraph(): assert set(H.edges) == {(0, 1, 0), (0, 2, 0)} with pytest.raises(KeyError, match="x"): nxcg.from_networkx(G, edge_attrs={"x": nxcg.convert.REQUIRED}) with pytest.raises(KeyError, match="x"): nxcg.from_networkx(G, edge_attrs={"x": ...}) with pytest.raises(KeyError, match="bar"): nxcg.from_networkx(G, node_attrs={"bar": nxcg.convert.REQUIRED}) with pytest.raises(KeyError, match="bar"): nxcg.from_networkx(G, node_attrs={"bar": ...}) # Now for something more complicated... G = graph_class() G.add_edge(10, 20, x=1) G.add_edge(10, 30, x=2, y=1.5) G.add_node(10, foo=100) G.add_node(20, foo=200, bar=1000) G.add_node(30, foo=300) # Some edges have masks, some don't for kwargs in [ {"preserve_edge_attrs": True}, {"preserve_all_attrs": True}, {"edge_attrs": {"x": None, "y": None}}, {"edge_attrs": {"x": 0, "y": None}}, {"edge_attrs": {"x": 0, "y": None}}, {"edge_attrs": {"x": 0, "y": None}, "edge_dtypes": {"x": int, "y": float}}, ]: Gcg = nxcg.from_networkx(G, **kwargs) assert Gcg.id_to_key == [10, 20, 30] # Remap node IDs to 0, 1, ... cp.testing.assert_array_equal(Gcg.src_indices, [0, 0, 1, 2]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 2, 0, 0]) cp.testing.assert_array_equal(Gcg.edge_values["x"], [1, 2, 1, 2]) assert sorted(Gcg.edge_masks) == ["y"] cp.testing.assert_array_equal(Gcg.edge_masks["y"], [False, True, False, True]) cp.testing.assert_array_equal( Gcg.edge_values["y"][Gcg.edge_masks["y"]], [1.5, 1.5] ) H = nxcg.to_networkx(Gcg) assert G.adj == H.adj # Some nodes have masks, some don't for kwargs in [ {"preserve_node_attrs": True}, {"preserve_all_attrs": True}, {"node_attrs": {"foo": None, "bar": None}}, {"node_attrs": {"foo": None, "bar": None}}, {"node_attrs": {"foo": 0, "bar": None, "missing": None}}, ]: Gcg = nxcg.from_networkx(G, **kwargs) assert Gcg.id_to_key == [10, 20, 30] # Remap node IDs to 0, 1, ... cp.testing.assert_array_equal(Gcg.src_indices, [0, 0, 1, 2]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 2, 0, 0]) cp.testing.assert_array_equal(Gcg.node_values["foo"], [100, 200, 300]) assert sorted(Gcg.node_masks) == ["bar"] cp.testing.assert_array_equal(Gcg.node_masks["bar"], [False, True, False]) cp.testing.assert_array_equal( Gcg.node_values["bar"][Gcg.node_masks["bar"]], [1000] ) H = nxcg.to_networkx(Gcg) assert G.nodes == H.nodes # Check default values for nodes for kwargs in [ {"node_attrs": {"foo": None, "bar": 0}}, {"node_attrs": {"foo": None, "bar": 0, "missing": None}}, {"node_attrs": {"bar": 0}}, {"node_attrs": {"bar": 0}, "node_dtypes": {"bar": int}}, {"node_attrs": {"bar": 0, "foo": None}, "node_dtypes": int}, ]: Gcg = nxcg.from_networkx(G, **kwargs) assert Gcg.id_to_key == [10, 20, 30] # Remap node IDs to 0, 1, ... cp.testing.assert_array_equal(Gcg.src_indices, [0, 0, 1, 2]) cp.testing.assert_array_equal(Gcg.dst_indices, [1, 2, 0, 0]) cp.testing.assert_array_equal(Gcg.node_values["bar"], [0, 1000, 0]) assert Gcg.node_masks == {} with pytest.raises( TypeError, match="edge_attrs and weight arguments should not both be given" ): interface.BackendInterface.convert_from_nx(G, edge_attrs={"x": 1}, weight="x") with pytest.raises(TypeError, match="Expected networkx.Graph"): nxcg.from_networkx({}) @pytest.mark.parametrize("graph_class", [nx.MultiGraph, nx.MultiDiGraph]) def test_multigraph(graph_class): G = graph_class() G.add_edge(0, 1, "key1", x=10) G.add_edge(0, 1, "key2", y=20) Gcg = nxcg.from_networkx(G, preserve_edge_attrs=True) H = nxcg.to_networkx(Gcg) assert type(G) is type(H) assert nx.utils.graphs_equal(G, H)
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/bench_convert.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import networkx as nx import numpy as np import pytest import nx_cugraph as nxcg try: import cugraph except ModuleNotFoundError: cugraph = None try: import scipy except ModuleNotFoundError: scipy = None # If the rapids-pytest-benchmark plugin is installed, the "gpubenchmark" # fixture will be available automatically. Check that this fixture is available # by trying to import rapids_pytest_benchmark, and if that fails, set # "gpubenchmark" to the standard "benchmark" fixture provided by # pytest-benchmark. try: import rapids_pytest_benchmark # noqa: F401 except ModuleNotFoundError: import pytest_benchmark gpubenchmark = pytest_benchmark.plugin.benchmark CREATE_USING = [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph] def _bench_helper(gpubenchmark, N, attr_kind, create_using, method): G = method(N, create_using=create_using) if attr_kind: skip = True for *_ids, edgedict in G.edges(data=True): skip = not skip if skip and attr_kind not in {"full", "required", "required_dtype"}: continue edgedict["x"] = random.randint(0, 100000) if attr_kind == "preserve": gpubenchmark(nxcg.from_networkx, G, preserve_edge_attrs=True) elif attr_kind == "half_missing": gpubenchmark(nxcg.from_networkx, G, edge_attrs={"x": None}) elif attr_kind == "required": gpubenchmark(nxcg.from_networkx, G, edge_attrs={"x": ...}) elif attr_kind == "required_dtype": gpubenchmark( nxcg.from_networkx, G, edge_attrs={"x": ...}, edge_dtypes={"x": np.int32}, ) else: # full, half_default gpubenchmark(nxcg.from_networkx, G, edge_attrs={"x": 0}) else: gpubenchmark(nxcg.from_networkx, G) def _bench_helper_cugraph( gpubenchmark, N, attr_kind, create_using, method, do_renumber ): G = method(N, create_using=create_using) if attr_kind: for *_ids, edgedict in G.edges(data=True): edgedict["x"] = random.randint(0, 100000) gpubenchmark(cugraph.utilities.convert_from_nx, G, "x", do_renumber=do_renumber) else: gpubenchmark(cugraph.utilities.convert_from_nx, G, do_renumber=do_renumber) def _bench_helper_scipy(gpubenchmark, N, attr_kind, create_using, method, fmt): G = method(N, create_using=create_using) if attr_kind: for *_ids, edgedict in G.edges(data=True): edgedict["x"] = random.randint(0, 100000) gpubenchmark(nx.to_scipy_sparse_array, G, weight="x", format=fmt) else: gpubenchmark(nx.to_scipy_sparse_array, G, weight=None, format=fmt) @pytest.mark.parametrize("N", [1, 10**6]) @pytest.mark.parametrize( "attr_kind", [ "required_dtype", "required", "full", "half_missing", "half_default", "preserve", None, ], ) @pytest.mark.parametrize("create_using", CREATE_USING) def bench_cycle_graph(gpubenchmark, N, attr_kind, create_using): _bench_helper(gpubenchmark, N, attr_kind, create_using, nx.cycle_graph) @pytest.mark.skipif("not cugraph") @pytest.mark.parametrize("N", [1, 10**6]) @pytest.mark.parametrize("attr_kind", ["full", None]) @pytest.mark.parametrize("create_using", CREATE_USING) @pytest.mark.parametrize("do_renumber", [True, False]) def bench_cycle_graph_cugraph(gpubenchmark, N, attr_kind, create_using, do_renumber): if N == 1 and not do_renumber: do_renumber = True _bench_helper_cugraph( gpubenchmark, N, attr_kind, create_using, nx.cycle_graph, do_renumber ) @pytest.mark.skipif("not scipy") @pytest.mark.parametrize("N", [1, 10**6]) @pytest.mark.parametrize("attr_kind", ["full", None]) @pytest.mark.parametrize("create_using", CREATE_USING) @pytest.mark.parametrize("fmt", ["coo", "csr"]) def bench_cycle_graph_scipy(gpubenchmark, N, attr_kind, create_using, fmt): _bench_helper_scipy(gpubenchmark, N, attr_kind, create_using, nx.cycle_graph, fmt) @pytest.mark.parametrize("N", [1, 1500]) @pytest.mark.parametrize( "attr_kind", [ "required_dtype", "required", "full", "half_missing", "half_default", "preserve", None, ], ) @pytest.mark.parametrize("create_using", CREATE_USING) def bench_complete_graph_edgedata(gpubenchmark, N, attr_kind, create_using): _bench_helper(gpubenchmark, N, attr_kind, create_using, nx.complete_graph) @pytest.mark.parametrize("N", [3000]) @pytest.mark.parametrize("attr_kind", [None]) @pytest.mark.parametrize("create_using", CREATE_USING) def bench_complete_graph_noedgedata(gpubenchmark, N, attr_kind, create_using): _bench_helper(gpubenchmark, N, attr_kind, create_using, nx.complete_graph) @pytest.mark.skipif("not cugraph") @pytest.mark.parametrize("N", [1, 1500]) @pytest.mark.parametrize("attr_kind", ["full", None]) @pytest.mark.parametrize("create_using", CREATE_USING) @pytest.mark.parametrize("do_renumber", [True, False]) def bench_complete_graph_cugraph(gpubenchmark, N, attr_kind, create_using, do_renumber): if N == 1 and not do_renumber: do_renumber = True _bench_helper_cugraph( gpubenchmark, N, attr_kind, create_using, nx.complete_graph, do_renumber ) @pytest.mark.skipif("not scipy") @pytest.mark.parametrize("N", [1, 1500]) @pytest.mark.parametrize("attr_kind", ["full", None]) @pytest.mark.parametrize("create_using", CREATE_USING) @pytest.mark.parametrize("fmt", ["coo", "csr"]) def bench_complete_graph_scipy(gpubenchmark, N, attr_kind, create_using, fmt): _bench_helper_scipy( gpubenchmark, N, attr_kind, create_using, nx.complete_graph, fmt )
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_ktruss.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import networkx as nx import pytest import nx_cugraph as nxcg @pytest.mark.parametrize( "get_graph", [nx.florentine_families_graph, nx.les_miserables_graph] ) def test_k_truss(get_graph): Gnx = get_graph() Gcg = nxcg.from_networkx(Gnx, preserve_all_attrs=True) for k in range(6): Hnx = nx.k_truss(Gnx, k) Hcg = nxcg.k_truss(Gcg, k) assert nx.utils.graphs_equal(Hnx, nxcg.to_networkx(Hcg)) if Hnx.number_of_edges() == 0: break
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/tests/test_utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import pytest from nx_cugraph.utils import _get_int_dtype def test_get_int_dtype(): uint8 = np.dtype(np.uint8) uint16 = np.dtype(np.uint16) uint32 = np.dtype(np.uint32) uint64 = np.dtype(np.uint64) # signed cur = np.iinfo(np.int8) for val in [cur.min, cur.min + 1, -1, 0, 1, cur.max - 1, cur.max]: assert _get_int_dtype(val) == np.int8 assert _get_int_dtype(val, signed=True) == np.int8 if val >= 0: assert _get_int_dtype(val, unsigned=True) == np.uint8 assert _get_int_dtype(val + 1, unsigned=True) == np.uint8 prev = cur cur = np.iinfo(np.int16) for val in [cur.min, cur.min + 1, prev.min - 1, prev.max + 1, cur.max - 1, cur.max]: assert _get_int_dtype(val) != prev.dtype assert _get_int_dtype(val, signed=True) == np.int16 if val >= 0: assert _get_int_dtype(val, unsigned=True) in {uint8, uint16} assert _get_int_dtype(val + 1, unsigned=True) in {uint8, uint16} prev = cur cur = np.iinfo(np.int32) for val in [cur.min, cur.min + 1, prev.min - 1, prev.max + 1, cur.max - 1, cur.max]: assert _get_int_dtype(val) != prev.dtype assert _get_int_dtype(val, signed=True) == np.int32 if val >= 0: assert _get_int_dtype(val, unsigned=True) in {uint16, uint32} assert _get_int_dtype(val + 1, unsigned=True) in {uint16, uint32} prev = cur cur = np.iinfo(np.int64) for val in [cur.min, cur.min + 1, prev.min - 1, prev.max + 1, cur.max - 1, cur.max]: assert _get_int_dtype(val) != prev.dtype assert _get_int_dtype(val, signed=True) == np.int64 if val >= 0: assert _get_int_dtype(val, unsigned=True) in {uint32, uint64} assert _get_int_dtype(val + 1, unsigned=True) in {uint32, uint64} with pytest.raises(ValueError, match="Value is too"): _get_int_dtype(cur.min - 1, signed=True) with pytest.raises(ValueError, match="Value is too"): _get_int_dtype(cur.max + 1, signed=True) # unsigned cur = np.iinfo(np.uint8) for val in [0, 1, cur.max - 1, cur.max]: assert _get_int_dtype(val) == (np.uint8 if val > 1 else np.int8) assert _get_int_dtype(val, unsigned=True) == np.uint8 assert _get_int_dtype(cur.max + 1) == np.int16 cur = np.iinfo(np.uint16) for val in [cur.max - 1, cur.max]: assert _get_int_dtype(val, unsigned=True) == np.uint16 assert _get_int_dtype(cur.max + 1) == np.int32 cur = np.iinfo(np.uint32) for val in [cur.max - 1, cur.max]: assert _get_int_dtype(val, unsigned=True) == np.uint32 assert _get_int_dtype(cur.max + 1) == np.int64 cur = np.iinfo(np.uint64) for val in [cur.max - 1, cur.max]: assert _get_int_dtype(val, unsigned=True) == np.uint64 with pytest.raises(ValueError, match="Value is incompatible"): _get_int_dtype(cur.min - 1, unsigned=True) with pytest.raises(ValueError, match="Value is too"): _get_int_dtype(cur.max + 1, unsigned=True) # API with pytest.raises(TypeError, match="incompatible"): _get_int_dtype(7, signed=True, unsigned=True) assert _get_int_dtype(7, signed=True, unsigned=False) == np.int8 assert _get_int_dtype(7, signed=False, unsigned=True) == np.uint8
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/core.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cupy as cp import networkx as nx import pylibcugraph as plc import nx_cugraph as nxcg from nx_cugraph.utils import _get_int_dtype, networkx_algorithm, not_implemented_for __all__ = ["k_truss"] @not_implemented_for("directed") @not_implemented_for("multigraph") @networkx_algorithm def k_truss(G, k): """ Currently raises `NotImplementedError` for graphs with more than one connected component when k >= 3. We expect to fix this soon. """ if is_nx := isinstance(G, nx.Graph): G = nxcg.from_networkx(G, preserve_all_attrs=True) if nxcg.number_of_selfloops(G) > 0: raise nx.NetworkXError( "Input graph has self loops which is not permitted; " "Consider using G.remove_edges_from(nx.selfloop_edges(G))." ) # TODO: create renumbering helper function(s) if k < 3: # k-truss graph is comprised of nodes incident on k-2 triangles, so k<3 is a # boundary condition. Here, all we need to do is drop nodes with zero degree. # Technically, it would be okay to delete this branch of code, because # plc.k_truss_subgraph behaves the same for 0 <= k < 3. We keep this branch b/c # it's faster and has an "early return" if there are no nodes with zero degree. degrees = G._degrees_array() # Renumber step 0: node indices node_indices = degrees.nonzero()[0] if degrees.size == node_indices.size: # No change return G if is_nx else G.copy() src_indices = G.src_indices dst_indices = G.dst_indices # Renumber step 1: edge values (no changes needed) edge_values = {key: val.copy() for key, val in G.edge_values.items()} edge_masks = {key: val.copy() for key, val in G.edge_masks.items()} elif (ncc := nxcg.number_connected_components(G)) > 1: raise NotImplementedError( "nx_cugraph.k_truss does not yet work on graphs with more than one " f"connected component (this graph has {ncc}). We expect to fix this soon." ) else: edge_dtype = _get_int_dtype(G.src_indices.size - 1) edge_indices = cp.arange(G.src_indices.size, dtype=edge_dtype) src_indices, dst_indices, edge_indices, _ = plc.k_truss_subgraph( resource_handle=plc.ResourceHandle(), graph=G._get_plc_graph(edge_array=edge_indices), k=k, do_expensive_check=False, ) # Renumber step 0: node indices node_indices = cp.unique(cp.concatenate([src_indices, dst_indices])) # Renumber step 1: edge values if edge_indices.dtype != edge_dtype: # The returned edge_indices may have different dtype (and float) edge_indices = edge_indices.astype(edge_dtype) edge_values = {key: val[edge_indices] for key, val in G.edge_values.items()} edge_masks = {key: val[edge_indices] for key, val in G.edge_masks.items()} # Renumber step 2: edge indices mapper = cp.zeros(len(G), src_indices.dtype) mapper[node_indices] = cp.arange(node_indices.size, dtype=mapper.dtype) src_indices = mapper[src_indices] dst_indices = mapper[dst_indices] # Renumber step 3: node values node_values = {key: val[node_indices] for key, val in G.node_values.items()} node_masks = {key: val[node_indices] for key, val in G.node_masks.items()} # Renumber step 4: key_to_id if (id_to_key := G.id_to_key) is not None: key_to_id = { id_to_key[old_index]: new_index for new_index, old_index in enumerate(node_indices.tolist()) } else: key_to_id = None # Same as calling `G.from_coo`, but use __class__ to indicate it's a classmethod. new_graph = G.__class__.from_coo( node_indices.size, src_indices, dst_indices, edge_values, edge_masks, node_values, node_masks, key_to_id=key_to_id, ) new_graph.graph.update(G.graph) return new_graph
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/isolate.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING import cupy as cp from nx_cugraph.convert import _to_graph from nx_cugraph.utils import networkx_algorithm if TYPE_CHECKING: # pragma: no cover from nx_cugraph.typing import IndexValue __all__ = ["is_isolate", "isolates", "number_of_isolates"] @networkx_algorithm def is_isolate(G, n): G = _to_graph(G) index = n if G.key_to_id is None else G.key_to_id[n] return not ( (G.src_indices == index).any().tolist() or G.is_directed() and (G.dst_indices == index).any().tolist() ) def _mark_isolates(G) -> cp.ndarray[bool]: """Return a boolean mask array indicating indices of isolated nodes.""" mark_isolates = cp.ones(len(G), bool) mark_isolates[G.src_indices] = False if G.is_directed(): mark_isolates[G.dst_indices] = False return mark_isolates def _isolates(G) -> cp.ndarray[IndexValue]: """Like isolates, but return an array of indices instead of an iterator of nodes.""" G = _to_graph(G) return cp.nonzero(_mark_isolates(G))[0] @networkx_algorithm def isolates(G): G = _to_graph(G) return G._nodeiter_to_iter(iter(_isolates(G).tolist())) @networkx_algorithm def number_of_isolates(G): G = _to_graph(G) return _mark_isolates(G).sum().tolist()
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from . import ( bipartite, centrality, community, components, shortest_paths, link_analysis, ) from .bipartite import complete_bipartite_graph from .centrality import * from .components import * from .core import * from .isolate import * from .shortest_paths import * from .link_analysis import *
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/bipartite/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .generators import *
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/bipartite/generators.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from numbers import Integral import cupy as cp import networkx as nx import numpy as np from nx_cugraph.generators._utils import _create_using_class, _number_and_nodes from nx_cugraph.utils import index_dtype, networkx_algorithm, nodes_or_number __all__ = [ "complete_bipartite_graph", ] @nodes_or_number([0, 1]) @networkx_algorithm def complete_bipartite_graph(n1, n2, create_using=None): graph_class, inplace = _create_using_class(create_using) if graph_class.is_directed(): raise nx.NetworkXError("Directed Graph not supported") orig_n1, unused_nodes1 = n1 orig_n2, unused_nodes2 = n2 n1, nodes1 = _number_and_nodes(n1) n2, nodes2 = _number_and_nodes(n2) all_indices = cp.indices((n1, n2), dtype=index_dtype) indices0 = all_indices[0].ravel() indices1 = all_indices[1].ravel() + n1 del all_indices src_indices = cp.hstack((indices0, indices1)) dst_indices = cp.hstack((indices1, indices0)) bipartite = cp.zeros(n1 + n2, np.int8) bipartite[n1:] = 1 if isinstance(orig_n1, Integral) and isinstance(orig_n2, Integral): nodes = None else: nodes = list(range(n1)) if nodes1 is None else nodes1 nodes.extend(range(n2) if nodes2 is None else nodes2) if len(set(nodes)) != len(nodes): raise nx.NetworkXError("Inputs n1 and n2 must contain distinct nodes") G = graph_class.from_coo( n1 + n2, src_indices, dst_indices, node_values={"bipartite": bipartite}, id_to_key=nodes, name=f"complete_bipartite_graph({orig_n1}, {orig_n2})", ) if inplace: return create_using._become(G) return G
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/components/connected.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import cupy as cp import networkx as nx import pylibcugraph as plc from nx_cugraph.convert import _to_undirected_graph from nx_cugraph.utils import _groupby, networkx_algorithm, not_implemented_for from ..isolate import _isolates __all__ = [ "number_connected_components", "connected_components", "is_connected", "node_connected_component", ] @not_implemented_for("directed") @networkx_algorithm def number_connected_components(G): return sum(1 for _ in connected_components(G)) # PREFERRED IMPLEMENTATION, BUT PLC DOES NOT HANDLE ISOLATED VERTICES WELL # G = _to_undirected_graph(G) # unused_node_ids, labels = plc.weakly_connected_components( # resource_handle=plc.ResourceHandle(), # graph=G._get_plc_graph(), # offsets=None, # indices=None, # weights=None, # labels=None, # do_expensive_check=False, # ) # return cp.unique(labels).size @number_connected_components._can_run def _(G): # NetworkX <= 3.2.1 does not check directedness for us try: return not G.is_directed() except Exception: return False @not_implemented_for("directed") @networkx_algorithm def connected_components(G): G = _to_undirected_graph(G) if G.src_indices.size == 0: # TODO: PLC doesn't handle empty graphs (or isolated nodes) gracefully! return [{key} for key in G._nodeiter_to_iter(range(len(G)))] node_ids, labels = plc.weakly_connected_components( resource_handle=plc.ResourceHandle(), graph=G._get_plc_graph(), offsets=None, indices=None, weights=None, labels=None, do_expensive_check=False, ) groups = _groupby(labels, node_ids) it = (G._nodearray_to_set(connected_ids) for connected_ids in groups.values()) # TODO: PLC doesn't handle isolated vertices yet, so this is a temporary fix isolates = _isolates(G) if isolates.size > 0: isolates = isolates[isolates > node_ids.max()] if isolates.size > 0: it = itertools.chain( it, ({node} for node in G._nodearray_to_list(isolates)) ) return it @not_implemented_for("directed") @networkx_algorithm def is_connected(G): G = _to_undirected_graph(G) if len(G) == 0: raise nx.NetworkXPointlessConcept( "Connectivity is undefined for the null graph." ) for community in connected_components(G): return len(community) == len(G) raise RuntimeError # pragma: no cover # PREFERRED IMPLEMENTATION, BUT PLC DOES NOT HANDLE ISOLATED VERTICES WELL # unused_node_ids, labels = plc.weakly_connected_components( # resource_handle=plc.ResourceHandle(), # graph=G._get_plc_graph(), # offsets=None, # indices=None, # weights=None, # labels=None, # do_expensive_check=False, # ) # return labels.size == len(G) and cp.unique(labels).size == 1 @not_implemented_for("directed") @networkx_algorithm def node_connected_component(G, n): # We could also do plain BFS from n G = _to_undirected_graph(G) node_id = n if G.key_to_id is None else G.key_to_id[n] node_ids, labels = plc.weakly_connected_components( resource_handle=plc.ResourceHandle(), graph=G._get_plc_graph(), offsets=None, indices=None, weights=None, labels=None, do_expensive_check=False, ) indices = cp.nonzero(node_ids == node_id)[0] if indices.size == 0: return {n} return G._nodearray_to_set(node_ids[labels == labels[indices[0]]])
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/components/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .connected import *
0
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms
rapidsai_public_repos/cugraph/python/nx-cugraph/nx_cugraph/algorithms/community/louvain.py
# Copyright (c) 2023, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings import pylibcugraph as plc from nx_cugraph.convert import _to_undirected_graph from nx_cugraph.utils import ( _dtype_param, _groupby, _seed_to_int, networkx_algorithm, not_implemented_for, ) from ..isolate import _isolates __all__ = ["louvain_communities"] @not_implemented_for("directed") @networkx_algorithm( extra_params={ "max_level : int, optional": ( "Upper limit of the number of macro-iterations (max: 500)." ), **_dtype_param, } ) def louvain_communities( G, weight="weight", resolution=1, threshold=0.0000001, seed=None, *, max_level=None, dtype=None, ): """`seed` parameter is currently ignored.""" # NetworkX allows both directed and undirected, but cugraph only allows undirected. seed = _seed_to_int(seed) # Unused, but ensure it's valid for future compatibility G = _to_undirected_graph(G, weight) if G.src_indices.size == 0: # TODO: PLC doesn't handle empty graphs gracefully! return [{key} for key in G._nodeiter_to_iter(range(len(G)))] if max_level is None: max_level = 500 elif max_level > 500: warnings.warn( f"max_level is set too high (={max_level}), setting it to 500.", UserWarning, stacklevel=2, ) max_level = 500 node_ids, clusters, modularity = plc.louvain( resource_handle=plc.ResourceHandle(), graph=G._get_plc_graph(weight, 1, dtype), max_level=max_level, # TODO: add this parameter to NetworkX threshold=threshold, resolution=resolution, do_expensive_check=False, ) groups = _groupby(clusters, node_ids, groups_are_canonical=True) rv = [set(G._nodearray_to_list(ids)) for ids in groups.values()] # TODO: PLC doesn't handle isolated node_ids yet, so this is a temporary fix isolates = _isolates(G) if isolates.size > 0: isolates = isolates[isolates > node_ids.max()] if isolates.size > 0: rv.extend({node} for node in G._nodearray_to_list(isolates)) return rv @louvain_communities._can_run def _( G, weight="weight", resolution=1, threshold=0.0000001, seed=None, *, max_level=None, dtype=None, ): # NetworkX allows both directed and undirected, but cugraph only allows undirected. return not G.is_directed()
0