Skip to content

clone_module

clone_module(module)

Clone a torch.nn.Module safely, sharing registered sub-module references.

Standard deepcopy fails when a module contains non-leaf tensors, for example the weight_u / weight_v buffers written by spectral-norm during a forward pass. This function works around the issue by temporarily detaching all registered sub-modules (module._modules) from the module registry, deepcopying only the skeleton (buffers and plain attributes, which are always leaf tensors), and then re-attaching the sub-modules by shared reference on both the original and the clone.

Sharing sub-module references is correct for our use case: the sub-modules attached to a flow model (e.g. a pre-trained score model) are never modified during flow training.

Parameters:

  • module (Module) –

    Module to clone.

Returns:

  • Module –

    Cloned module with the same skeleton and shared sub-module references.