Browse and solve 1,200+ machine learning coding challenges on Deep-ML. Filter by difficulty (beginner, intermediate, advanced) and category (linear algebra, machine learning, deep learning, NLP, computer vision). Write Python solutions in the browser and get instant feedback against test cases.
Deep-ML | Performer Attention with Positive Random FeaturesPerformer Attention with Positive Random Features
With D = 4, the inputs are scaled by 4^(-1/4) = 0.7071. For the first row x = (1, 0, 0, 0): x' = (0.7071, 0, 0, 0), |x'|^2 / 2 = 0.25, and the two features are exp(0.7071 - 0.25) / sqrt(2) = 1.1169 and exp(-0.25) / sqrt(2) = 0.5507.
Softmax attention costs O(N2) because it forms the N×N matrix Aij=exp(qi⊤kj/D). The Performer writes A as an expectation of a product of random features, Aij=E[ϕ(qi)⊤ϕ(kj)], and then uses associativity to get linear cost:
attention(Q,K,V)=diag(Q′((K′)⊤1N))−1Q′((K′)⊤V)
Use the positive random features of FAVOR+. With a matrix W∈RM×D whose rows are the random directions w1,…,wM, and x′=x/D1/4,
ϕ(x)=M1[exp(wm⊤x′−21∥x′∥2)]m=1M
Implement:
performer_features(X, W): apply ϕ to every row of X (shape (N, D)), returning (N, M).
performer_attention(Q, K, V, W): returns (approx, exact), both (N, d_v). approx must be computed in the linear order above, never forming an N×N matrix; exact is softmax(QK⊤/D)V with a row-wise softmax.