def get_parameters(model, predicate):
for module in model.modules():
for param_name, param in module.named_parameters():
if predicate(module, param_name):
yield param
def get_parameters_conv(model, name):
return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d) and m.groups == 1 and p == name)
def get_parameters_conv_depthwise(model, name):
return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d)
and m.groups == m.in_channels
and m.in_channels == m.out_channels
and p == name)
def get_parameters_bn(model, name):
return get_parameters(model, lambda m, p: isinstance(m, nn.BatchNorm2d) and p == name)
The provided code defines three utility functions (get_parameters_conv, get_parameters_conv_depthwise, and get_parameters_bn) that are used to filter and retrieve specific parameters from a PyTorch model based on certain conditions. These functions rely on the generic get_parameters function, which iterates over all modules and their parameters in a model.
get_parametersdef get_parameters(model, predicate):
for module in model.modules():
for param_name, param in module.named_parameters():
if predicate(module, param_name):
yield param
predicate).model: The PyTorch model to search through.predicate: A function that takes a module and a parameter name as input and returns True if the parameter should be selected.model.modules().module.named_parameters().predicate function to determine if the parameter should be selected.get_parameters_convdef get_parameters_conv(model, name):
return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d) and m.groups == 1 and p == name)
nn.Conv2d) in the model.model: The PyTorch model to search through.name: The name of the parameter to filter (e.g., "weight" or "bias").get_parameters with a predicate that checks:
nn.Conv2d.groups == 1).name.get_parameters_conv_depthwisedef get_parameters_conv_depthwise(model, name):
return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d)
and m.groups == m.in_channels
and m.in_channels == m.out_channels
and p == name)