Latent Encode-Decode Round Trip
Problem Statement
Verify the scaling is applied consistently: encoding to a latent multiplies by s, decoding divides by s. Run the round trip and report the max absolute reconstruction error against the original.
Background
Stable Diffusion scales latents on encode (z = s * z_raw) and unscales on decode (z_raw = z / s). If both use the same s, the round trip is exact up to floating point. This problem models the scale-only part of the round trip (ignoring the VAE), so the reconstruction should match the input to numerical precision.
Your Task
Implement:
def roundtrip_error(z_raw, encode_scale, decode_scale):
- Encode: z = encode_scale * z_raw. Decode: recon = z / decode_scale.
Return the maximum absolute error max|recon - z_raw| rounded to 6 decimals.
Input Format
- z_raw: list of floats.
- encode_scale, decode_scale (float, nonzero).
Output Format
- A float rounded to 6 decimals.
Sample
print(roundtrip_error([1.0, 2.0, 3.0], 0.18215, 0.18215))
Output:
0.0
Example
print(roundtrip_error([1.0, 2.0, 3.0], 0.18215, 0.18215))
0.0
- Encoding Step: Multiply each element of the input vector by the
encode_scale() to produce the latent representation . This yields . - Decoding Step: Divide each element of the latent vector by the
decode_scale() to reconstruct the original values. Since the scales are identical, the division cancels the multiplication: . - Error Calculation: Compute the absolute difference between the reconstructed vector and the original input: .
- Max Error Extraction: Identify the maximum value in the error vector, which is .
- The final output is 0.0
Constraints
1 <= len(z_raw) <= 100000, scales nonzero.recon = (encode_scale * z_raw) / decode_scale.- Return
max|recon - z_raw|rounded to 6 decimals.