Skip to content

Gat cora#157

Draft
xrhd wants to merge 3 commits intojax-ml:mainfrom
xrhd:gat-cora
Draft

Gat cora#157
xrhd wants to merge 3 commits intojax-ml:mainfrom
xrhd:gat-cora

Conversation

@xrhd
Copy link
Copy Markdown

@xrhd xrhd commented Feb 6, 2026

Resolves #12

This PR introduces the Graph Attention Network (GAT) implementation in bonsai. The implementation follows the original architecture by Veličković et al. (2018) and has been validated against the Cora dataset.

  • Supports multi-head attention with configurable concatenation (hidden layers) and averaging (output layer).
  • Includes a validation notebook that replicates the transductive Cora benchmark.
  • Cora Dataset: Achieved 80.3% test accuracy (exceeding the 80% baseline) using a standard 2-layer GAT configuration.
  • Edge Cases: Verified handling of zero-edge graphs (self-loops) and dimension mismatches.

Reference

Checklist

  • I have read the [Contribution Guidelines (https://github.com/jax-ml/bonsai/blob/main/CONTRIBUTING.md#contributing-a-model) and used pre-commit hooks
    (https://github.com/jax-ml/bonsai/blob/main/CONTRIBUTING.md#linting-and-type-checking) to format this commit.
  • I have added all the necessary unit tests for my change. (run_model.py for model usage, GAT_cora_validation.py for quality).
  • (If using an LLM) I have carefully reviewed and removed all superfluous comments or unneeded, commented-out code. Only necessary and functional code
    remains.
  • I have signed the Contributor License Agreement (CLA).

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @xrhd, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates a new Graph Attention Network (GAT) model into the bonsai library, leveraging JAX/Flax for its implementation. The primary goal is to expand the library's capabilities to include graph-based neural networks, demonstrated by successfully replicating and exceeding the benchmark accuracy on the Cora dataset. This addition provides a robust and validated GAT model, complete with usage examples and comprehensive testing for various scenarios.

Highlights

  • New GAT Model Implementation: Introduces a Graph Attention Network (GAT) model implemented in JAX/Flax, following the original architecture by Veličković et al. (2018).
  • Cora Dataset Validation: The GAT implementation has been validated against the Cora dataset, achieving 80.3% test accuracy, exceeding the 80% baseline.
  • Multi-head Attention Support: The model supports multi-head attention with configurable concatenation for hidden layers and averaging for the output layer.
  • Robustness to Edge Cases: Verified handling of zero-edge graphs (self-loops) and dimension mismatches in the model.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • README.md
    • Updated the main README to include GAT in the list of available models under "Graph Attention".
  • bonsai/models/gat/.gitignore
    • Added a .gitignore file to exclude tests/data from version control within the new GAT model directory.
  • bonsai/models/gat/README.md
    • Provided a dedicated README for the GAT model, detailing its JAX/Flax implementation, usage examples, and instructions for reproducing the Cora dataset validation.
  • bonsai/models/gat/modeling.py
    • Introduced the core implementation of the GAT model, including GATLayer and the main GAT class, defining the attention mechanism, linear transformations, and multi-layer architecture.
  • bonsai/models/gat/params.py
    • Defined GATConfig dataclass to manage hyperparameters for the GAT model, such as feature dimensions, number of heads, dropout probability, and LeakyReLU alpha.
  • bonsai/models/gat/tests/GAT_cora_validation.ipynb
    • Added a Jupyter notebook for end-to-end validation of the GAT model on the Cora dataset, covering data loading, preprocessing, model training, and evaluation, demonstrating the achieved accuracy.
  • bonsai/models/gat/tests/GAT_cora_validation.md
    • Markdown representation of the GAT_cora_validation.ipynb notebook.
  • bonsai/models/gat/tests/run_model.py
    • Implemented unit tests to verify the GAT model's forward pass functionality and its handling of various edge cases, such as zero-edge graphs and dimension mismatches.
Activity
  • The pull request introduces a new Graph Attention Network (GAT) model.
  • The GAT implementation is based on the original research paper by Veličković et al. (2018).
  • Validation against the Cora dataset has been performed, achieving a test accuracy of 80.3%.
  • The implementation supports multi-head attention and handles specific edge cases.
  • The author has confirmed adherence to contribution guidelines, including unit tests and CLA signing.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a JAX/Flax implementation of the Graph Attention Network (GAT) model, complete with a validation notebook for the Cora dataset and basic unit tests. The implementation correctly supports multi-head attention and aligns with the original GAT architecture. The changes include adding the GAT model files, updating the main README.md to list the new model, and providing a .gitignore for test data. Overall, the code is well-structured and functional, but there are a few areas for improvement regarding documentation consistency, parameter usage, and robustness in error handling.

dropout_rng: jax.Array,
dropout_prob: float = 0.6,
alpha: float = 0.2,
concat_hidden: bool = True,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The concat_hidden parameter is defined in the GAT class's __init__ method but is not used. The concat argument for GATLayer within the hidden layers loop is hardcoded to True. This makes the concat_hidden parameter redundant and potentially misleading. Please either remove it or integrate its functionality.


## Validation

To reproduce the results on the Cora dataset (~83% accuracy):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The validation section states ~83% accuracy for the Cora dataset, but the pull request description mentions 80.3%. Please ensure consistency in the reported accuracy across all documentation.

# Masked attention
# adj is assumed to be 0 for no edge, 1 for edge (including self-loop)
# We want to mask where adj is 0
zero_vec = -9e15 * jnp.ones_like(e)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using a hardcoded large negative number (-9e15) for attention masking can sometimes lead to numerical instability or issues if the floating-point precision changes. It's generally safer and more robust to use jnp.finfo(e.dtype).min to get the smallest representable number for the given data type.

Suggested change
zero_vec = -9e15 * jnp.ones_like(e)
zero_vec = jnp.finfo(e.dtype).min * jnp.ones_like(e)

" from bonsai.models.gat.params import GATConfig\n",
"except ImportError:\n",
" try:\n",
" !pip insetall -e .\n",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's a typo in the pip install command: insetall should be install.

        !pip install -e .

"print(f\"Test Accuracy: {test_acc:.4f}\")\n",
"\n",
"if test_acc >= 0.80:\n",
" print(\"SUCCESS: Accuracy is above 80%\")\n",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The validation notebook output shows a test accuracy of 0.8032, which is 80.32%. However, the bonsai/models/gat/README.md states ~83% accuracy. Please ensure that the reported accuracy in the README matches the actual validation results.

from bonsai.models.gat.params import GATConfig
except ImportError:
try:
!pip insetall -e .
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's a typo in the pip install command: insetall should be install.

Suggested change
!pip insetall -e .
!pip install -e .

Comment on lines +60 to +66
print("Case 2: Feature dimension mismatch...")
x_wrong = jax.random.normal(key, (N, F + 1))
try:
model(x_wrong, adj_zero, training=False)
print("Failure: Model should have raised a dimension mismatch error.")
except Exception as e:
print(f"Success: Correctly caught error: {e}")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While JAX will raise an error for dimension mismatches, it's good practice to add explicit input shape validation at the beginning of the __call__ method in GATLayer or GAT. This provides clearer error messages to users and makes the model more robust. For example, you could check h.shape[1] == self.in_features and adj.shape == (N, N).

@chapman20j
Copy link
Copy Markdown
Collaborator

Hi @xrhd. Thanks for opening this PR! I see that this is still in a draft stage. Let me know when you're ready for us to take a look. Please also address the comments from gemini-code-assist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Graph Attention Network (GAT)

2 participants