-
Notifications
You must be signed in to change notification settings - Fork 74
[feat] SID: add SidRqkmeans model (FAISS-trained residual K-Means) #539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,914
−9
Merged
Changes from all commits
Commits
Show all changes
48 commits
Select commit
Hold shift + click to select a range
995b23e
[feat] SID: add SidRqkmeans model (FAISS-trained residual K-Means)
WhiteSwan1 c7f3a09
[review] SID: drop forced tail-checkpoint after on_train_end
WhiteSwan1 61ec842
[review] SID: address code-review findings on PR #539
WhiteSwan1 753f3fe
[review] SID: default normalize_residuals to False
WhiteSwan1 52c7452
[review] SID: encapsulation, comment, and import cleanups
WhiteSwan1 fbd973f
[review] SID: move FAISS fit-sample sizing into the quantizer
WhiteSwan1 893a627
[review] SID: log rank0 FAISS-fit failure with traceback
WhiteSwan1 3734fc2
[review] SID: clarify the reservoir ceil-div comment
WhiteSwan1 795c676
[review] SID: fix FAISS gpu kwarg + close test gaps from PR review
WhiteSwan1 2bb5abc
[review] SID: default FAISS fit to CPU + DDP fit-failure test
WhiteSwan1 33acbe6
[review] SID: log the FAISS fit device (CPU/GPU)
WhiteSwan1 25a1e30
Merge remote-tracking branch 'upstream/master' into sid-2-rqkmeans
WhiteSwan1 23c552c
[chore] bump version to 1.2.18
WhiteSwan1 3261c2c
[review] SID: address 23c552c review (test timeout, N>=K assert, cap …
WhiteSwan1 e6e4d00
Merge upstream/master into sid-2-rqkmeans; bump version to 1.2.19
WhiteSwan1 39017ab
[review] checkpoint_util: force only overrides the dedupe
WhiteSwan1 5afbd5e
[review] checkpoint maybe_save: clarify final vs force docstrings
WhiteSwan1 415b8a3
[refactor] SidRqkmeans: single-process only; raise under DDP
WhiteSwan1 b27eb7b
[refactor] SidRqkmeans: move DDP guard to __init__ (fail fast)
WhiteSwan1 6f7ae1d
[simplify] SidRqkmeans: drop dead max(1,...) cap clamp; fold test _bu…
WhiteSwan1 5827d5b
[style] ruff-format the __init__ DDP guard (collapse to one line)
WhiteSwan1 4e2e878
[refactor] SidRqkmeans: CPU-only — raise on visible CUDA, drop device…
WhiteSwan1 4773e2a
[simplify] train_offline: assert host input; single-copy float32 own
WhiteSwan1 df83d07
[refactor] KMeansLayer.predict: use torch.cdist; drop _squared_euclid…
WhiteSwan1 d037db7
[refactor] SidRqkmeans: drop input_embedding from predictions
WhiteSwan1 88856f3
[simplify] trim SID docstrings (predict provenance; stale SidRqvae xref)
WhiteSwan1 2fa312b
[refactor] extract reservoir sampling into ReservoirSampler (kmeans.py)
WhiteSwan1 e296c8d
[refactor] ReservoirSampler: log capacity + dim on construction
WhiteSwan1 892a8d2
[fix] SID code-review: fail-fast cap, skip pre-fit eval, dedup MSE, d…
WhiteSwan1 b14304a
[simplify] SID: raise (not assert) for cap guard; name normalize_resi…
WhiteSwan1 eb39b5e
[style] SID: trim verbose comments
WhiteSwan1 8bf50aa
[refactor] SID: move init_metric/update_metric to BaseSidModel + Rela…
WhiteSwan1 e8a3609
[test] SID: add sid_integration_test (train -> fit -> checkpoint -> e…
WhiteSwan1 3dfbde0
[test] checkpoint: verify force re-save overwrites the same step
WhiteSwan1 d67ccd1
[review] split quantizer tests by module; clarify copy=True
WhiteSwan1 6a736c5
[refactor] drop CheckpointManager force param; SID uses no periodic c…
WhiteSwan1 5bc89d4
[refactor] typed FaissKmeansConfig proto; drop Struct + _coerce_proto…
WhiteSwan1 feeb4af
[refactor] add QuantizeLayer base; KMeansLayer -> KMeansQuantizeLayer
WhiteSwan1 a5d43b2
[refactor] unify reconstruction key to x_hat; drop _reconstruction hook
WhiteSwan1 c4c361a
[style] SID: trim redundant comments
WhiteSwan1 db7f2be
[refactor] QuantizeLayer: make lookup concrete in the base
WhiteSwan1 ed12cff
[refactor] QuantizeLayer: own n_clusters/n_features in the base
WhiteSwan1 d2697eb
[refactor] SID: extract QuantizeLayer ABC; rename kmeans -> kmeans_qu…
WhiteSwan1 097e9eb
[docs] checkpoint_util: tighten maybe_save `final` param docstring
WhiteSwan1 a9a889c
[fix] SID: review fixes + fail-fast validation; fix integration test …
WhiteSwan1 3b41df9
[review] SID: doc fixes, negative tests, stronger integration assertions
WhiteSwan1 5f5af01
[review] SID: drop _extract_feature width guard (embedding width is n…
WhiteSwan1 43e84ca
[fix] SID integration test: skip on CUDA, run on CPU CI
WhiteSwan1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # Copyright (c) 2026, Alibaba Group; | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import torch | ||
| from torchmetrics import Metric | ||
|
|
||
|
|
||
| class RelativeL1(Metric): | ||
| """Mean symmetric relative-L1 error ``|t - p| / (max(|t|, |p|) + eps)``. | ||
|
|
||
| A bounded reconstruction-error metric (0 = exact, → 1 = unrelated). It is a | ||
| verbatim port of OpenOneRec's residual-K-Means ``calc_loss`` and is | ||
| deliberately **not** ``torchmetrics.MeanAbsolutePercentageError``, which uses | ||
| the asymmetric ``|t - p| / |t|`` denominator. Aggregation is element-wise | ||
| (count-weighted), so the reported value is the mean over all elements seen. | ||
| """ | ||
|
|
||
| higher_is_better = False | ||
| is_differentiable = True | ||
|
|
||
| def __init__(self, epsilon: float = 1e-4, **kwargs) -> None: | ||
| super().__init__(**kwargs) | ||
| self.epsilon = epsilon | ||
| # float64 sum / long count: float32 loses integer precision past 2**24 | ||
| # (~32K rows of a 512-dim embedding) under element-wise aggregation. | ||
| self.add_state( | ||
| "sum_rel", | ||
| default=torch.tensor(0.0, dtype=torch.float64), | ||
| dist_reduce_fx="sum", | ||
| ) | ||
| self.add_state( | ||
| "count", default=torch.tensor(0, dtype=torch.long), dist_reduce_fx="sum" | ||
| ) | ||
|
|
||
| def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: | ||
| """Accumulate the relative-L1 error between ``preds`` and ``target``. | ||
|
|
||
| Args: | ||
| preds (Tensor): reconstruction, shape (B, D). | ||
| target (Tensor): ground-truth embedding, shape (B, D). | ||
| """ | ||
| rel = torch.abs(target - preds) / ( | ||
| torch.maximum(torch.abs(target), torch.abs(preds)) + self.epsilon | ||
| ) | ||
| self.sum_rel += rel.sum().double() | ||
| self.count += rel.numel() | ||
|
|
||
| def compute(self) -> torch.Tensor: | ||
| """Mean relative-L1 over all elements (NaN before any update).""" | ||
| return self.sum_rel / self.count |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # Copyright (c) 2026, Alibaba Group; | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from tzrec.metrics.relative_l1 import RelativeL1 | ||
|
|
||
|
|
||
| class RelativeL1Test(unittest.TestCase): | ||
| def test_zero_on_identity(self) -> None: | ||
| metric = RelativeL1() | ||
| x = torch.randn(8, 4) | ||
| metric.update(x, x.clone()) | ||
| self.assertAlmostEqual(metric.compute().item(), 0.0, places=6) | ||
|
|
||
| def test_matches_formula(self) -> None: | ||
| metric = RelativeL1(epsilon=1e-4) | ||
| p = torch.tensor([[1.0, 0.0]]) | ||
| t = torch.tensor([[0.0, 2.0]]) | ||
| # |t-p|/(max(|t|,|p|)+eps): [1/(1+eps), 2/(2+eps)], mean of the two. | ||
| expected = (1.0 / (1.0 + 1e-4) + 2.0 / (2.0 + 1e-4)) / 2 | ||
| metric.update(p, t) | ||
| self.assertAlmostEqual(metric.compute().item(), expected, places=5) | ||
|
|
||
| def test_count_weighted_across_updates(self) -> None: | ||
| """Aggregation is element-wise, not a mean of per-batch means.""" | ||
| metric = RelativeL1() | ||
| metric.update(torch.zeros(1, 4), torch.ones(1, 4)) # 4 elems, rel ~1 | ||
| metric.update(torch.ones(3, 4), torch.ones(3, 4)) # 12 elems, rel 0 | ||
| # Element-weighted: 4 nonzero over 16 elems -> ~0.25, NOT (1+0)/2 = 0.5. | ||
| per = 1.0 / (1.0 + 1e-4) # rel of a 0-vs-1 element (with epsilon) | ||
| self.assertAlmostEqual(metric.compute().item(), 4 * per / 16, places=6) | ||
|
|
||
| def test_nan_before_update(self) -> None: | ||
| self.assertTrue(torch.isnan(RelativeL1().compute())) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.