Upload qandc/variance_compensation.py
Browse files
qandc/variance_compensation.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Variance Compensation (VC) for Exposure Bias Correction.
|
| 3 |
+
Second key contribution of Q&C paper (Section 3.2, Eq 9-12).
|
| 4 |
+
Corrects variance shifts when quantization + cache are combined.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
class VarianceCompensation:
|
| 11 |
+
"""Full VC with analytical K_t from Eq 12."""
|
| 12 |
+
def __init__(self, n_timesteps, n_channels, device="cuda"):
|
| 13 |
+
self.n_timesteps = n_timesteps
|
| 14 |
+
self.n_channels = n_channels
|
| 15 |
+
self.device = device
|
| 16 |
+
self.K = torch.ones(n_timesteps, n_channels, device=device)
|
| 17 |
+
self._numerator = torch.zeros(n_timesteps, n_channels, device=device)
|
| 18 |
+
self._denominator = torch.zeros(n_timesteps, n_channels, device=device)
|
| 19 |
+
self._count = torch.zeros(n_timesteps, device=device)
|
| 20 |
+
self._calibrated = False
|
| 21 |
+
|
| 22 |
+
def accumulate(self, t_idx, x_fp, x_qc):
|
| 23 |
+
reduce_dims = (0, 2, 3) if x_fp.dim() == 4 else (0,)
|
| 24 |
+
mu = x_qc.mean(dim=reduce_dims)
|
| 25 |
+
x_fp_c = x_fp - mu.view(1, -1, 1, 1) if x_fp.dim() == 4 else x_fp - mu
|
| 26 |
+
x_qc_c = x_qc - mu.view(1, -1, 1, 1) if x_qc.dim() == 4 else x_qc - mu
|
| 27 |
+
term1 = (x_fp_c * x_qc_c).mean(dim=reduce_dims)
|
| 28 |
+
x_fp_safe = x_fp.clone(); x_fp_safe[x_fp_safe.abs() < 1e-6] = 1e-6
|
| 29 |
+
term2 = (x_qc_c / x_fp_safe).mean(dim=reduce_dims)
|
| 30 |
+
dterm1 = (x_qc_c ** 2).mean(dim=reduce_dims)
|
| 31 |
+
dterm2 = ((x_qc_c ** 2) / (x_fp_safe ** 2)).mean(dim=reduce_dims)
|
| 32 |
+
self._numerator[t_idx] += (term1 + term2).to(self.device)
|
| 33 |
+
self._denominator[t_idx] += (dterm1 + dterm2).to(self.device)
|
| 34 |
+
self._count[t_idx] += 1
|
| 35 |
+
|
| 36 |
+
def calibrate(self):
|
| 37 |
+
for t in range(self.n_timesteps):
|
| 38 |
+
if self._count[t] > 0:
|
| 39 |
+
self.K[t] = torch.clamp(self._numerator[t] / torch.clamp(self._denominator[t], min=1e-8), 0.5, 2.0)
|
| 40 |
+
self._calibrated = True
|
| 41 |
+
print(f"VC calibrated: K range [{self.K.min():.4f}, {self.K.max():.4f}]")
|
| 42 |
+
|
| 43 |
+
def apply(self, x, t_idx):
|
| 44 |
+
if not self._calibrated: return x
|
| 45 |
+
K_t = self.K[t_idx]
|
| 46 |
+
if x.dim() == 4:
|
| 47 |
+
mu = x.mean(dim=(0, 2, 3), keepdim=True)
|
| 48 |
+
return mu + K_t.view(1, -1, 1, 1).to(x.device) * (x - mu)
|
| 49 |
+
else:
|
| 50 |
+
mu = x.mean(dim=0, keepdim=True)
|
| 51 |
+
return mu + K_t.view(1, -1).to(x.device) * (x - mu)
|
| 52 |
+
|
| 53 |
+
class SimpleVarianceCompensation:
|
| 54 |
+
"""Simplified VC using variance ratio estimation. Applies only in later denoising stages."""
|
| 55 |
+
def __init__(self, n_timesteps, n_channels, apply_after_fraction=0.5, device="cuda"):
|
| 56 |
+
self.n_timesteps = n_timesteps
|
| 57 |
+
self.n_channels = n_channels
|
| 58 |
+
self.apply_after_fraction = apply_after_fraction
|
| 59 |
+
self.device = device
|
| 60 |
+
self.var_ratio = torch.ones(n_timesteps, n_channels, device=device)
|
| 61 |
+
self._fp_var_sum = torch.zeros(n_timesteps, n_channels, device=device)
|
| 62 |
+
self._qc_var_sum = torch.zeros(n_timesteps, n_channels, device=device)
|
| 63 |
+
self._count = torch.zeros(n_timesteps, device=device)
|
| 64 |
+
self._calibrated = False
|
| 65 |
+
|
| 66 |
+
def accumulate(self, t_idx, x_fp, x_qc):
|
| 67 |
+
reduce_dims = (0, 2, 3) if x_fp.dim() == 4 else (0,)
|
| 68 |
+
self._fp_var_sum[t_idx] += x_fp.var(dim=reduce_dims).to(self.device)
|
| 69 |
+
self._qc_var_sum[t_idx] += x_qc.var(dim=reduce_dims).to(self.device)
|
| 70 |
+
self._count[t_idx] += 1
|
| 71 |
+
|
| 72 |
+
def calibrate(self):
|
| 73 |
+
for t in range(self.n_timesteps):
|
| 74 |
+
if self._count[t] > 0:
|
| 75 |
+
fp_var = self._fp_var_sum[t] / self._count[t]
|
| 76 |
+
qc_var = torch.clamp(self._qc_var_sum[t] / self._count[t], min=1e-8)
|
| 77 |
+
self.var_ratio[t] = torch.clamp(torch.sqrt(fp_var / qc_var), 0.5, 2.0)
|
| 78 |
+
self._calibrated = True
|
| 79 |
+
print(f"Simple VC calibrated: ratio [{self.var_ratio.min():.4f}, {self.var_ratio.max():.4f}]")
|
| 80 |
+
|
| 81 |
+
def apply(self, x, t_idx):
|
| 82 |
+
if not self._calibrated: return x
|
| 83 |
+
if t_idx < int(self.n_timesteps * self.apply_after_fraction): return x
|
| 84 |
+
ratio = self.var_ratio[t_idx]
|
| 85 |
+
if x.dim() == 4:
|
| 86 |
+
mu = x.mean(dim=(0, 2, 3), keepdim=True)
|
| 87 |
+
return mu + ratio.view(1, -1, 1, 1).to(x.device) * (x - mu)
|
| 88 |
+
else:
|
| 89 |
+
mu = x.mean(dim=0, keepdim=True)
|
| 90 |
+
return mu + ratio.view(1, -1).to(x.device) * (x - mu)
|