Skip to content

Commit a3a741f

Browse files
committed
[quantization] bnb dequantize: undo Conv1D transpose, cast to the dense dtype
1 parent de7a245 commit a3a741f

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

‎src/transformers/integrations/bitsandbytes.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,23 @@ def convert(
9090
return {key_weight: new_value}
9191

9292

93+
def _to_dense_layout(weights, key, model, full_layer_name):
94+
"""Undo the `Conv1D` transpose done at quantization time and cast to the dtype of the dense param."""
95+
if model is None:
96+
return weights
97+
name = next(iter(expand_target_names({key: None}, full_layer_name)))
98+
try:
99+
module, param_name = get_module_from_name(model, name)
100+
except AttributeError:
101+
return weights # e.g. a source of a fused param: the converter ops that follow handle it
102+
param = getattr(module, param_name, None)
103+
transpose = isinstance(module, Conv1D)
104+
return [
105+
(weight.T if transpose else weight).to(param.dtype if param is not None else weight.dtype)
106+
for weight in weights
107+
]
108+
109+
93110
class Bnb4bitDequantize(ConversionOps):
94111
"""Dense weights from the serialized `weight` and its quant state, saved under `weight.*`."""
95112

@@ -114,6 +131,7 @@ def convert(self, input_dict, model=None, full_layer_name=None, **kwargs) -> dic
114131
)
115132
for i, weight in enumerate(weights)
116133
]
134+
weights = _to_dense_layout(weights, key, model, full_layer_name)
117135
output[key] = weights
118136
return output
119137

@@ -134,6 +152,7 @@ def convert(self, input_dict, model=None, full_layer_name=None, **kwargs) -> dic
134152
if scales is not None:
135153
scales = scales if isinstance(scales, list) else [scales]
136154
weights = [weight.float() * scale.view(-1, 1) / 127 for weight, scale in zip(weights, scales)]
155+
weights = _to_dense_layout(weights, key, model, full_layer_name)
137156
output[key] = weights
138157
return output
139158

0 commit comments

Comments
 (0)