Upcycling starts an MoE from a trained dense model: the dense FFN is cut into slices along its hidden dimension and copied into the experts, and two scale factors are chosen so that, at initialization, the MoE layer computes the same function as the dense FFN. Implement the slicing, the scales, the MoE forward and the parity check.
The dense FFN is with W1 of shape (d, H), W2 of shape (H, d) and no biases. activation is "relu" () or "relu2" ().
dense_ffn(x, W1, W2, activation): the dense forward, (T, d) in and out.
upcycle(W1, W2, granularity, expansion_rate, top_k, activation, pre_softmax=False)
granularity (it divides ), slice is hidden columns of W1 and the same rows of W2. There are expansion_rate experts, and expert gets slice .pre_softmax is false, and when it is true ( = top_k)."relu" and for "relu2". Both expert matrices are multiplied by ."W1" (E, d, H/G), "W2" (E, H/G, d), "activation_scale" and "weight_scale" (floats).moe_ffn(x, W1e, W2e, W_router, top_k, activation, pre_softmax=False)
W_router is (d, E)); each token selects the top_k largest logits, ties to the lower expert index.pre_softmax is true, a selected expert's weight is its probability under the softmax over all logits (no renormalisation). Otherwise the weights are the softmax over the selected logits only.parity_gap(x, W1, W2, granularity, expansion_rate, top_k, activation, pre_softmax=False, W_router=None)
Upcycle, run the MoE with W_router (an all-zero (d, E) router if None) and return the largest absolute difference from the dense output, rounded to 6 decimals. top_k is a multiple of granularity in the tests.