Skip to content

Commit 9c471ca

Browse files
committed
Fix CGR bundle
Ensure both inputs are in the same shape.
1 parent 24c2676 commit 9c471ca

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

torchhd/tensors/cgr.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,30 @@ def bundle(self, other: "CGRTensor") -> "CGRTensor":
6363
"""
6464
assert self.block_size == other.block_size
6565

66-
t = torch.stack((self, other), dim=-2)
67-
val, _ = torch.mode(t, dim=-2)
66+
# Ensure hypervectors are in the same shape, i.e., [..., 1, DIM]
67+
t1 = self
68+
if len(t1.shape) == 1:
69+
t1 = t1.unsqueeze(0)
70+
t2 = other
71+
if len(t2.shape) == 1:
72+
t2 = t2.unsqueeze(0)
73+
74+
t = torch.stack((t1, t2), dim=-2)
75+
val = t.multibundle()
76+
77+
# Convert shape back to [DIM] if inputs are plain hypervectors
78+
need_squeeze = len(self.shape) == 1 and len(other.shape) == 1
79+
if need_squeeze:
80+
return val.squeeze(0)
81+
6882
return val
6983

7084
def multibundle(self) -> "CGRTensor":
7185
"""Bundle multiple hypervectors"""
7286

87+
# The use of torch.mode() makes untying deterministic as it always
88+
# returns the lowest index among the ties. For example, if there is an
89+
# equal number amount of 0s and 1s in a bundle, 0 is returned.
7390
val, _ = torch.mode(self, dim=-2)
7491
return val
7592

0 commit comments

Comments
 (0)