Appendix F of the H-Net paper converts a pretrained token-level model into a byte-level one. The main network is frozen, and the new encoder and router learn to pass it what it expects. Besides next-byte prediction there are two auxiliary losses: a binary cross-entropy that asks the router to fire at the first byte of each token, and an L2 loss that matches passed hidden states to token embeddings. Implement the targets and the losses. A token is a string, one character per byte.
boundary_labels(tokens)
1.0 at the first byte of each token, 0.0 elsewhere.embedding_match_index(tokens)
-1.distillation_loss(ar_loss, p, kept_idx, kept_hidden, tokens, token_emb, w_boundary=1.0, w_embed=0.02)
ar_loss is a scalar tensor, the next-byte loss. p is (L,), the router's boundary probabilities. kept_idx is a long tensor (K,) of the byte positions passed to the main network, and kept_hidden is (K, E), their hidden states after the adapter. token_emb is (T, E), the frozen embeddings of the tokens in order.boundary is torch.nn.functional.binary_cross_entropy(p, boundary_labels(tokens)).embed is the mean squared error between kept_hidden and the matching embeddings, over kept positions whose match index is not -1, using mse_loss with its default mean. It is 0.0 if there are none. No gradient may reach token_emb.total (), boundary and embed.boundary_accuracy(b, tokens)
b is a boolean tensor over the bytes (predicted boundaries). Return, as a float, the fraction of bytes where b agrees with boundary_labels(tokens).torch.repeat_interleave turns token lengths into a per-byte token index.