At inference an H-Net reads one byte at a time. The encoder and decoder step on every byte, while the main network steps only when the router draws a boundary. Implement one such step for a 1-stage H-Net, for a batch whose elements can make different boundary decisions.
Each sequence network has init_state(batch), returning a tensor (B, D), and step(x, state), returning (output, new_state) for inputs (B', D) and states (B', D).
init_stream_state(batch, d, enc, main, dec)
enc, main, dec (each network's init_state(batch)), last_x (zeros (B, D), the previous encoder output), zbar (zeros (B, D), the last smoothed main output) and seen (boolean False, shape (B,)).stream_step(x_t, st, enc, w_q, w_k, main, dec, res)
x_t is (B, D). w_q, w_k and res are nn.Linear. Return (y_t, st, n_main): y_t is (B, D), st the updated dict and n_main an int, the number of batch elements on which the main network ran.torch.no_grad(). Steps, in order:
last_x for the previous output. An element that has not seen a byte yet has . The boundary is .res applied to . The confidence factor from training is exactly 1 in value, so it disappears here.last_x and seen.The tests compare your stream against a full forward over the whole sequence.
torch.nn.functional.cosine_similarity.