manbeast3b commited on
Commit
2aefef8
·
verified ·
1 Parent(s): 4d7f9fa

Update src/pipeline.py

Browse files
Files changed (1) hide show
  1. src/pipeline.py +30 -2
src/pipeline.py CHANGED
@@ -7,7 +7,33 @@ from PIL.Image import Image
7
  from pipelines.models import TextToImageRequest
8
  from torch import Generator
9
  from diffusers import DiffusionPipeline
10
- from torchao.quantization import quantize_, int8_weight_only
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  Pipeline = None
13
  MODEL_ID = "black-forest-labs/FLUX.1-schnell"
@@ -23,7 +49,9 @@ def load_pipeline() -> Pipeline:
23
  vae = AutoencoderKL.from_pretrained(
24
  MODEL_ID, subfolder="vae", torch_dtype=torch.bfloat16
25
  )
26
- quantize_(vae, int8_weight_only(), device="cuda")
 
 
27
  pipeline = DiffusionPipeline.from_pretrained(
28
  MODEL_ID,
29
  vae=vae,
 
7
  from pipelines.models import TextToImageRequest
8
  from torch import Generator
9
  from diffusers import DiffusionPipeline
10
+
11
+ class BasicQuantization:
12
+ def __init__(self, bits=1):
13
+ self.bits = bits
14
+ self.qmin = -(2**(bits-1))
15
+ self.qmax = 2**(bits-1) - 1
16
+ def quantize_tensor(self, tensor):
17
+ scale = (tensor.max() - tensor.min()) / (self.qmax - self.qmin)
18
+ zero_point = self.qmin - torch.round(tensor.min() / scale)
19
+ qtensor = torch.round(tensor / scale + zero_point) #q
20
+ qtensor = torch.clamp(qtensor, self.qmin, self.qmax)
21
+ tensor_q = (qtensor - zero_point) * scale #d
22
+ return tensor_q, scale, zero_point
23
+ class SDXLQuantization:
24
+ def __init__(self, model, bit_number=16):
25
+ self.model = model
26
+ self.quant = BasicQuantization(bit_number)
27
+ def quantize_model(self, save_name=None):
28
+ quantized_layers_state = {}
29
+ for name, module in self.model.named_modules():
30
+ if isinstance(module, (torch.nn.Linear)): # nn.Conv2d
31
+ if hasattr(module, 'weight'):
32
+ quantized_weight, _, _ = self.quant.quantize_tensor(module.weight)
33
+ module.weight = torch.nn.Parameter(quantized_weight)
34
+ if hasattr(module, 'bias') and module.bias is not None:
35
+ quantized_bias, _, _ = self.quant.quantize_tensor(module.bias)
36
+ module.bias = torch.nn.Parameter(quantized_bias)
37
 
38
  Pipeline = None
39
  MODEL_ID = "black-forest-labs/FLUX.1-schnell"
 
49
  vae = AutoencoderKL.from_pretrained(
50
  MODEL_ID, subfolder="vae", torch_dtype=torch.bfloat16
51
  )
52
+ instance = SDXLQuantization(vae, 8)
53
+ instance.quantize_model()
54
+
55
  pipeline = DiffusionPipeline.from_pretrained(
56
  MODEL_ID,
57
  vae=vae,