Skip to content

Created create_random_permute function #115

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
Feb 2, 2023
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
2 changes: 2 additions & 0 deletions torchhd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
inverse,
negative,
cleanup,
create_random_permute,
randsel,
multirandsel,
soft_quantize,
Expand Down Expand Up @@ -71,6 +72,7 @@
"inverse",
"negative",
"cleanup",
"create_random_permute",
"randsel",
"multirandsel",
"soft_quantize",
Expand Down
47 changes: 46 additions & 1 deletion torchhd/functional.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import math
from typing import Type, Union
from typing import Type, Union, Callable
import torch
from torch import LongTensor, FloatTensor, Tensor
from collections import deque
Expand All @@ -25,6 +25,7 @@
"inverse",
"negative",
"cleanup",
"create_random_permute",
"hard_quantize",
"soft_quantize",
"hamming_similarity",
Expand Down Expand Up @@ -661,6 +662,50 @@ def permute(input: VSA_Model, *, shifts=1) -> VSA_Model:
return input.permute(shifts)



def create_random_permute(dim: int) -> Callable[[VSA_Model, int], VSA_Model]:
r"""Creates random permutation functions.

Args:
dim (int): dimension of the hypervectors

Examples::

>>> a = torchhd.random_hv(3, 10)
>>> a
tensor([[-1., 1., 1., 1., -1., -1., -1., -1., 1., -1.],
[-1., -1., -1., 1., -1., 1., -1., -1., 1., -1.],
[ 1., 1., 1., -1., -1., 1., -1., 1., 1., 1.]])
>>> p = torchhd.create_random_permute(10)
>>> p(a, 2)
tensor([[ 1., 1., -1., -1., -1., 1., -1., -1., 1., -1.],
[ 1., -1., -1., -1., 1., 1., -1., -1., -1., -1.],
[ 1., 1., 1., -1., 1., -1., -1., 1., 1., 1.]])
>>> p(a, -2)
tensor([[-1., 1., 1., 1., -1., -1., -1., -1., 1., -1.],
[-1., -1., -1., 1., -1., 1., -1., -1., 1., -1.],
[ 1., 1., 1., -1., -1., 1., -1., 1., 1., 1.]])

"""

forward = torch.randperm(dim)
backward = torch.empty_like(forward)
backward[forward] = torch.arange(dim)

def permute(input: VSA_Model, shifts: int = 1) -> VSA_Model:
y = input
if shifts > 0:
for _ in range(shifts):
y = y[..., forward]
elif shifts < 0:
for _ in range(shifts):
y = y[..., backward]
return y

return permute



def inverse(input: VSA_Model) -> VSA_Model:
r"""Inverse for the binding operation.

Expand Down