MCPcopy Create free account
hub / github.com/bitsandbytes-foundation/bitsandbytes / replace_linear

Function replace_linear

bitsandbytes/utils.py:121–163  ·  view source on GitHub ↗

Replace linear modules with a new Linear module. Parameters: model (`torch.nn.Module`): Input model or `torch.nn.Module` as the function is run recursively. linear_replacement (`torch.nn.Module`): The linear module that replaces the old one. Only expe

(
    model,
    linear_replacement,
    skip_modules=("lm_head",),
    copy_weights=False,
    post_processing_function=None,
)

Source from the content-addressed store, hash-verified

119
120
121def replace_linear(
122 model,
123 linear_replacement,
124 skip_modules=("lm_head",),
125 copy_weights=False,
126 post_processing_function=None,
127):
128 """
129 Replace linear modules with a new Linear module.
130 Parameters:
131 model (`torch.nn.Module`):
132 Input model or `torch.nn.Module` as the function is run recursively.
133 linear_replacement (`torch.nn.Module`):
134 The linear module that replaces the old one. Only expects standard arguments.
135 If other arguments need to be passed, use a lambda.
136 skip_modules (`List[str]`, *optional*, defaults to `lm_head`):
137 List of modules names not to convert. Defaults to `lm_head`.
138 copy_weights (`bool`):
139 Copy the weights from the old linear module to the new one
140 post_processing_function (`str`):
141 A function name of the replacement linear class that is called
142 after processing.
143 """
144 for name, module in model.named_children():
145 if len(list(module.children())) > 0:
146 replace_linear(module, linear_replacement, skip_modules, copy_weights, post_processing_function)
147
148 if isinstance(module, torch.nn.Linear) and name not in skip_modules:
149 old_module = model._modules[name]
150 model._modules[name] = linear_replacement(
151 module.in_features,
152 module.out_features,
153 module.bias is not None,
154 )
155 if copy_weights:
156 model._modules[name].weight = old_module.weight
157 model._modules[name].bias = old_module.bias
158
159 if post_processing_function is not None:
160 func = getattr(module, post_processing_function, None)
161 if func is not None:
162 func(module)
163 return model
164
165
166def pack_dict_to_tensor(source_dict):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected