Metadata-Version: 2.4
Name: mlx-graphs-explain
Version: 0.0.1
Summary: Explainability for Graph Neural Networks on Apple Silicon, built on mlx-graphs and MLX
Author: mlx-graphs contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/mlx-graphs/mlx-graphs-explain
Project-URL: Issues, https://github.com/mlx-graphs/mlx-graphs-explain/issues
Keywords: mlx,apple-silicon,graph-neural-networks,gnn,explainable-ai,xai
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: MacOS
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mlx>=0.20
Requires-Dist: mlx-graphs>=0.2
Requires-Dist: numpy
Provides-Extra: viz
Requires-Dist: matplotlib; extra == "viz"
Requires-Dist: networkx; extra == "viz"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: matplotlib; extra == "dev"
Requires-Dist: networkx; extra == "dev"
Dynamic: license-file

# mlx-graphs-explain

Explainability for Graph Neural Networks on Apple Silicon, built on
[mlx-graphs](https://github.com/mlx-graphs/mlx-graphs) and [MLX](https://github.com/ml-explore/mlx).

The API mirrors [`torch_geometric.explain`](https://pytorch-geometric.readthedocs.io/en/latest/modules/explain.html),
so PyG users should feel at home.

## Installation

```bash
pip install mlx-graphs-explain
```

From source:

```bash
git clone https://github.com/mlx-graphs/mlx-graphs-explain.git && cd mlx-graphs-explain
pip install -e ".[dev]"
```

## Algorithms

| Algorithm | Module | Type | Node mask | Edge mask | Task levels |
|---|---|---|---|---|---|
| `Saliency` | `algorithm.gradient` | gradient | ✓ | ✓ | node, graph |
| `IntegratedGradients` | `algorithm.gradient` | gradient | ✓ | ✓ | node, graph |
| `GNNExplainer` | `algorithm.gnn_explainer` | mask learning | ✓ | ✓ | node, graph |

PyG runs gradient methods through Captum (`CaptumExplainer`); MLX has no
Captum, so `Saliency` and `IntegratedGradients` are native here.

## Quickstart

```python
import mlx.nn as nn
from mlx_graphs.nn import GCNConv

from mlx_graphs_explain import Explainer
from mlx_graphs_explain.algorithm import GNNExplainer


class GCN(nn.Module):
    def __init__(self, in_dim, hidden, out_dim):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hidden)
        self.conv2 = GCNConv(hidden, out_dim)

    # accept `edge_weights` and pass it to the layers so edges can be explained
    def __call__(self, edge_index, node_features, edge_weights=None):
        h = nn.relu(self.conv1(edge_index, node_features, edge_weights))
        return self.conv2(edge_index, h, edge_weights)


model = GCN(...)  # train it first

explainer = Explainer(
    model=model,
    algorithm=GNNExplainer(epochs=200),
    explanation_type="model",
    node_mask_type="attributes",
    edge_mask_type="object",
    model_config=dict(
        mode="multiclass_classification",
        task_level="node",
        return_type="raw",
    ),
)

explanation = explainer(edge_index, node_features, index=10)
explanation.node_mask  # [num_nodes, num_features]
explanation.edge_mask  # [num_edges]

top = explanation.threshold("topk_hard", 10)
top.get_explanation_subgraph()  # edge_index of the 10 most important edges
```

Note the mlx-graphs argument order: `explainer(edge_index, node_features, ...)`.

### Evaluating explanations

```python
from mlx_graphs_explain.metric import characterization_score, fidelity

pos, neg = fidelity(explainer, explanation.threshold("topk_hard", 10))
characterization_score(pos, neg)
```

`groundtruth_auc` scores a mask against a known ground truth, and
`mlx_graphs_explain.datasets.ba_shapes` builds the BA-Shapes benchmark.

### Visualizing explanations

```bash
pip install "mlx-graphs-explain[viz]"   # matplotlib + networkx
```

```python
# the explanation subgraph: edge opacity = edge importance,
# explained node in red, nodes shaded by importance ("object" node masks)
explanation.threshold("topk", 12).visualize_graph("explanation.png")

# write each edge's mask value on it
explanation.visualize_graph("explanation.png", edge_labels=True)

# bar plot of feature importance ("attributes" node masks)
explanation.visualize_feature_importance("features.png", top_k=10)
```

Both methods match PyG's names and arguments. `visualize_graph` uses
graphviz when it is installed (`pip install graphviz` and
`brew install graphviz`), else networkx; pass `backend="networkx"` to choose.
Pass `highlight_index=False` or `show_node_mask=False` to turn off the extras.

## Example: BA-Shapes

```bash
python examples/ba_shapes_demo.py
```

Trains a 3-layer GCN on BA-Shapes, then explains 20 nodes inside "house"
motifs. Edge AUC measures how well the edge mask finds the motif. It also
saves `ba_shapes_explanation.png`: the edges GNNExplainer considers
important (mask > 0.1) for a roof node, labelled with their mask values.

## Reproducibility

On the Mac GPU, training may not be bit-for-bit reproducible even with
`mx.random.seed`: message passing sums neighbour messages with parallel
scatter-adds, whose order is not guaranteed to be the same between runs. The tiny floating-point
differences add up over training, so two runs can give slightly different
models and therefore slightly different explanations (e.g. GNNExplainer may
weight two equivalent edges differently). For identical results on every run,
use the CPU:

```python
import mlx.core as mx

mx.set_default_device(mx.cpu)
```

## Current limitations

- **Edge masks go through `edge_weights`.** The explained model must accept an
  `edge_weights` keyword and pass it to its layers. For GCN-style layers the
  mask also changes the degree normalization, which affects fidelity scores
  on hard (thresholded) masks. A mask hook inside mlx-graphs' `MessagePassing`
  will remove both limitations.
- Edge-level tasks (link prediction) and heterogeneous graphs are not supported yet.

## Roadmap

- `PGExplainer`, `AttentionExplainer`, `GraphMaskExplainer`
- `SubgraphX`, counterfactual explainers
- More benchmarks (Tree-Cycles, Tree-Grid, BA-2Motifs)

## Development

```bash
pip install -e ".[dev]"
pytest
ruff check . && ruff format --check .
```

## License

MIT
