Skip to content
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

Reduce excess matrix manipulations in item-KNN #678

Merged
merged 5 commits into from
Mar 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/lenskit/knn/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,14 @@ def __call__(self, query: QueryInput, items: ItemList) -> ItemList:
assert isinstance(model, csr_array)
model = model[:, ti_valid_nums]
assert isinstance(model, csr_array)
# convert to CSC so we can count neighbors per target item.
model = model.tocsc()

# count neighborhood sizes
sizes = np.diff(model.indptr)
# which neighborhoods are usable? (at least min neighbors)
m_ind = csr_array(
(np.ones(model.nnz, np.int32), model.indices, model.indptr), shape=model.shape
)
sizes = m_ind.sum(0)
del m_ind
assert isinstance(sizes, np.ndarray) and len(sizes) == model.shape[1]
scorable = sizes >= self.config.min_nbrs

# fast-path neighborhoods that fit within max neighbors
Expand All @@ -268,7 +270,7 @@ def __call__(self, query: QueryInput, items: ItemList) -> ItemList:
# PyTorch, make a dense matrix (this is usually small enough to be
# usable), and use the Torch topk function.
slow_mat = model.T[~fast, :]
assert isinstance(slow_mat, csr_array)
# assert isinstance(slow_mat, csr_array)
n_slow, _ = slow_mat.shape
if n_slow:
# mask for the slow items.
Expand Down
2 changes: 1 addition & 1 deletion tests/models/test_knn_item_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ def test_ii_implicit_large(rng, ml_ratings):

for user in users:
recs = pipe.run("recommender", query=user, n=NRECS)
_log.info("user %s recs\n%s", user, recs)
_log.info("user %s recs\n%r", user, recs)
assert isinstance(recs, ItemList)
assert len(recs) == NRECS
urates = ml_ratings[ml_ratings["user_id"] == user]
Expand Down
Loading