LoRA keeps a pre-trained weight matrix frozen and trains only a low-rank update . Implement one plain gradient-descent step on and for a batch, with a squared-error loss.
lora_sgd_step(X, Y, W0, A, B, alpha, lr)
X: inputs, shape (n, k), one input vector per row.Y: targets, shape (n, d).W0: frozen pre-trained weight, shape (d, k).A: shape (r, k); B: shape (d, r). The rank is the number of rows of A.alpha: the LoRA scale constant; the update is multiplied by .lr: learning rate.Inputs may be NumPy arrays or nested lists. For each row the layer computes
and the loss is
Compute and the gradients and at the current and , then update both at once: , .
Return {"loss": L, "A": A_new, "B": B_new} with L a float (the loss before the step) and the new matrices as nested lists.
W0 receives no update and must not be modified. Do not modify the input A and B either; return new matrices.A and B from before the step.