Name | ckatorch JSON |
Version |
1.0.0
JSON |
| download |
home_page | None |
Summary | Centered Kernel Alignment in PyTorch |
upload_time | 2025-08-16 14:28:22 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.10 |
license | MIT License Copyright (c) 2024 Alessandro Ristori Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
cka
centered kernel aligment
deep learning
neural network similarity
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
<div align="center">
# :robot: CKA PyTorch :robot:
**CKA (Centered Kernel Alignment) in PyTorch.**
[](https://github.com/python/cpython)
[](https://github.com/pytorch/pytorch)
</div>
> [!WARNING]
> This repository has been built mainly for personal and academic use since <img height="15" width="15" src="https://cdn.simpleicons.org/pytorch"/>[Captum](https://github.com/pytorch/captum) still needs to implement its variant of CKA. As such, do not expect this project to work for every model.
---
## :black_nib: About
> [!NOTE]
> Centered Kernel Alignment (CKA) [1] is a similarity index between representations of features in neural networks, based on the Hilbert-Schmidt Independence Criterion (HSIC) [2]. Given a set of examples, CKA compares the representations of examples passed through the layers that we want to compare.
Given two matrices $X \in \mathbb{R}^{n\times s_1}$ and $Y \in \mathbb{R}^{n\times s_2}$ representing the output of two layers, we can define two auxiliary $n \times n$ Gram matrices $K=XX^T$ and $L=YY^T$ and compute the *dot-product similarity* between them
$$\langle vec(XX^T), vec(YY^T)\rangle = tr(XX^T YY^T) = \lVert Y^T X \rVert_F^2.$$
Then, the $HSIC$ on $K$ and $L$ is defined as
$$HSIC_0(K, L) = \frac{tr(KHLH)}{(n - 1)^2},$$
where $H = I_n - \frac{1}{n}J_n$ is the centering matrix and $J_n$ is an $n \times n$ matrix filled with ones. Finally, to obtain the CKA value we only need to normalize $HSIC_0$
$$CKA(K, L) = \frac{HSIC(K, L)}{\sqrt{HSIC(K, K) HSIC(L, L)}}.$$
> [!NOTE]
> However, naive computation of linear CKA (i.e.: the previous equation) requires maintaining the activations across the entire dataset in memory, which is challenging for wide and deep networks [3].
Therefore, we need to define the unbiased estimator of HSIC so that the value of CKA is independent of the batch size
$$HSIC_1(K, L)=\frac{1}{n(n-3)}\left( tr(\tilde{K}, \tilde{L}) + \frac{1^T\tilde{K}11^T\tilde{L}1}{(n-1)(n-2)} - \frac{2}{n-2}1^T\tilde{K}\tilde{L}1\right),$$
where $\tilde{K}$ and $\tilde{L}$ are obtained by setting the diagonal entries of $K$ and $L$ to zero. Finally, we can compute the minibatch version of CKA by averaging $HSIC_1$ scores over $k$ minibatches
$$CKA_{minibatch}=\frac{\frac{1}{k} \displaystyle\sum_{i=1}^{k} HSIC_1(K_i, L_i)}{\sqrt{\frac{1}{k} \displaystyle\sum_{i=1}^{k} HSIC_1(K_i, K_i)}\sqrt{\frac{1}{k} \displaystyle\sum_{i=1}^{k} HSIC_1(L_i, L_i)}},$$
with $K_i=X_iX_i^T$ and $L_i=Y_iY_i^T$, where $X_i \in \mathbb{R}^{m \times p_1}$ and $Y_i \in \mathbb{R}^{m \times p_2}$ are now matrices containing activations of the $i^{th}$ minibatch of $m$ examples sampled without replacement [3].
---
## :package: Installation
This project requires python >= 3.10.
### Create a new venv
> [!NOTE]
> This will create a new virtual environment in the working directory under .venv.
```bash
# If you have uv installed
uv venv
# Otherwise
python -m venv .venv
# Activate the virtual environment
source .venv/bin/activate # if you are on Linux
.\.venv\Scripts\activate.bat # if you are using the cmd on Windows
.\.venv\Scripts\Activate.ps1 # if you are using the PowerShell on Windows
```
### Install the package
> [!NOTE]
> This will install <img height="15" width="15" src="https://cdn.simpleicons.org/pytorch"/>PyTorch compiled with CUDA.
You can install the package by either:
- _using pip_
```bash
# Using uv
uv pip install git+https://github.com/RistoAle97/centered-kernel-alignment
# Using pip
pip install git+https://github.com/RistoAle97/centered-kernel-alignment
```
- _cloning the repository and installing the dependencies_
```bash
git clone https://github.com/RistoAle97/centered-kernel-alignment
# If you have uv installed
uv pip install -e centered-kernel-alignment
uv pip install ckatorch --group dev # if you want to also install the dev dependencies
# Otherwise
pip install -e centered-kernel-alignment
pip install ckatorch --group dev # same as for uv, remember to open a pull request afterwards
```
Take a look at the `examples` directory to understand how to compute CKA in two basic scenarios.
---
## :framed_picture: Plots
> [!NOTE]
> The comparison makes more sense if the models share a common architecture.
Model compared with itself | Different models compared
:-------------------------:|:-------------------------:
 | 
---
## :books: Bibliography
[1] Kornblith, Simon, et al. ["Similarity of neural network representations revisited."](https://arxiv.org/abs/1905.00414) *International Conference on Machine Learning*. PMLR, 2019.
[2] Wang, Tinghua, Xiaolu Dai, and Yuze Liu. ["Learning with Hilbert–Schmidt independence criterion: A review and new perspectives."](https://www.sciencedirect.com/science/article/pii/S0950705121008297) *Knowledge-based systems* 234 (2021): 107567.
[3] Nguyen, Thao, Maithra Raghu, and Simon Kornblith. ["Do wide and deep networks learn the same things? uncovering how neural network representations vary with width and depth."](https://arxiv.org/abs/2010.15327) *arXiv preprint* arXiv:2010.15327 (2020).
This project is also based on the following repositories:
- [representation_similarity](https://github.com/google-research/google-research/tree/master/representation_similarity) (original implementation).
- [PyTorch-Model-Compare](https://github.com/AntixK/PyTorch-Model-Compare) (nice PyTorch implementation that employs hooks).
- [CKA.pytorch](https://github.com/numpee/CKA.pytorch) (minibatch version of CKA and useful batched implementation of $HSIC_1$).
---
## :memo: License
This project is [MIT licensed](https://github.com/RistoAle97/centered-kernel-alignment/blob/main/LICENSE).
Raw data
{
"_id": null,
"home_page": null,
"name": "ckatorch",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "CKA, Centered Kernel Aligment, Deep Learning, Neural Network Similarity",
"author": null,
"author_email": "Alessandro Ristori <aleristori97@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/b3/5a/f2962332cd25ffada4e7beec0f6275ccf4f68611b60c4ef740b76f40286d/ckatorch-1.0.0.tar.gz",
"platform": null,
"description": "<div align=\"center\">\n\n# :robot: CKA PyTorch :robot:\n**CKA (Centered Kernel Alignment) in PyTorch.**\n\n[](https://github.com/python/cpython)\n[](https://github.com/pytorch/pytorch)\n\n</div>\n\n> [!WARNING]\n> This repository has been built mainly for personal and academic use since <img height=\"15\" width=\"15\" src=\"https://cdn.simpleicons.org/pytorch\"/>[Captum](https://github.com/pytorch/captum) still needs to implement its variant of CKA. As such, do not expect this project to work for every model.\n\n---\n\n## :black_nib: About\n> [!NOTE]\n> Centered Kernel Alignment (CKA) [1] is a similarity index between representations of features in neural networks, based on the Hilbert-Schmidt Independence Criterion (HSIC) [2]. Given a set of examples, CKA compares the representations of examples passed through the layers that we want to compare.\n\nGiven two matrices $X \\in \\mathbb{R}^{n\\times s_1}$ and $Y \\in \\mathbb{R}^{n\\times s_2}$ representing the output of two layers, we can define two auxiliary $n \\times n$ Gram matrices $K=XX^T$ and $L=YY^T$ and compute the *dot-product similarity* between them\n\n$$\\langle vec(XX^T), vec(YY^T)\\rangle = tr(XX^T YY^T) = \\lVert Y^T X \\rVert_F^2.$$\n\nThen, the $HSIC$ on $K$ and $L$ is defined as\n\n$$HSIC_0(K, L) = \\frac{tr(KHLH)}{(n - 1)^2},$$\n\nwhere $H = I_n - \\frac{1}{n}J_n$ is the centering matrix and $J_n$ is an $n \\times n$ matrix filled with ones. Finally, to obtain the CKA value we only need to normalize $HSIC_0$\n\n$$CKA(K, L) = \\frac{HSIC(K, L)}{\\sqrt{HSIC(K, K) HSIC(L, L)}}.$$\n\n> [!NOTE]\n> However, naive computation of linear CKA (i.e.: the previous equation) requires maintaining the activations across the entire dataset in memory, which is challenging for wide and deep networks [3].\n\nTherefore, we need to define the unbiased estimator of HSIC so that the value of CKA is independent of the batch size\n\n$$HSIC_1(K, L)=\\frac{1}{n(n-3)}\\left( tr(\\tilde{K}, \\tilde{L}) + \\frac{1^T\\tilde{K}11^T\\tilde{L}1}{(n-1)(n-2)} - \\frac{2}{n-2}1^T\\tilde{K}\\tilde{L}1\\right),$$\n\nwhere $\\tilde{K}$ and $\\tilde{L}$ are obtained by setting the diagonal entries of $K$ and $L$ to zero. Finally, we can compute the minibatch version of CKA by averaging $HSIC_1$ scores over $k$ minibatches\n\n$$CKA_{minibatch}=\\frac{\\frac{1}{k} \\displaystyle\\sum_{i=1}^{k} HSIC_1(K_i, L_i)}{\\sqrt{\\frac{1}{k} \\displaystyle\\sum_{i=1}^{k} HSIC_1(K_i, K_i)}\\sqrt{\\frac{1}{k} \\displaystyle\\sum_{i=1}^{k} HSIC_1(L_i, L_i)}},$$\n\nwith $K_i=X_iX_i^T$ and $L_i=Y_iY_i^T$, where $X_i \\in \\mathbb{R}^{m \\times p_1}$ and $Y_i \\in \\mathbb{R}^{m \\times p_2}$ are now matrices containing activations of the $i^{th}$ minibatch of $m$ examples sampled without replacement [3].\n\n---\n\n## :package: Installation\nThis project requires python >= 3.10.\n\n### Create a new venv\n> [!NOTE]\n> This will create a new virtual environment in the working directory under .venv.\n```bash\n# If you have uv installed\nuv venv\n\n# Otherwise\npython -m venv .venv\n\n# Activate the virtual environment\nsource .venv/bin/activate # if you are on Linux\n.\\.venv\\Scripts\\activate.bat # if you are using the cmd on Windows\n.\\.venv\\Scripts\\Activate.ps1 # if you are using the PowerShell on Windows\n```\n\n### Install the package\n> [!NOTE]\n> This will install <img height=\"15\" width=\"15\" src=\"https://cdn.simpleicons.org/pytorch\"/>PyTorch compiled with CUDA.\n\nYou can install the package by either:\n- _using pip_\n ```bash\n # Using uv\n uv pip install git+https://github.com/RistoAle97/centered-kernel-alignment\n\n # Using pip\n pip install git+https://github.com/RistoAle97/centered-kernel-alignment\n ```\n\n- _cloning the repository and installing the dependencies_\n ```bash\n git clone https://github.com/RistoAle97/centered-kernel-alignment\n\n # If you have uv installed\n uv pip install -e centered-kernel-alignment\n uv pip install ckatorch --group dev # if you want to also install the dev dependencies\n\n # Otherwise\n pip install -e centered-kernel-alignment\n pip install ckatorch --group dev # same as for uv, remember to open a pull request afterwards\n ```\n\nTake a look at the `examples` directory to understand how to compute CKA in two basic scenarios.\n\n---\n\n## :framed_picture:\tPlots\n> [!NOTE]\n> The comparison makes more sense if the models share a common architecture.\n\nModel compared with itself | Different models compared\n:-------------------------:|:-------------------------:\n | \n\n---\n\n## :books: Bibliography\n[1] Kornblith, Simon, et al. [\"Similarity of neural network representations revisited.\"](https://arxiv.org/abs/1905.00414) *International Conference on Machine Learning*. PMLR, 2019.\n\n[2] Wang, Tinghua, Xiaolu Dai, and Yuze Liu. [\"Learning with Hilbert\u2013Schmidt independence criterion: A review and new perspectives.\"](https://www.sciencedirect.com/science/article/pii/S0950705121008297) *Knowledge-based systems* 234 (2021): 107567.\n\n[3] Nguyen, Thao, Maithra Raghu, and Simon Kornblith. [\"Do wide and deep networks learn the same things? uncovering how neural network representations vary with width and depth.\"](https://arxiv.org/abs/2010.15327) *arXiv preprint* arXiv:2010.15327 (2020).\n\nThis project is also based on the following repositories:\n- [representation_similarity](https://github.com/google-research/google-research/tree/master/representation_similarity) (original implementation).\n- [PyTorch-Model-Compare](https://github.com/AntixK/PyTorch-Model-Compare) (nice PyTorch implementation that employs hooks).\n- [CKA.pytorch](https://github.com/numpee/CKA.pytorch) (minibatch version of CKA and useful batched implementation of $HSIC_1$).\n\n---\n\n## :memo: License\nThis project is [MIT licensed](https://github.com/RistoAle97/centered-kernel-alignment/blob/main/LICENSE).\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2024 Alessandro Ristori Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"summary": "Centered Kernel Alignment in PyTorch",
"version": "1.0.0",
"project_urls": {
"Repository": "https://github.com/RistoAle97/centered-kernel-alignment"
},
"split_keywords": [
"cka",
" centered kernel aligment",
" deep learning",
" neural network similarity"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "49dedcc2e08f3b0b9213ae14da161b9e89228fbc981759c528aa5c856d630d86",
"md5": "b3ce87e24fa30da761d7f5e3a8aacb91",
"sha256": "3b80e7ab93117851ae9aa57dbec9dd45e5b250c551e49552a04cd9d79c1bde20"
},
"downloads": -1,
"filename": "ckatorch-1.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "b3ce87e24fa30da761d7f5e3a8aacb91",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 15839,
"upload_time": "2025-08-16T14:28:20",
"upload_time_iso_8601": "2025-08-16T14:28:20.988683Z",
"url": "https://files.pythonhosted.org/packages/49/de/dcc2e08f3b0b9213ae14da161b9e89228fbc981759c528aa5c856d630d86/ckatorch-1.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "b35af2962332cd25ffada4e7beec0f6275ccf4f68611b60c4ef740b76f40286d",
"md5": "dcb07335a3e445e0b2b7605c504f0e26",
"sha256": "160f9034b8e9bb91fdfcbe65b0f28311af8d4c07f9e94ef9dc77926ea0674253"
},
"downloads": -1,
"filename": "ckatorch-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "dcb07335a3e445e0b2b7605c504f0e26",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 147697,
"upload_time": "2025-08-16T14:28:22",
"upload_time_iso_8601": "2025-08-16T14:28:22.635729Z",
"url": "https://files.pythonhosted.org/packages/b3/5a/f2962332cd25ffada4e7beec0f6275ccf4f68611b60c4ef740b76f40286d/ckatorch-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-16 14:28:22",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "RistoAle97",
"github_project": "centered-kernel-alignment",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "ckatorch"
}