The Multi-Scale Residual Tokenizer: VAR's Encoding and Reconstruction
VAR needs an image encoded as K token maps r1,…,rK from coarse to fine, where each map depends only on the maps before it. Its tokenizer quantises the feature map f at the smallest size, subtracts what that map explains, quantises the remainder at the next size, and so on. Implement the paper's encoding and reconstruction procedures on a given feature map.
Encoding of f with shape (n,n,C), a codebook Z with shape (V,C) shared by all scales, sizes s1<⋯<sK=n and maps ϕ1,…,ϕK:
for k=1,…,K:rk=Q(down(f,sk)),zk=up(lookup(Z,rk),n),f←f−ϕk(zk).
Reconstruction: f^=∑kϕk(up(lookup(Z,rk),n)).
The operations, with our concrete choices where the paper leaves them open:
- Q maps each C-vector to the index of the nearest codebook row in Euclidean distance (ties: the smaller index).
- down(x,s) averages each non-overlapping block of (n/s)×(n/s) cells. Every sk must divide n.
- up(x,n) repeats each cell of an s×s map into an (n/s)×(n/s) block.
- ϕk multiplies the vector at every cell by a C×C matrix Pk (a 1×1 convolution): ϕk(z)=zPk.
phi=None means every Pk is the identity.
var_encode(f, Z, sides, phi=None) returns (maps, residual): the list of K integer arrays of shapes (sk,sk) and the final value of f after the last subtraction, shape (n,n,C).
var_decode(maps, Z, n, phi=None, upto=None) returns f^ with shape (n,n,C), using only the first upto maps when upto is given (the matching first upto matrices of phi).
Raise ValueError in var_encode if f is not square, the sizes are not strictly increasing, the last size is not n, or a size does not divide n. Inputs must not be modified.