Hi, suppose for the first call of this function that layer is a neural network containing a nn.Sequential() with batch norm.
While iterating we will at some point hit the sequential layer which will raise the AttributeError which then triggers the recursuve part.
In this case the function passes the current sub_layer (nn.Sequential()) separated from the actual model and changes every batch norm to a group norm. Now the actual model has not changed and so we need to overwrite the original nn.Sequential() with the returned one.
I think you are wondering about the name right? The name returned by layer.named_modules() is a chained name as described in my function (i can’t edit the post but model.layer1.sequential… is actually not correct. It should only show the theoretical build. The correct name would be layer1.0…).
Example with a ResNet: The network does have some attributes like self.layer1 which is a sequential. To iterate over the modules, pytorch returns name = layer1.0 or layer1.1 and so on… where layer1 is the attribute of the ResNet model and 0 is the attribute of layer1. Zero in that case is the index of the first module in the sequential as a string and the module is then added like a key value pair.
See the sequential init which is build as follows:
    def __init__(self, *args):
        super(Sequential, self).__init__()
        if len(args) == 1 and isinstance(args[0], OrderedDict):
            for key, module in args[0].items():
                self.add_module(key, module)
        else:
            for idx, module in enumerate(args):
                self.add_module(str(idx), module)

The sequential actually adds the module by passing str(idx).
Actually you will overwrite the resnet.layer1 attribute multiple times but since this is done in no time, i did not insert another mechanism to simply check if we already processed the layer1 or not.
So as a result:

i split the name to get layer1 out of layer1.0
then i get the sequential by getattr
i change batch norm to group norm inside the sequential
i add the correct layer1 to the ResNet by setattr.