The routing module of an H-Net decides, for every position, whether it starts a new chunk. It compares each encoder output with the one before it:
Implement it as a PyTorch module.
class RoutingModule(nn.Module)
__init__(self, d_model): creates two bias-free linear layers self.W_q and self.W_k from d_model to d_model. Both weight matrices start as the identity, as in the released code, so the first boundaries come from plain adjacent cosine similarity.forward(self, x, starts=None):
x is a float tensor (B, L, D) of encoder outputs, with L >= 1.starts is an optional bool tensor (B, L). Where it is True, a new document begins, so p at that position must be 1.0 whatever the vectors say.(p, b): p is a float tensor (B, L) in [0, 1] and b a bool tensor (B, L).p[:, 0] is always exactly 1.0.t with the key at t-1, in that order. Clamp p into [0, 1], since rounding can push the cosine just outside [-1, 1].b must not carry gradient (it is a bool tensor), while p must carry gradient to W_q, W_k and x.