Spaces:
Sleeping
Sleeping
File size: 5,484 Bytes
7f19394 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 |
import json
import os
import re
from pathlib import Path
import numpy as np
import torch
from disvae.models.vae import init_specific_model
MODEL_FILENAME = "model.pt"
META_FILENAME = "specs.json"
def vae2onnx(vae, p_out: str) -> None:
if isinstance(vae, str):
p_out = Path(p_out)
if not p_out.exists():
p_out.mkdir()
device = next(vae.parameters()).device
vae.cpu()
# Encoder
vae.encoder.eval()
dummy_input_im = torch.zeros(tuple(np.concatenate([[1], vae.img_size])))
torch.onnx.export(vae.encoder, dummy_input_im, p_out / "encoder.onnx", verbose=True)
# Decoder
vae.decoder.eval()
dummy_input_latent = torch.zeros((1, vae.latent_dim))
torch.onnx.export(
vae.decoder, dummy_input_latent, p_out / "decoder.onnx", verbose=True
)
vae.to(device) # restore device
def save_model(model, directory, metadata=None, filename=MODEL_FILENAME):
"""
Save a model and corresponding metadata.
Parameters
----------
model : nn.Module
Model.
directory : str
Path to the directory where to save the data.
metadata : dict
Metadata to save.
"""
device = next(model.parameters()).device
model.cpu()
if metadata is None:
# save the minimum required for loading
metadata = dict(
img_size=model.img_size,
latent_dim=model.latent_dim,
model_type=model.model_type,
)
save_metadata(metadata, directory)
path_to_model = os.path.join(directory, filename)
torch.save(model.state_dict(), path_to_model)
model.to(device) # restore device
def load_metadata(directory, filename=META_FILENAME):
"""Load the metadata of a training directory.
Parameters
----------
directory : string
Path to folder where model is saved. For example './experiments/mnist'.
"""
path_to_metadata = os.path.join(directory, filename)
with open(path_to_metadata) as metadata_file:
metadata = json.load(metadata_file)
return metadata
def save_metadata(metadata, directory, filename=META_FILENAME, **kwargs):
"""Load the metadata of a training directory.
Parameters
----------
metadata:
Object to save
directory: string
Path to folder where to save model. For example './experiments/mnist'.
kwargs:
Additional arguments to `json.dump`
"""
path_to_metadata = os.path.join(directory, filename)
with open(path_to_metadata, "w") as f:
json.dump(metadata, f, indent=4, sort_keys=True, **kwargs)
def load_model(directory, is_gpu=True, filename=MODEL_FILENAME):
"""Load a trained model.
Parameters
----------
directory : string
Path to folder where model is saved. For example './experiments/mnist'.
is_gpu : bool
Whether to load on GPU is available.
"""
device = torch.device("cuda" if torch.cuda.is_available() and is_gpu else "cpu")
path_to_model = os.path.join(directory, MODEL_FILENAME)
metadata = load_metadata(directory)
img_size = metadata["img_size"]
latent_dim = metadata["latent_dim"]
model_type = metadata["model_type"]
path_to_model = os.path.join(directory, filename)
model = _get_model(model_type, img_size, latent_dim, device, path_to_model)
return model
def load_checkpoints(directory, is_gpu=True):
"""Load all chechpointed models.
Parameters
----------
directory : string
Path to folder where model is saved. For example './experiments/mnist'.
is_gpu : bool
Whether to load on GPU .
"""
checkpoints = []
for root, _, filenames in os.walk(directory):
for filename in filenames:
results = re.search(r".*?-([0-9].*?).pt", filename)
if results is not None:
epoch_idx = int(results.group(1))
model = load_model(root, is_gpu=is_gpu, filename=filename)
checkpoints.append((epoch_idx, model))
return checkpoints
def _get_model(model_type, img_size, latent_dim, device, path_to_model):
"""Load a single model.
Parameters
----------
model_type : str
The name of the model to load. For example Burgess.
img_size : tuple
Tuple of the number of pixels in the image width and height.
For example (32, 32) or (64, 64).
latent_dim : int
The number of latent dimensions in the bottleneck.
device : str
Either 'cuda' or 'cpu'
path_to_device : str
Full path to the saved model on the device.
"""
model = init_specific_model(model_type, img_size, latent_dim).to(device)
# works with state_dict to make it independent of the file structure
model.load_state_dict(torch.load(path_to_model), strict=False)
model.eval()
return model
def numpy_serialize(obj):
if type(obj).__module__ == np.__name__:
if isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj.item()
raise TypeError("Unknown type:", type(obj))
def save_np_arrays(arrays, directory, filename):
"""Save dictionary of arrays in json file."""
save_metadata(arrays, directory, filename=filename, default=numpy_serialize)
def load_np_arrays(directory, filename):
"""Load dictionary of arrays from json file."""
arrays = load_metadata(directory, filename=filename)
return {k: np.array(v) for k, v in arrays.items()}
|