How can I get the adjacency matrix of a dgl block

Does there API to get the adjacency matrix of dgl block, especially of the weighted graph.
I constructed a big weighted big graph, and got the subgraph of block by node dataloader, but I cannot get the adjacency matrix of this block.
Have you ever come across this problem ?

See if the example below helps:

import dgl
import torch
from scipy.sparse import rand, coo_matrix

adj = rand(100, 100, density=0.05)
g = dgl.from_scipy(adj)
g.edata['w'] = torch.randn(500, 1)
sampler = dgl.dataloading.MultiLayerFullNeighborSampler(2)
dataloader = dgl.dataloading.NodeDataLoader(g, list(range(100)), sampler, batch_size=16)
input_nodes, output_nodes, blocks = next(iter(dataloader))
demo_block = blocks[0]
# If you don't care about edge weight
adj = demo_block.adj()
# If you do want to keep the edge weight
graph_data = (demo_block.edata['w'].squeeze(-1), demo_block.edges())
shape = (g.num_nodes(), g.num_nodes())
adj = coo_matrix(graph_data, shape)

Thanks for your nice example. It is really helpfule!
I still have some questions

  1. in your example code
adj = rand(100, 100, density=0.05)
g = dgl.from_scipy(adj)
g.edata['w'] = torch.randn(500, 1)

what if the adj tensor not only for the graph structure, but also provides the edge weight ? so how to use the weight in adj for the graph edge weight?

  1. If I use cuda to train the network, how to get the adjacency matrix of this block in GPU to avoid the transfer from cpu to gpu?
  1. how to use the weight in adj for the graph edge weight?

    dgl.from_scipy allows retrieving the edge weights from adj. See the doc.

  2. If I use cuda to train the network, how to get the adjacency matrix of this block in GPU to avoid the transfer from cpu to gpu?

    If you want a sparse adjacency matrix on GPU and assume your block is on GPU, then below is all you need

    src, dst = demo_block.edges()
    

    If you need a dense one

    src, dst = demo_block.edges()
    block_adj = torch.zeros(demo_block.num_src_nodes(), demo_block.num_dst_nodes(), device='cuda:0')
    block_adj[src, dst] = demo_block.edata['w'].squeeze(-1)
    

    but then you are copying a tensor from CPU to GPU as well…