Skip to content

Add cleanup function for associative memory lookup #30

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
merged 2 commits into from
May 13, 2022
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
3 changes: 2 additions & 1 deletion docs/_templates/class.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@

.. autoclass:: {{ name }}
:members:
:special-members:
:special-members:
:exclude-members: __weakref__
1 change: 1 addition & 0 deletions docs/functional.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Operations
bind
bundle
permute
cleanup
soft_quantize
hard_quantize

Expand Down
25 changes: 25 additions & 0 deletions torchhd/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"bind",
"bundle",
"permute",
"cleanup",
"hard_quantize",
"soft_quantize",
"hamming_similarity",
Expand Down Expand Up @@ -543,3 +544,27 @@ def index_to_value(

"""
return map_range(input.float(), 0, index_length - 1, out_min, out_max)


def cleanup(input: Tensor, memory: Tensor, threshold=0.0) -> Tensor:
"""Returns a copy of the most similar hypervector in memory.

If the cosine similarity is less than threshold, raises a KeyError.

Args:
input (Tensor): The hypervector to cleanup
memory (Tensor): The `n` hypervectors in memory of shape (n, d)

Returns:
Tensor: output tensor
"""
scores = cosine_similarity(input, memory)
value, index = torch.max(scores, dim=-1)

if value.item() < threshold:
raise KeyError(
"Hypervector with the highest similarity is less similar than the provided threshold"
)

# Copying prevents manipulating the memory tensor
return torch.clone(memory[index])