Loads a pretrained StyleGAN2-ADA generator network from a pickle file. Args: network_pkl (str): The URL or local path to the network pickle file. device (torch.device): The device to use for the computation. fp16 (bool): Whether to use half-precision floating point
(
network_pkl: str = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/afhqdog.pkl",
device: torch.device = torch.device("cuda"),
fp16: bool = True,
)
| 18 | from . import utils |
| 19 | |
| 20 | def load_model( |
| 21 | network_pkl: str = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/afhqdog.pkl", |
| 22 | device: torch.device = torch.device("cuda"), |
| 23 | fp16: bool = True, |
| 24 | ) -> torch.nn.Module: |
| 25 | """ |
| 26 | Loads a pretrained StyleGAN2-ADA generator network from a pickle file. |
| 27 | |
| 28 | Args: |
| 29 | network_pkl (str): The URL or local path to the network pickle file. |
| 30 | device (torch.device): The device to use for the computation. |
| 31 | fp16 (bool): Whether to use half-precision floating point format for the network weights. |
| 32 | |
| 33 | Returns: |
| 34 | The pretrained generator network. |
| 35 | """ |
| 36 | print('Loading networks from "%s"...' % network_pkl) |
| 37 | with dnnlib.util.open_url(network_pkl) as f: |
| 38 | chkpt = legacy.load_network_pkl(f, force_fp16=fp16) |
| 39 | G = chkpt["G_ema"].to(device).eval() |
| 40 | for param in G.parameters(): |
| 41 | param.requires_grad_(False) |
| 42 | |
| 43 | # Create a new attribute called "activations" for the Generator class |
| 44 | # This will be a list of activations from each layer |
| 45 | G.__setattr__("activations", None) |
| 46 | |
| 47 | # Forward hook to collect features |
| 48 | def hook(module, input, output): |
| 49 | G.activations = output |
| 50 | |
| 51 | # Apply the hook to the 7th layer (256x256) |
| 52 | for i, (name, module) in enumerate(G.synthesis.named_children()): |
| 53 | if i == 6: |
| 54 | print("Registering hook for:", name) |
| 55 | module.register_forward_hook(hook) |
| 56 | |
| 57 | return G |
| 58 | |
| 59 | |
| 60 | def register_hook(G): |
no test coverage detected