Skip to content

Cross-Stack Adapters

to_dgl(data)

Convert one derived-graph PyG carrier into (dgl graph, metadata).

Raises :class:TypeError when data is a :class:torch_geometric.data.Batch: the adapters convert one encoded graph at a time.

The returned graph is an int64 CPU dgl.graph((src, dst)) over num_nodes nodes (isolated objects survive) with:

  • ndata["x_ids"]: the [N, 6] float id channels verbatim,
  • ndata["role_ids"]: convenience x_ids[:, 0].long() role column,
  • edata["edge_attr"]: the [E, 9] float edge channels verbatim.

The metadata dict carries the shared vocabularies (vocab_roles / vocab_predicates / vocab_actions / vocab_relations / vocab_edge_kinds / channel_names / edge_channel_names), node_names when exported, and every other non-core attribute the carrier holds. When the input carries hyperedge membership (HypergraphIncidenceEncoder), two extra entries appear because core DGL has no native hypergraph:

  • hyperedge_index: the raw [2, sum(sizes)] membership tensor (node row, hyperedge row),
  • hyperedge_bipartite: a second int64 DGL graph of N + H nodes in which each member node points at its hyperedge anchor, whose id is the hyperedge index offset by N.

H is the carrier's authoritative hyperedge count (num_hyperedges / hyperedge_attr_ids.size(0)) when it declares one, and max(hyperedge_index[1]) + 1 otherwise. The encoder core guarantees no empty hyperedge (an arity-0 instance takes the anchor node as its single member), so the two agree by construction and a disagreement means a corrupted carrier — it is reported rather than silently under- or over-counting.

Source code in src/mifrost/encoders/cross_stack.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def to_dgl(data: Any) -> tuple[Any, dict[str, Any]]:
    """Convert one derived-graph PyG carrier into ``(dgl graph, metadata)``.

    Raises :class:`TypeError` when ``data`` is a
    :class:`torch_geometric.data.Batch`: the adapters convert one encoded
    graph at a time.

    The returned graph is an int64 CPU ``dgl.graph((src, dst))`` over
    ``num_nodes`` nodes (isolated objects survive) with:

    - ``ndata["x_ids"]``: the ``[N, 6]`` float id channels verbatim,
    - ``ndata["role_ids"]``: convenience ``x_ids[:, 0].long()`` role column,
    - ``edata["edge_attr"]``: the ``[E, 9]`` float edge channels verbatim.

    The metadata dict carries the shared vocabularies
    (``vocab_roles`` / ``vocab_predicates`` / ``vocab_actions`` /
    ``vocab_relations`` / ``vocab_edge_kinds`` / ``channel_names`` /
    ``edge_channel_names``), ``node_names`` when exported, and every other
    non-core attribute the carrier holds. When the input carries hyperedge
    membership (``HypergraphIncidenceEncoder``), two extra entries appear
    because core DGL has no native hypergraph:

    - ``hyperedge_index``: the raw ``[2, sum(sizes)]`` membership tensor
      (node row, hyperedge row),
    - ``hyperedge_bipartite``: a second int64 DGL graph of ``N + H`` nodes
      in which each member node points at its hyperedge anchor, whose id is
      the hyperedge index offset by ``N``.

    ``H`` is the carrier's authoritative hyperedge count
    (``num_hyperedges`` / ``hyperedge_attr_ids.size(0)``) when it declares
    one, and ``max(hyperedge_index[1]) + 1`` otherwise. The encoder core
    guarantees no empty hyperedge (an arity-0 instance takes the anchor node
    as its single member), so the two agree by construction and a
    disagreement means a corrupted carrier — it is reported rather than
    silently under- or over-counting.
    """
    _reject_batch(data)
    dgl = _require("dgl", "pip install dgl")
    import torch

    num_nodes = int(data.num_nodes)
    src = data.edge_index[0].long().cpu()
    dst = data.edge_index[1].long().cpu()
    graph = dgl.graph(
        (src, dst),
        num_nodes=num_nodes,
        idtype=torch.int64,
        device=torch.device("cpu"),
    )
    graph.ndata["x_ids"] = data.x_ids.cpu()
    graph.ndata["role_ids"] = data.x_ids[:, 0].long().cpu()
    graph.edata["edge_attr"] = data.edge_attr.cpu()

    metadata = _collect_metadata(data)
    hyperedge_index = getattr(data, "hyperedge_index", None)
    if isinstance(hyperedge_index, torch.Tensor) and hyperedge_index.numel() > 0:
        members = hyperedge_index[0].long().cpu()
        anchor_rows = hyperedge_index[1].long().cpu()
        num_hyperedges = int(anchor_rows.max().item()) + 1
        declared = _declared_hyperedge_count(data)
        if declared is not None:
            if declared != num_hyperedges:
                raise ValueError(
                    "hyperedge membership disagrees with the declared hyperedge "
                    f"count ({num_hyperedges} implied by hyperedge_index[1], "
                    f"{declared} declared); the encoder core guarantees every "
                    "hyperedge has at least one member, so this carrier is "
                    "inconsistent"
                )
            num_hyperedges = declared
        metadata["hyperedge_bipartite"] = dgl.graph(
            (members, anchor_rows + num_nodes),
            num_nodes=num_nodes + num_hyperedges,
            idtype=torch.int64,
            device=torch.device("cpu"),
        )
    elif hyperedge_index is not None:
        # Empty membership: no hyperedges to anchor, but keep the entry so
        # consumers can rely on the key whenever the input carries the attr.
        empty = torch.empty(0, dtype=torch.int64)
        metadata["hyperedge_bipartite"] = dgl.graph(
            (empty, empty),
            num_nodes=num_nodes,
            idtype=torch.int64,
            device=torch.device("cpu"),
        )
    return graph, metadata

