MCPcopy Create free account
hub / github.com/deepspeedai/DeepSpeed / FP_Quantize

Class FP_Quantize

deepspeed/ops/fp_quantizer/quantize.py:43–178  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

41
42
43class FP_Quantize(Quantizer):
44
45 def __init__(self, quantization_config) -> None:
46 global fp_quant_module
47 super().__init__(group_size=quantization_config.group_size)
48 if fp_quant_module is None:
49 fp_quant_module = FPQuantizerBuilder().load()
50 self.cuda_impl = getattr(fp_quant_module, "CUDA_IMPL", True)
51 self.q_config = quantization_config
52
53 self.orig_dtype = None
54 self.num_groups = None
55 self.input_q = None
56 self.scale = None
57
58 def _validate_shape(self, input):
59 if self.group_size <= 0:
60 raise ValueError(f"quantization group_size must be positive, got {self.group_size}")
61 if self.cuda_impl and self.group_size % 8 != 0:
62 raise ValueError(f"quantization group_size must be divisible by 8, got {self.group_size}")
63 if input.numel() % self.group_size != 0:
64 raise ValueError(
65 f"quantized tensor with {input.numel()} elements must be divisible by group_size {self.group_size}")
66
67 def quantize(self,
68 input,
69 q_bits=8,
70 q_mantisa_bits=3,
71 stochastic_mode=False,
72 return_meta_tensor=False) -> torch.Tensor:
73 assert input.dtype == torch.bfloat16, "only support bf16 for now"
74 if return_meta_tensor:
75 assert q_bits == 8, "meta tensor is only supported with q_bit=8"
76
77 self._validate_shape(input)
78 self.orig_dtype = input.dtype
79 self.orig_shape = input.shape
80
81 if q_bits == 8:
82 pass
83 elif q_bits == 12:
84 q_mantisa_bits = 7
85 elif q_bits == 6:
86 q_mantisa_bits = 2
87 elif q_bits == 4:
88 q_mantisa_bits = 1
89 else:
90 assert (0), \
91 f"Missing {q_bits}-quantization, please add the template arguments for the kernel to support this precision!"
92 self.num_groups = input.numel() // self.group_size
93 self.input_q = torch.ones(self.num_groups,
94 int(self.group_size * q_bits) // 8 + 4,
95 dtype=torch.uint8,
96 device=input.device)
97 out = fp_quant_module.quantize(self.input_q, input, self.group_size, stochastic_mode, q_bits, q_mantisa_bits)
98 if return_meta_tensor:
99 data, self.scale = out.split(self.group_size, dim=-1)
100 data = data.contiguous().reshape(input.shape)

Callers 6

_quantizerFunction · 0.90
test_fp_quant_metaFunction · 0.90
test_fp_quant_selectiveFunction · 0.90
test_fp_quantFunction · 0.90
__new__Method · 0.90

Calls

no outgoing calls

Tested by 5

_quantizerFunction · 0.72
test_fp_quant_metaFunction · 0.72
test_fp_quant_selectiveFunction · 0.72
test_fp_quantFunction · 0.72