"Transformers are Inherently Succinct" studies the unique-hard attention transformer (UHAT): every position attends to exactly one other position, the one with the highest score. Implement the two layer types and the language recogniser. All numbers in this problem are integers, so ties are exact.
An affine map is a pair (W, b) and maps a vector x to W @ x + b.
uha_layer(V, A, B, C, mask, tie)
V is a list of vectors of width . A and B are affine maps from width to width . C is an affine map from width to width . For positions and the score is the dot product
mask selects the positions that position may attend to:
"none": every position, including itself."future" (strict future masking): only ."past" (strict past masking): only .Among the allowed positions with the highest score, tie picks the leftmost ("left") or the rightmost ("right"). The attention vector is the input vector at the picked position. If no position is allowed, is the zero vector. The output at position is applied to the concatenation of and .
Return (out, picks): out is a list of lists of ints, and picks holds the picked position for each (0-indexed) or None.
relu_layer(V, r) returns the vectors with applied to coordinate r (0-indexed) only.
uhat_accepts(word, emb, layers, t)
emb maps each symbol to its embedding vector. layers is a list whose entries are ("uha", A, B, C, mask, tie) or ("relu", r), applied in order. With the final vector at the last position, return True when . The empty word is never accepted.
mask, tie or layer name raises ValueError.