Update src/pipeline.py
Browse files- src/pipeline.py +32 -0
src/pipeline.py
CHANGED
|
@@ -26,6 +26,36 @@ torch.backends.cudnn.benchmark = True
|
|
| 26 |
torch.backends.cuda.matmul.allow_tf32 = True
|
| 27 |
torch.cuda.set_per_process_memory_fraction(0.95)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
ckpt_id = "black-forest-labs/FLUX.1-schnell"
|
| 30 |
def empty_cache():
|
| 31 |
start = time.time()
|
|
@@ -65,6 +95,8 @@ def load_pipeline() -> Pipeline:
|
|
| 65 |
# vae.to(dtype=DTYPE)
|
| 66 |
|
| 67 |
# quantize_(vae, int8_weight_only())
|
|
|
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
|
|
|
|
| 26 |
torch.backends.cuda.matmul.allow_tf32 = True
|
| 27 |
torch.cuda.set_per_process_memory_fraction(0.95)
|
| 28 |
|
| 29 |
+
|
| 30 |
+
class BasicQuantization:
|
| 31 |
+
def __init__(self, bits=1):
|
| 32 |
+
self.bits = bits
|
| 33 |
+
self.qmin = -(2**(bits-1))
|
| 34 |
+
self.qmax = 2**(bits-1) - 1
|
| 35 |
+
|
| 36 |
+
def quantize_tensor(self, tensor):
|
| 37 |
+
scale = (tensor.max() - tensor.min()) / (self.qmax - self.qmin)
|
| 38 |
+
zero_point = self.qmin - torch.round(tensor.min() / scale)
|
| 39 |
+
qtensor = torch.round(tensor / scale + zero_point)
|
| 40 |
+
qtensor = torch.clamp(qtensor, self.qmin, self.qmax)
|
| 41 |
+
return (qtensor - zero_point) * scale, scale, zero_point
|
| 42 |
+
|
| 43 |
+
class ModelQuantization:
|
| 44 |
+
def __init__(self, model, bits=9):
|
| 45 |
+
self.model = model
|
| 46 |
+
self.quant = BasicQuantization(bits)
|
| 47 |
+
|
| 48 |
+
def quantize_model(self):
|
| 49 |
+
for name, module in self.model.named_modules():
|
| 50 |
+
if isinstance(module, torch.nn.Linear):
|
| 51 |
+
if hasattr(module, 'weightML'):
|
| 52 |
+
quantized_weight, _, _ = self.quant.quantize_tensor(module.weight)
|
| 53 |
+
module.weight = torch.nn.Parameter(quantized_weight)
|
| 54 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
| 55 |
+
quantized_bias, _, _ = self.quant.quantize_tensor(module.bias)
|
| 56 |
+
module.bias = torch.nn.Parameter(quantized_bias)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
ckpt_id = "black-forest-labs/FLUX.1-schnell"
|
| 60 |
def empty_cache():
|
| 61 |
start = time.time()
|
|
|
|
| 95 |
# vae.to(dtype=DTYPE)
|
| 96 |
|
| 97 |
# quantize_(vae, int8_weight_only())
|
| 98 |
+
quantizer = ModelQuantization(vae)
|
| 99 |
+
quantizer.quantize_model()
|
| 100 |
|
| 101 |
|
| 102 |
|