req-metrics 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. req_metrics-0.1.0/LICENSE +202 -0
  2. req_metrics-0.1.0/NOTICE +26 -0
  3. req_metrics-0.1.0/PKG-INFO +288 -0
  4. req_metrics-0.1.0/README.md +248 -0
  5. req_metrics-0.1.0/pyproject.toml +65 -0
  6. req_metrics-0.1.0/setup.cfg +4 -0
  7. req_metrics-0.1.0/src/req_metrics/__init__.py +180 -0
  8. req_metrics-0.1.0/src/req_metrics/_types.py +44 -0
  9. req_metrics-0.1.0/src/req_metrics/calibration.py +514 -0
  10. req_metrics-0.1.0/src/req_metrics/integrations/__init__.py +1 -0
  11. req_metrics-0.1.0/src/req_metrics/integrations/lightning.py +432 -0
  12. req_metrics-0.1.0/src/req_metrics/layouts.py +115 -0
  13. req_metrics-0.1.0/src/req_metrics/metrics/__init__.py +15 -0
  14. req_metrics-0.1.0/src/req_metrics/metrics/clustering.py +337 -0
  15. req_metrics-0.1.0/src/req_metrics/metrics/compare.py +850 -0
  16. req_metrics-0.1.0/src/req_metrics/metrics/dimension.py +305 -0
  17. req_metrics-0.1.0/src/req_metrics/metrics/distribution.py +169 -0
  18. req_metrics-0.1.0/src/req_metrics/metrics/equivariance.py +267 -0
  19. req_metrics-0.1.0/src/req_metrics/metrics/functional.py +48 -0
  20. req_metrics-0.1.0/src/req_metrics/metrics/relational.py +168 -0
  21. req_metrics-0.1.0/src/req_metrics/metrics/spectral.py +355 -0
  22. req_metrics-0.1.0/src/req_metrics/metrics/tokens.py +164 -0
  23. req_metrics-0.1.0/src/req_metrics/metrics/trajectory.py +82 -0
  24. req_metrics-0.1.0/src/req_metrics/metrics/views.py +260 -0
  25. req_metrics-0.1.0/src/req_metrics/monitor.py +1167 -0
  26. req_metrics-0.1.0/src/req_metrics/neighbors.py +70 -0
  27. req_metrics-0.1.0/src/req_metrics/pipeline.py +993 -0
  28. req_metrics-0.1.0/src/req_metrics/preprocess.py +49 -0
  29. req_metrics-0.1.0/src/req_metrics/protocols.py +83 -0
  30. req_metrics-0.1.0/src/req_metrics/py.typed +0 -0
  31. req_metrics-0.1.0/src/req_metrics/records.py +318 -0
  32. req_metrics-0.1.0/src/req_metrics/registry.py +146 -0
  33. req_metrics-0.1.0/src/req_metrics/selection.py +122 -0
  34. req_metrics-0.1.0/src/req_metrics/spectrum.py +63 -0
  35. req_metrics-0.1.0/src/req_metrics/stability.py +95 -0
  36. req_metrics-0.1.0/src/req_metrics/view_construction.py +178 -0
  37. req_metrics-0.1.0/src/req_metrics.egg-info/PKG-INFO +288 -0
  38. req_metrics-0.1.0/src/req_metrics.egg-info/SOURCES.txt +67 -0
  39. req_metrics-0.1.0/src/req_metrics.egg-info/dependency_links.txt +1 -0
  40. req_metrics-0.1.0/src/req_metrics.egg-info/requires.txt +18 -0
  41. req_metrics-0.1.0/src/req_metrics.egg-info/top_level.txt +1 -0
  42. req_metrics-0.1.0/tests/test_calibration.py +261 -0
  43. req_metrics-0.1.0/tests/test_clustering.py +60 -0
  44. req_metrics-0.1.0/tests/test_compare.py +487 -0
  45. req_metrics-0.1.0/tests/test_core.py +74 -0
  46. req_metrics-0.1.0/tests/test_dadapy_parity.py +124 -0
  47. req_metrics-0.1.0/tests/test_degenerate.py +81 -0
  48. req_metrics-0.1.0/tests/test_dense_structure.py +123 -0
  49. req_metrics-0.1.0/tests/test_devices.py +62 -0
  50. req_metrics-0.1.0/tests/test_dimension.py +74 -0
  51. req_metrics-0.1.0/tests/test_equivariance.py +75 -0
  52. req_metrics-0.1.0/tests/test_functional.py +78 -0
  53. req_metrics-0.1.0/tests/test_layouts.py +71 -0
  54. req_metrics-0.1.0/tests/test_lightning_integration.py +379 -0
  55. req_metrics-0.1.0/tests/test_monitor.py +584 -0
  56. req_metrics-0.1.0/tests/test_pipeline.py +328 -0
  57. req_metrics-0.1.0/tests/test_readme.py +164 -0
  58. req_metrics-0.1.0/tests/test_registry_sweep.py +77 -0
  59. req_metrics-0.1.0/tests/test_relational.py +123 -0
  60. req_metrics-0.1.0/tests/test_rsa.py +59 -0
  61. req_metrics-0.1.0/tests/test_schedule.py +290 -0
  62. req_metrics-0.1.0/tests/test_selection.py +64 -0
  63. req_metrics-0.1.0/tests/test_similarity.py +117 -0
  64. req_metrics-0.1.0/tests/test_spectral.py +172 -0
  65. req_metrics-0.1.0/tests/test_tokens.py +98 -0
  66. req_metrics-0.1.0/tests/test_trajectory.py +62 -0
  67. req_metrics-0.1.0/tests/test_validation.py +142 -0
  68. req_metrics-0.1.0/tests/test_version.py +15 -0
  69. req_metrics-0.1.0/tests/test_views.py +155 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Angelos-Nikolaos Kanatas
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,26 @@
1
+ req-metrics
2
+ Copyright 2026 Angelos-Nikolaos Kanatas
3
+
4
+ This product includes software derived from DADApy
5
+ (https://github.com/sissa-data-science/DADApy),
6
+ Copyright 2021-2023 The DADApy Authors, licensed under the Apache License,
7
+ Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0).
8
+
9
+ The GRIDE likelihood solver and the TwoNN fitting procedure in
10
+ src/req_metrics/metrics/dimension.py are ports of DADApy's
11
+ _utils/utils.py (_filter_mus, _neg_dloglik_did, _argmax_loglik,
12
+ _fisher_info_scaling) and id_estimation.py (_compute_id_2NN,
13
+ return_id_scaling_gride). Changes: rewritten on torch tensors, neighbor
14
+ distances taken from a shared precomputed table instead of recomputed per
15
+ call, scales exposed by their outer neighbor rank, results returned as
16
+ MetricResult.
17
+
18
+ Method references for every metric are listed in docs/references.bib; the
19
+ toolkit asks users to cite the original paper of each metric they report.
20
+
21
+ The bias-corrected participation-ratio formulas in req_metrics/metrics/spectral.py
22
+ (participation_ratio with correction="row" or "both") follow the estimators of
23
+ Chun, Canatar, Chung and Lee (ICLR 2026) and their reference implementation
24
+ https://github.com/badooki/dimensionality (MIT License, Copyright (c) 2026 Chan Woo
25
+ Chun). The quartic index sums are computed here in closed form from the Gram matrix
26
+ and column moments.
@@ -0,0 +1,288 @@
1
+ Metadata-Version: 2.4
2
+ Name: req-metrics
3
+ Version: 0.1.0
4
+ Summary: Label-free representation-quality metrics for layer-wise analysis of pretrained models and for monitoring during training
5
+ Author: Angelos-Nikolaos Kanatas
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/angeloskanatas/req-metrics
8
+ Project-URL: Documentation, https://github.com/angeloskanatas/req-metrics/tree/main/docs
9
+ Project-URL: Paper, https://arxiv.org/abs/2608.14819
10
+ Project-URL: Layer-wise results, https://angeloskanatas.github.io/music-fms-layer-eval/
11
+ Keywords: representation learning,self-supervised learning,intrinsic dimension,effective rank,layer-wise analysis,training monitoring
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: Operating System :: OS Independent
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: NOTICE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: torch>=2.1
26
+ Requires-Dist: scipy>=1.10
27
+ Provides-Extra: lightning
28
+ Requires-Dist: lightning>=2.2; extra == "lightning"
29
+ Provides-Extra: plot
30
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7; extra == "dev"
33
+ Requires-Dist: ruff>=0.16; extra == "dev"
34
+ Requires-Dist: mypy>=1.8; extra == "dev"
35
+ Requires-Dist: lightning>=2.2; extra == "dev"
36
+ Requires-Dist: tensorboard>=2.14; extra == "dev"
37
+ Requires-Dist: pandas>=2.0; extra == "dev"
38
+ Requires-Dist: scikit-learn>=1.3; extra == "dev"
39
+ Dynamic: license-file
40
+
41
+ # req-metrics
42
+
43
+ Label-free metrics of representation quality, for analyzing the layers of trained models and for
44
+ monitoring self-supervised training.
45
+
46
+ [![tests](https://github.com/angeloskanatas/req-metrics/actions/workflows/ci.yml/badge.svg)](https://github.com/angeloskanatas/req-metrics/actions/workflows/ci.yml)
47
+ [![PyPI](https://img.shields.io/pypi/v/req-metrics.svg)](https://pypi.org/project/req-metrics/)
48
+ [![license](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/angeloskanatas/req-metrics/blob/main/LICENSE)
49
+ [![python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://github.com/angeloskanatas/req-metrics/blob/main/pyproject.toml)
50
+ [![arXiv](https://img.shields.io/badge/arXiv-2608.14819-b31b1b.svg)](https://arxiv.org/abs/2608.14819)
51
+
52
+ When you use a pretrained model as a frozen feature extractor, you have to decide which layer to
53
+ read. When you train a self-supervised model, you want to know whether the run is healthy and which
54
+ checkpoint to keep. Both questions are usually answered by training labeled probes. The metrics in
55
+ this library answer them from the embeddings alone, with a few thousand unlabeled samples.
56
+
57
+ req-metrics has 39 metrics. They cover the spectrum of the embeddings (effective rank or RankMe,
58
+ α-ReQ, anisotropy), intrinsic dimension (TwoNN, GRIDE, MLE), neighborhoods and clusters, invariance
59
+ and discriminability over augmented views (LiDAR, InfoNCE, DiME), pitch-transposition equivariance
60
+ (PTE), and the similarity between two representations (CKA, SVCCA, information imbalance). Each one
61
+ is a PyTorch function on tensors, so it works with embeddings from any model.
62
+
63
+ On top of the metrics, `rq.compute` draws a seeded subsample, shares spectra and neighbor tables
64
+ between metrics, and works at three levels: one vector per sample, the tokens of each sample, or the
65
+ tokens of all samples. It returns records that keep the parameters, sample size and citation of every
66
+ value.
67
+
68
+ The library was written for the paper [What Makes a Good Layer?](https://arxiv.org/abs/2608.14819)
69
+ (ISMIR 2026) and includes more metrics than the paper uses.
70
+
71
+ ## Installation
72
+
73
+ Requires Python 3.10+ and PyTorch 2.1+.
74
+
75
+ ```bash
76
+ pip install req-metrics
77
+ pip install "req-metrics[lightning]" # with the Lightning callback
78
+ ```
79
+
80
+ The development version:
81
+
82
+ ```bash
83
+ pip install "req-metrics @ git+https://github.com/angeloskanatas/req-metrics.git"
84
+ ```
85
+
86
+ ## Quick start
87
+
88
+ ### Analyzing a trained model
89
+
90
+ Pass the embeddings of each layer as a dictionary keyed by layer index. The `model` and `pooling`
91
+ labels are stored in the record.
92
+
93
+ ```python
94
+ import req_metrics as rq
95
+
96
+ layers = {0: z0, 1: z1, 2: z2} # (N, D) per layer: one vector per sample
97
+ rec = rq.compute(layers, ["effective_rank", "intrinsic_dimension/gride", "anisotropy/spectral", "self_clustering"],
98
+ n_items=10000, seed=42, model="my-encoder", pooling="time-mean")
99
+ rec.profile("effective_rank") # [(layer, value), ...]
100
+ print(rec.to_markdown()) # layers x metrics; also to_csv, to_json, to_pandas
101
+
102
+ tokens = {0: [t0_s0, t0_s1, ...], 1: [...]} # (T_i, D) frames or patches per sample
103
+ rq.compute(tokens, ["trajectory_curvature", "effective_rank"], level="sample", n_items=2000)
104
+ rq.compute(tokens, ["effective_rank"], level="population", n_tokens=10000)
105
+
106
+ views = {0: v0, 1: v1} # (q, N, D) augmented views of the same samples
107
+ rq.compute(views, ["lidar", "infonce"], views=rq.ViewSpec(source="shared", augmentations=("PitchShift(-4..4)",), q=10))
108
+
109
+ rq.compute(shifted_layers, ["pte"], shifts=rq.ShiftSpec("waveform pitch shift", semitones=tuple(range(1, 12))))
110
+ rq.compute_pairs(layers, metrics=["information_imbalance", "cka"]) # every pair of layers
111
+ rq.compute_pairs(audio_layers, text_layers, metrics=["neighborhood_overlap"], # two models or modalities
112
+ params={"neighborhood_overlap": {"k": 10, "l2": True}}, model="audio", model_b="text")
113
+ rq.calibrate(rq.cka, a, b, groups=clip_ids) # against permutations of whole clips (Gröger et al., arXiv:2602.14486)
114
+ rq.jackknife(rq.information_imbalance, a, b) # mean and spread over five half-samples (Acevedo et al., arXiv:2505.17101)
115
+ rq.compute(tokens, ["dense_structure"], level="population") # needs the sample of every token
116
+
117
+ rq.convergence(z1, "effective_rank").to_markdown() # the value against the sample size
118
+ rq.top_layers(rec, "intrinsic_dimension/gride", k=3)
119
+ p = rq.protocols.get("kanatas2026") # the metrics and parameters of a published analysis
120
+ rq.compute(layers, p.names("sequence"), params=p.params("sequence"), n_items=p.n_items)
121
+ ```
122
+
123
+ Single metrics can also be called directly and return `MetricResult(value, extras)`, for example
124
+ `rq.effective_rank(x)`, `rq.lidar(views)` or `rq.pte(z, shifted)`. The functions in
125
+ `req_metrics.layouts` turn spectrogram-patch grids and frame sequences into points, trajectories or
126
+ token sets.
127
+
128
+ ### Monitoring training
129
+
130
+ The Lightning callback hooks the blocks of the model and keeps a fixed subset of the training set
131
+ for monitoring. At the start of training and then on a schedule, it computes every metric on every
132
+ layer and logs one scalar per layer and metric (`layer_metrics/<metric>_layer_<l>`). On Weights &
133
+ Biases it also plots the depth profile at each sweep, and with `spectra=256` the singular spectrum of
134
+ every layer.
135
+
136
+ ```python
137
+ from req_metrics.integrations.lightning import LayerMonitorCallback
138
+
139
+ trainer = pl.Trainer(callbacks=[LayerMonitorCallback(
140
+ ["effective_rank", "intrinsic_dimension/mlid", "anisotropy/spectral"], layers="backbone.blocks", pool="cls",
141
+ n_items=5000, every_n_epochs=5, sweep_steps=(100, 300, 1000, 3000, 10000),
142
+ model_attr="backbone",
143
+ view_metrics=["lidar"], augment=my_augment, q=10, # views: the objective's own positives
144
+ online=True)]) # also the training-batch buffer, as a collapse indicator
145
+ ```
146
+
147
+ Without Lightning, `LayerMonitor` does the same with a forward function and a data loader. With
148
+ `drift_metrics`, each layer is also compared with its state at the first (or the previous) sweep, as
149
+ in SVCCA (Raghu et al., NeurIPS 2017):
150
+
151
+ ```python
152
+ mon = rq.LayerMonitor(model.blocks, pool="cls", metrics=["effective_rank", "intrinsic_dimension/mlid"],
153
+ n_items=5000, drift_metrics=["cka"])
154
+ mon.sweep(model, monitor_loader, step=epoch, sinks=[rq.wandb_sink(history=mon.history), rq.csv_sink("sweeps.csv")])
155
+ mon.profiles("effective_rank") # {step: [(layer, value), ...]}
156
+ mon.profiles("cka") # drift of every layer from its first sweep
157
+ ```
158
+
159
+ A few things to keep in mind when monitoring:
160
+
161
+ - Spectral and neighbor metrics that center the embeddings miss a collapse onto a single shared
162
+ vector. Log `normalized_std` (Chen and He, 2021) or `anisotropy/cosine` next to them.
163
+ - Each record also holds `delta_first`, the change since the first sweep, and `drawdown`, the drop
164
+ below the best value so far. Absolute collapse thresholds vary by dataset (De Melo Costa et al.,
165
+ 2026), so a threshold on the drawdown is easier to set. Log it with `log_extras=("drawdown",)`.
166
+ - A hooked layer must return one row per item. If the trainer flattens the frames of a clip into
167
+ the batch, pool them back into a (B, T, D) trajectory and use `level="sample"`.
168
+ - Block outputs are taken before the final normalization layer, which can change the spectrum.
169
+ Compare the last block with the normalized output.
170
+ - Spectral metrics warn when a layer has fewer samples than dimensions, and view metrics warn when
171
+ two passes return identical views.
172
+
173
+ The per-layer values are also written to `trainer.callback_metrics`, so `EarlyStopping` and
174
+ `ModelCheckpoint` can use them:
175
+
176
+ ```python
177
+ EarlyStopping(monitor="layer_metrics/normalized_std_layer_12", mode="max", divergence_threshold=0.2 / D**0.5)
178
+ ModelCheckpoint(monitor="layer_metrics/effective_rank_layer_12", mode="max", save_top_k=1) # only where rank tracks your probe
179
+ ```
180
+
181
+ With `mode="max"`, `divergence_threshold` stops training when the value falls below it. For
182
+ `normalized_std`, 1/sqrt(D) is the value of an embedding that has not collapsed. Layer indices in the
183
+ keys are zero-padded (`layer_07` in a 12-block model). Between sweeps the last value is kept, so
184
+ match the checkpoint schedule to the sweep schedule. A resumed run restores the sweep history and the
185
+ drift reference from the checkpoint.
186
+
187
+ ### Ranking runs and layers
188
+
189
+ - `rq.rank_runs({name: records}, "effective_rank", layer=12)` orders runs or checkpoints by a
190
+ metric at one layer. This is the selection rule of RankMe and LiDAR. Use the layer you read
191
+ downstream.
192
+ - `rq.top_layers` ranks the layers of one model.
193
+ - `rq.top_local_maxima(values, t=3, window=2)` keeps the best local maxima over checkpoints or
194
+ layers, the rule Dai et al. (NeurIPS 2025) use with `dense_structure`.
195
+
196
+ The direction is an argument, because whether higher is better depends on the task and on how the
197
+ model was trained. If you have a few hundred labeled examples, check the ranking against a probe
198
+ (`docs/DESIGN.md`, section 4b). Near-equal values should be read as ties.
199
+
200
+ `pool` can be `cls`, `mean`, `max`, `last`, `tokens`, a grid readout (`gap`, `freq_concat_mean`,
201
+ `partitioned`, `freq_concat`, `freq_mean`, with `pool_kwargs={"grid": (F, T)}`) or any function
202
+ without parameters. `augment` is any function you supply. Results can go to `csv_sink`, `json_sink`,
203
+ `tensorboard_sink`, `wandb_sink` or any function of `(records, step)`. Monitoring and post-hoc
204
+ analysis produce records with the same schema. `docs/DESIGN.md` explains the choices behind the fixed
205
+ subset, the training-batch buffer, the sweep schedule and reading every layer.
206
+
207
+ ## Metrics
208
+
209
+ | Group | Metrics | Input |
210
+ |---|---|---|
211
+ | Spectral | `alpha_req`, `anisotropy/spectral`, `effective_rank`, `eigenvalue_early_enrichment`, `matrix_entropy`, `participation_ratio` | `(N, D)` points |
212
+ | Intrinsic dimension | `intrinsic_dimension/twonn`, `intrinsic_dimension/gride`, `intrinsic_dimension/mle`, `intrinsic_dimension/mlid`, `intrinsic_dimension/mst` | `(N, D)` points |
213
+ | Relational | `anisotropy/cosine`, `normalized_std`, `self_clustering`, `uniformity` | `(N, D)` points |
214
+ | Clustering | `cluster_quality`, `dense_structure` | `(N, D)` points; `dense_structure` takes the token fields of many samples at the population level |
215
+ | Trajectory | `trajectory_curvature` | `(T, D)` per sample, time-ordered |
216
+ | Views | `alignment`, `dime`, `infonce`, `lidar` | `(q, N, D)` augmented views; `dime` takes q = 2 |
217
+ | Equivariance | `pte` | embeddings of transformed copies (pitch shifts in the paper) |
218
+ | Representation pairs | `cka`, `cycle_knn`, `information_imbalance`, `neighborhood_overlap`, `procrustes`, `ridge_predictivity`, `rsa`, `svcca` | two representations of the same items: layers, checkpoints, models or modalities |
219
+ | Functional | `jacobian_effective_rank` | the model and its inputs, during monitoring |
220
+ | Token fields | `cls_patch_cosine`, `token_cosine`, `token_gram_drift`, `token_norm_outliers` | `(T, D)` token fields per sample; `token_gram_drift` also takes a reference field and is called directly |
221
+ | Distribution | `embedding_norm`, `gaussianity`, `sparsity` | `(N, D)` points |
222
+
223
+ `rq.list_metrics()`, `rq.get_metric(name)` and `rq.describe(name)` show the input, preprocessing,
224
+ citation and card of each metric. Different estimators of the same quantity share a prefix and are
225
+ named after their method, for example `intrinsic_dimension/twonn` and `intrinsic_dimension/gride`.
226
+ None of them is the default. Options such as a bias correction are arguments, and the record keeps
227
+ the value under every option.
228
+
229
+ ## Documentation
230
+
231
+ - `docs/METRICS.md`: the definition, protocol and citation of every metric.
232
+ - `docs/metrics/`: one card per metric, generated from the registry.
233
+ - `docs/VIEWS.md`: how augmented views and pitch-shifted copies are passed in.
234
+ - `docs/DESIGN.md`: the design choices, the cost of each metric and the sample sizes.
235
+ - `examples/`: from per-layer embedding files to records, and correlating layer profiles with
236
+ per-layer downstream scores.
237
+
238
+ ## Reproducing the paper
239
+
240
+ `rq.protocols.get("kanatas2026")` fixes the metric variants, parameters and sample sizes used in
241
+ the paper. The per-layer results of every model and task are on the
242
+ [project page](https://angeloskanatas.github.io/music-fms-layer-eval/), and `Records.to_atlas_json`
243
+ writes records in the same format.
244
+
245
+ ## Related tools
246
+
247
+ - [DADApy](https://github.com/sissa-data-science/DADApy) and
248
+ [scikit-dimension](https://github.com/scikit-learn-contrib/scikit-dimension): intrinsic-dimension estimators.
249
+ - [reptrix](https://github.com/BARL-SSL/reptrix): RankMe, α-ReQ and LiDAR for PyTorch models.
250
+ - [stable-pretraining](https://github.com/galilai-group/stable-pretraining): Lightning callbacks for RankMe
251
+ and LiDAR on a queue of training batches.
252
+ - [lightly](https://github.com/lightly-ai/lightly): a collapse indicator for self-supervised training.
253
+ - [information_flow](https://github.com/OFSkean/information_flow) (Skean et al., ICML 2025): layer-wise
254
+ entropy, curvature and InfoNCE for language models.
255
+ - [synesis](https://github.com/chrispla/synesis) (Plachouras et al., IJCNN 2025): probe-based
256
+ informativeness, equivariance, invariance and disentanglement.
257
+
258
+ ## Development
259
+
260
+ ```bash
261
+ git clone https://github.com/angeloskanatas/req-metrics.git && cd req-metrics
262
+ pip install -e ".[dev]"
263
+ pre-commit install
264
+ ruff check src tests examples scripts && ruff format --check src tests examples scripts
265
+ pytest
266
+ ```
267
+
268
+ `CONTRIBUTING.md` explains how to add a metric.
269
+
270
+ ## Citation
271
+
272
+ If you use req-metrics, please cite the paper below and the original paper of each metric you
273
+ report. Every metric's citation keys point into `docs/references.bib`, and `CITATION.cff` cites the
274
+ software.
275
+
276
+ ```bibtex
277
+ @inproceedings{kanatas2026goodlayer,
278
+ title = {What Makes a Good Layer? Assessing the Layer-Wise Intrinsic Properties of Music Foundation Models},
279
+ author = {Kanatas, Angelos-Nikolaos and Kong, Yuexuan and Alonso-Jim{\'e}nez, Pablo and Serra, Xavier and Bogdanov, Dmitry},
280
+ booktitle = {Proceedings of the International Society for Music Information Retrieval Conference (ISMIR)},
281
+ year = {2026},
282
+ note = {arXiv:2608.14819}
283
+ }
284
+ ```
285
+
286
+ ## License
287
+
288
+ Apache License 2.0. Code adapted from other projects is credited in `NOTICE`.