How Far Can the Judge Stretch?

Adversarial GenerationMedium+20 XP+20

How Far Can the Judge Stretch?

A discriminator that gets too sharp stops teaching. A tiny change to its input can swing its verdict wildly, and the generator is left with almost no useful signal. One widely used fix is a constraint on the discriminator itself: no layer may stretch any input by more than a factor of 1.

From Linear Algebra, a weight matrix WWW turns the unit circle into an ellipse, and its largest singular value σ\sigmaσ is how far that ellipse reaches from its centre along its longest axis (half that axis's full length): the most WWW can stretch any input of length 1. Dividing every weight by σ\sigmaσ pulls that farthest reach in to exactly 1:

Wnorm=WσW_{\text{norm}} = \frac{W}{\sigma}Wnorm​=σW​

Finding σ\sigmaσ exactly at every training step would be slow, so it is estimated with a few rounds of a cheap procedure. Start from a given vector uuu, with one entry per row of WWW. Each round does two things, in this order:

  1. v←W⊤uv \leftarrow W^{\top} uv←W⊤u, then divide vvv by its length.
  2. u←Wvu \leftarrow W vu←Wv, then divide uuu by its length.

(A vector's length is the square root of the sum of its squared entries.) After the last round, the estimate is

σ^=u⊤Wv\hat\sigma = u^{\top} W vσ^=u⊤Wv

Task: write spectral_normalize(W, u, steps).

  • W is a list of rows of any shape, not necessarily square.
  • u has one entry per row of W. It need not have length 1.
  • steps is the number of rounds, at least 1.

Return a tuple (sigma, W_norm): the estimate σ^\hat\sigmaσ^ after exactly steps rounds, and W with every entry divided by that estimate. Round sigma and every entry of W_norm to 4 decimal places, dividing by the unrounded estimate.

Real training runs a single round per step and carries u over to the next step, so the estimate is allowed to be unsettled. Report what the rounds actually produce, not the exact singular value.

Examples

W = [[2.0, 1.0], [1.0, 2.0]]
u = [1.0, 0.0]
steps = 3
returns (3.0, [[0.6667, 0.3333], [0.3333, 0.6667]])
W = [[3.0, 0.0, 1.0], [0.0, 2.0, -1.0]]
u = [0.0, 1.0]
steps = 1
returns (2.2804, [[1.3156, 0.0, 0.4385], [0.0, 0.8771, -0.4385]])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run