sourcelibs/Matrix/demos/low-rank-update.xtl

1⍝!/usr/bin/env xetal 2⍝ A small frozen LoRA row space and a full learned update. 3"mx:" u̲se< "Matrix" 4"ch:" u̲se< "Check" 5frozen ← 2 4 r̲eshape 1 0 0 0 0 1 0 0 6update ← f̲loat 3 4 r̲eshape 3 0 0 0 0 2 0 0 0 0 1 0 7projected ← frozen ᵐˣp̲roject update 8best ← 2 ᵐˣt̲runcate update 9remainder ← frozen ᵐˣr̲emainder update 10⍝ This basis happens to capture the two largest singular directions. 11projected 12ᵐˣs̲ingular update 13best 14⍝ Projection and the unrestricted rank-2 optimum agree for this toy. 15"frozen-basis projection matches best rank 2" ᶜʰt̲est projected ᶜʰn̲ear best 16⍝ The discarded direction is orthogonal to the frozen row space. 17remainder 18frozen ᵐˣa̲ngles projected 19projected ᵐˣa̲ngles best 20⍝ Tilt the second frozen direction by a known 0.4 radians. 21tilted ← 2 4 r̲eshape 1.0 0.0 0.0 0.0 c̲at 0.0 c̲at (c̲os 0.4) c̲at (s̲in 0.4) c̲at 0.0 22tiltedProjection ← tilted ᵐˣp̲roject update 23tiltedProjection 24⍝ Its row space is tilted away from the globally best rank-2 update. 25tiltedProjection ᵐˣa̲ngles best 26"one shared direction and one 0.4-radian tilt" ᶜʰt̲est 0.0 0.4 ᶜʰn̲ear tiltedProjection ᵐˣa̲ngles best 27⍝ A fixed but tilted rank budget leaves a larger error than the optimum. 28error ← s̲qrt '+ r̲/ r̲avel (update − tiltedProjection) × update − tiltedProjection 29error 30"the known projection error" ᶜʰt̲est (s̲qrt 1.0 + 3.0 × (s̲in 0.4) ^ 2) ᶜʰn̲ear error