to_jraph(data)

Convert one derived-graph PyG carrier into (GraphsTuple, metadata).

Raises :class:TypeError when data is a :class:torch_geometric.data.Batch: the adapters convert one encoded graph at a time.

The returned single-graph jraph.GraphsTuple stores:

  • nodes: the [N, 6] float id channels,
  • edges: the [E, 9] float edge channels,
  • senders / receivers: edge_index[0] / edge_index[1],
  • n_node=[N], n_edge=[E],
  • globals: the metadata dict itself (vocabularies plus every hyperedge/tuple/spd tensor).

The metadata dict mirrors globals so callers that want to run jax.jit can swap globals out first: string-valued vocabularies are valid pytree leaves outside tracing but not valid JAX input types.

Source code in src/mifrost/encoders/cross_stack.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def to_jraph(data: Any) -> tuple[Any, dict[str, Any]]:
    """Convert one derived-graph PyG carrier into ``(GraphsTuple, metadata)``.

    Raises :class:`TypeError` when ``data`` is a
    :class:`torch_geometric.data.Batch`: the adapters convert one encoded
    graph at a time.

    The returned single-graph ``jraph.GraphsTuple`` stores:

    - ``nodes``: the ``[N, 6]`` float id channels,
    - ``edges``: the ``[E, 9]`` float edge channels,
    - ``senders`` / ``receivers``: ``edge_index[0]`` / ``edge_index[1]``,
    - ``n_node=[N]``, ``n_edge=[E]``,
    - ``globals``: the metadata dict itself (vocabularies plus every
      hyperedge/tuple/spd tensor).

    The metadata dict mirrors ``globals`` so callers that want to run
    ``jax.jit`` can swap ``globals`` out first: string-valued vocabularies
    are valid pytree leaves outside tracing but not valid JAX input types.
    """
    _reject_batch(data)
    jraph = _require("jraph", "pip install jraph jax")
    import jax.numpy as jnp

    metadata = _collect_metadata(data)
    graphs_tuple = jraph.GraphsTuple(
        nodes=jnp.asarray(data.x_ids.float()),
        edges=jnp.asarray(data.edge_attr.float()),
        receivers=jnp.asarray(data.edge_index[1].long()),
        senders=jnp.asarray(data.edge_index[0].long()),
        n_node=jnp.asarray([int(data.num_nodes)]),
        n_edge=jnp.asarray([int(data.edge_index.size(1))]),
        globals=metadata,
    )
    return graphs_tuple, dict(metadata)