Model Utilities¶
Type Definitions¶
fusion_bench.utils.type
¶
Parameter Count and Manipulation¶
fusion_bench.utils.parameters
¶
check_parameters_all_equal(list_of_param_names)
¶
Checks if all models have the same parameters.
This function takes a list of parameter names or state dictionaries from different models. It checks if all models have the same parameters by comparing the parameter names. If any model has different parameters, it raises a ValueError with the differing parameters.
Parameters:
-
list_of_param_names
(List[Union[StateDict, List[str]]]
) –A list of parameter names or state dictionaries.
Raises:
-
ValueError
–If any model has different parameters.
Returns:
-
None
–None
Source code in fusion_bench/utils/parameters.py
count_parameters(module, non_zero_only=False)
¶
Counts the number of trainable and total parameters in a PyTorch model.
Parameters:
-
model
(Module
) –The PyTorch model for which to count parameters.
-
non_zero_only
(bool
, default:False
) –If True, only non-zero parameters are counted. If False, all parameters are counted. Defaults to False.
Returns:
-
tuple
(tuple[int, int]
) –A tuple containing the number of trainable parameters and the total number of parameters.
Examples:
```python
# Count the parameters
trainable_params, all_params = count_parameters(model)
```
Source code in fusion_bench/utils/parameters.py
get_parameter_statistics(module_or_state_dict, model_wise=False)
¶
Get statistics of the parameters in a PyTorch model or state dictionary.
Parameters:
-
module_or_state_dict
(Union[Module, StateDictType]
) –The PyTorch model for which to get parameter statistics.
Returns:
-
dict
(dict
) –A dictionary containing the mean, standard deviation, min, and max of the parameters.
Source code in fusion_bench/utils/parameters.py
get_parameter_summary(module_or_state_dict, non_zero_only=False)
¶
Get a summary of the parameters in a PyTorch model.
Source code in fusion_bench/utils/parameters.py
human_readable(num)
¶
Converts a number into a human-readable string with appropriate magnitude suffix.
Examples:
```python
print(human_readable(1500))
# Output: '1.50K'
print(human_readable(1500000))
# Output: '1.50M'
```
Parameters:
-
num
(int
) –The number to convert.
Returns:
-
str
(str
) –The human-readable string representation of the number.
Source code in fusion_bench/utils/parameters.py
print_parameters(module, is_human_readable=True, print_fn=print, non_zero_only=False)
¶
Prints the number of trainable and total parameters in a PyTorch model.
Parameters:
-
module
(Module
) –The PyTorch model for which to print parameters.
-
human_readable
(bool
) –If True, the parameter counts are converted to a human-readable format (e.g., '1.5M' instead of '1500000'). Defaults to True.
-
print_fn
(Callable
, default:print
) –Function used to print the message.
-
non_zero_only
(bool
, default:False
) –If True, only non-zero elements are counted. If False, all elements are counted. Defaults to False.
Prints
The number of trainable parameters, the total number of parameters, and the percentage of trainable parameters in the model.
Source code in fusion_bench/utils/parameters.py
state_dict_to_vector(state_dict, remove_keys=None)
¶
Convert a state dictionary to a vector.
Parameters:
-
state_dict
(Union[dict[str, Tensor], Module]
) –The state dictionary to convert.
-
remove_keys
(list
, default:None
) –List of keys to remove from the state dictionary. Defaults to [].
Returns:
-
–
torch.Tensor: The converted vector.
Source code in fusion_bench/utils/parameters.py
trainable_state_dict(module, prefix='', keep_vars=False)
¶
Returns the state dictionary of the module containing only the trainable parameters.
Parameters:
-
module
(Module
) –The neural network module.
-
prefix
(str
, default:''
) –The prefix to add to the parameter names. Defaults to "".
-
keep_vars
(bool
, default:False
) –If True, the parameters are not detached. Defaults to False.
Returns:
-
StateDictType
–Dict[str, Tensor]: A dictionary containing the names and values of the trainable parameters.
Source code in fusion_bench/utils/parameters.py
vector_to_state_dict(vector, state_dict, remove_keys=None)
¶
Convert a vector to a state dictionary.
Parameters:
-
vector
(Tensor
) –The vector to convert.
-
state_dict
(Union[dict[str, Tensor], Module]
) –The reference state dictionary to define the order of the vector.
-
remove_keys
(list
, default:None
) –List of keys to remove from the reference state dictionary. Defaults to [].
Returns:
-
dict
–The converted state dictionary.
Source code in fusion_bench/utils/parameters.py
State Dict Arithmetic¶
fusion_bench.utils.state_dict_arithmetic
¶
num_params_of_state_dict(state_dict)
¶
Returns the number of parameters in a state dict.
Parameters:
-
state_dict
(Dict[str, Tensor]
) –The state dict to count the number of parameters in.
Returns:
-
int
–The number of parameters in the state dict.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_add(a, b, strict=True, device=None, show_pbar=False)
¶
Returns the sum of two state dicts.
Parameters:
-
a
(Dict
) –The first state dict.
-
b
(Dict
) –The second state dict.
-
strict
(bool
, default:True
) –Whether to check if the keys of the two state dicts are the same.
Returns:
-
Dict
–The sum of the two state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_avg(state_dicts)
¶
Returns the average of a list of state dicts.
Parameters:
-
state_dicts
(List[Dict[str, Tensor]]
) –The list of state dicts to average.
Returns:
-
Dict
–The average of the state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_binary_mask(a, b, compare_fn='greater')
¶
Returns the binary mask of elements in a compared to elements in b using the provided comparison function.
Parameters:
-
a
(StateDictType
) –The first state dict.
-
b
(StateDictType
) –The second state dict.
-
compare_fn
(Union[Literal['greater', 'less', 'equal', 'not_equal'], Callable[[Tensor, Tensor], Tensor]]
, default:'greater'
) –A function that takes two tensors and returns a boolean tensor. Defaults to greater than comparison (x > y).
Returns:
-
StateDictType
(BoolStateDictType
) –A dictionary containing binary masks (0 or 1) based on the comparison.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_diff_abs(a, b)
¶
Returns the per-layer abs of the difference between two state dicts.
Parameters:
-
a
(StateDictType
) –The first state dict.
-
b
(StateDictType
) –The second state dict.
Returns:
-
StateDictType
–The absolute difference between the two state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_div(state_dict, scalar, show_pbar=False)
¶
Returns the division of a state dict by a scalar.
Parameters:
-
state_dict
(Dict
) –The state dict to be divided.
-
scalar
(float
) –The scalar to divide the state dict by.
Returns:
-
Dict
–The division of the state dict by the scalar.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_flatten(state_dict)
¶
Flattens a state dict.
Parameters:
-
state_dict
(Dict[str, Tensor]
) –The state dict to be flattened.
Returns:
-
Tensor
–The flattened state dict.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_hadmard_product(a, b)
¶
Returns the Hadamard product of two state dicts, i.e. element-wise product.
Parameters:
-
a
(StateDictType
) –The first state dict.
-
b
(StateDictType
) –The second state dict.
Returns:
-
StateDictType
(StateDictType
) –The Hadamard product of the two state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_interpolation(state_dicts, scalars)
¶
Interpolates between a list of state dicts using a list of scalars.
Parameters:
-
state_dicts
(List[Dict[str, Tensor]]
) –The list of state dicts to interpolate between.
-
scalars
(List[float]
) –The list of scalars to use for interpolation.
Returns:
-
Dict
–The interpolated state dict.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_mul(state_dict, scalar)
¶
Returns the product of a state dict and a scalar.
Parameters:
-
state_dict
(Dict
) –The state dict to be multiplied.
-
scalar
(float
) –The scalar to multiply the state dict with.
Returns:
-
Dict
–The product of the state dict and the scalar.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_power(state_dict, p)
¶
Returns the power of a state dict.
Parameters:
-
state_dict
(Dict[str, Tensor]
) –The state dict to be powered.
-
p
(float
) –The power to raise the state dict to.
Returns:
-
–
Dict[str, Tensor]: The powered state dict.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_sub(a, b, strict=True, device=None)
¶
Returns the difference between two state dicts a-b
.
Parameters:
-
a
(StateDictType
) –The first state dict.
-
b
(StateDictType
) –The second state dict.
-
strict
(bool
, default:True
) –Whether to check if the keys of the two state dicts are the same.
Returns:
-
StateDictType
–The difference between the two state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_sum(state_dicts)
¶
Returns the sum of a list of state dicts.
Parameters:
-
state_dicts
(List[Dict[str, Tensor]]
) –The list of state dicts to sum.
Returns:
-
Dict
–The sum of the state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dict_weighted_sum(state_dicts, weights, device=None)
¶
Returns the weighted sum of a list of state dicts.
Parameters:
-
state_dicts
(List[Dict[str, Tensor]]
) –The list of state dicts to interpolate between.
-
weights
(List[float]
) –The list of weights to use for the weighted sum.
Returns:
-
Dict
–The weighted sum of the state dicts.
Source code in fusion_bench/utils/state_dict_arithmetic.py
state_dicts_check_keys(state_dicts)
¶
Checks that the state dictionaries have the same keys.
Parameters:
-
state_dicts
(List[Dict[str, Tensor]]
) –A list of dictionaries containing the state of PyTorch models.
Raises:
-
ValueError
–If the state dictionaries have different keys.
Source code in fusion_bench/utils/state_dict_arithmetic.py
Lazy Model Loading¶
fusion_bench.utils.lazy_state_dict.LazyStateDict
¶
Dictionary-like object that lazily loads a state dict from a checkpoint path.
Source code in fusion_bench/utils/lazy_state_dict.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
|
__init__(checkpoint, meta_module_class=None, meta_module=None, cache_state_dict=False, torch_dtype=None, device='cpu', hf_revision=None, hf_cache_dir=None, hf_proxies=None)
¶
Parameters:
-
checkpoint
(str
) –Path to the checkpoint file or directory.
-
meta_module_class
(Type[Module]
, default:None
) –Class of the meta module to instantiate.
-
meta_module
(Module
, default:None
) –Pre-initialized meta module.
-
cache_state_dict
(bool
, default:False
) –Whether to cache the state dict in memory.
-
torch_dtype
(dtype
, default:None
) –The dtype to use for the tensors.
-
device
(str
, default:'cpu'
) –The device to load the tensors onto.
-
hf_revision
(str
, default:None
) –The revision of the model to download from Hugging Face Hub.
-
hf_cache_dir
(str
, default:None
) –The cache directory for Hugging Face models.
-
hf_proxies
(Dict
, default:None
) –Proxies to use for downloading from Hugging Face Hub.
Source code in fusion_bench/utils/lazy_state_dict.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
|
__setitem__(key, value)
¶
Set a tensor in the LazyStateDict. This will update the state dict cache if it is enabled.
Source code in fusion_bench/utils/lazy_state_dict.py
load_state_dict(state_dict, strict=True)
¶
Load a state dict into this LazyStateDict. This method is only for compatibility with nn.Module and it overrides the cache of LazyStateDict.
Parameters:
-
state_dict
(Dict[str, Tensor]
) –The state dict to load.
-
strict
(bool
, default:True
) –Whether to enforce that all keys in the state dict are present in this LazyStateDict.
Source code in fusion_bench/utils/lazy_state_dict.py
state_dict(keep_vars=False)
¶
Parameters:
-
keep_vars
(bool
, default:False
) –Ignored, as LazyStateDict does not support keep_vars. Just for compatibility.