Skip to main content

Centered Kernel Alignment in PyTorch

Project description

🤖 CKA PyTorch 🤖

CKA (Centered Kernel Alignment) in PyTorch.

Python Pytorch

PyPI Python versions

[!WARNING] This repository has been built mainly for personal and academic use since Captum still needs to implement its variant of CKA. As such, do not expect this project to work for every model.


✒️ 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].


📦 Installation

This project requires python >= 3.10.

Create a new venv

# 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 PyTorch compiled with CUDA.

You can install the package:

  • from PyPI

    # Using uv
    uv pip install ckatorch
    
    # Using pip
    pip install ckatorch
    
  • from this repo

    # 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
    
  • by cloning the repository and installing the dependencies

    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.


🖼️ Plots

[!NOTE] The comparison makes more sense if the models share a common architecture.

Model compared with itself Different models compared
Model compared with itself Model comparison

📚 Bibliography

[1] Kornblith, Simon, et al. "Similarity of neural network representations revisited." 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." 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." arXiv preprint arXiv:2010.15327 (2020).

This project is also based on the following repositories:


📝 License

This project is MIT licensed.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ckatorch-1.0.1.tar.gz (144.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ckatorch-1.0.1-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file ckatorch-1.0.1.tar.gz.

File metadata

  • Download URL: ckatorch-1.0.1.tar.gz
  • Upload date:
  • Size: 144.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ckatorch-1.0.1.tar.gz
Algorithm Hash digest
SHA256 0c3ebcc9018f42d1a88e54630ef2e8b7969c96aa9bb8b29228ccfe8ec212bee6
MD5 a8382d9b36bcc47ba256bb1efa84c6ba
BLAKE2b-256 591bc0384a86480efba2f4640e14794042ead147ae84566ff2786da9f28f5236

See more details on using hashes here.

Provenance

The following attestation bundles were made for ckatorch-1.0.1.tar.gz:

Publisher: publish-to-pypi.yml on RistoAle97/centered-kernel-alignment

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ckatorch-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: ckatorch-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for ckatorch-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bbde2458dc0b888b4c62e6dd56b0d81c7f549f674802d0fde5dfe557bedf5e79
MD5 3a1a04385542f9a5263328a3198870a1
BLAKE2b-256 cf933fea6ca11a5f8c5cfd737cf562598b60c1eee83b6345cb4ea189abbb6887

See more details on using hashes here.

Provenance

The following attestation bundles were made for ckatorch-1.0.1-py3-none-any.whl:

Publisher: publish-to-pypi.yml on RistoAle97/centered-kernel-alignment

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page