Training and evaluation¶
What the loop does, step by step, is on the INRs page.
training
¶
Training loop for implicit neural representations (INRs) on coordinate datasets.
train
¶
train(model: Module, train_dataset: Dataset, eval_dataset: Dataset | None = None, *, loss_fn: LossFn | None = None, batch_size: int = 1, num_steps: int = 1000, optimizer: Optimizer | None = None, lr: float = 0.01, weight_decay: float = 0.0, adam_betas: tuple[float, float] = (0.9, 0.999), adam_eps: float = 1e-08, quantize: bool = False, quant_max: int = 127, quant_interval: int = -1, metrics: Mapping[str, Callable[[Tensor, Tensor], float]] | None = None, rate_metrics: Mapping[str, Callable[[bytes, Tensor], float]] | None = None, log_interval: int = 100, eval_interval: int | None = None, chunk_size: int | None = None, save_reconstruction: bool = True, device: str | device | None = None, ckpt_path: str | PathLike[str] | None = None, log_dir: str | PathLike[str] | None = None, seed: int = 0) -> dict[str, Any]
Fit an INR, by default with Adam and a cosine-annealed learning rate.
Each step draws one batch and takes one optimizer step. The learning rate anneals
over num_steps to a hundredth of its initial value, except for a
BCD solver without momentum, whose weight stays
one. The model and the datasets with a to method move to device in place.
Parameters:
-
model(Module) –INR to train in place.
-
train_dataset(Dataset) –Dataset whose items hold
inputandtarget; keys with a leading underscore stay out of training batches. -
eval_dataset(Dataset | None, default:None) –Evaluation dataset;
Noneor empty usestrain_dataset. -
loss_fn(LossFn | None, default:None) –Called as
loss_fn(batch, model) -> (loss, metrics);Noneuses MSE and logs PSNR for targets in[-1, 1]. Metrics may stay scalar tensors, read only when logged. -
batch_size(int, default:1) –Items per batch.
-
num_steps(int, default:1000) –Number of training steps.
-
optimizer(Optimizer | None, default:None) –Optimizer under the cosine schedule;
Nonebuilds Adam fromlr,weight_decay,adam_betasandadam_eps. ABCDsolver fits each batch itself, withoutloss_fn. -
lr(float, default:0.01) –Initial learning rate of Adam.
-
weight_decay(float, default:0.0) –Weight decay of Adam.
-
adam_betas(tuple[float, float], default:(0.9, 0.999)) –Moment decay rates of Adam.
-
adam_eps(float, default:1e-08) –Epsilon of Adam.
-
quantize(bool, default:False) –Whether to evaluate a quantized copy and quantize the final model in place.
-
quant_max(int, default:127) –Largest integer level, less than
2**63; codes use the smallest signed integer dtype that holds it. -
quant_interval(int, default:-1) –Steps between fake quantizations of the model, with
quantize=True; non-positive values disable them. -
metrics(Mapping[str, Callable[[Tensor, Tensor], float]] | None, default:None) –Distortion metrics by name, called as
fn(reconstruction, original). -
rate_metrics(Mapping[str, Callable[[bytes, Tensor], float]] | None, default:None) –Rate metrics by name, called as
fn(encoded_bytes, original). -
log_interval(int, default:100) –Steps between history records; final and evaluation steps are always recorded, and non-positive values record only those.
-
eval_interval(int | None, default:None) –Steps between evaluations, the final step always included;
Noneevaluates only there and non-positive values never. -
chunk_size(int | None, default:None) –Coordinates per forward pass;
Noneor a non-positive value evaluates all at once. -
save_reconstruction(bool, default:True) –Whether to save each reconstruction with
dataset.saveaslog_dir/{id}_reconstructed. -
device(str | device | None, default:None) –Device to run on;
Noneuses CUDA when available, else the CPU. -
ckpt_path(str | PathLike[str] | None, default:None) –State dict to load first, if the file exists.
-
log_dir(str | PathLike[str] | None, default:None) –Directory for
log.txt(truncated first),log.json(appended), reconstructions andcheckpoint.pt;Nonewrites no files. -
seed(int, default:0) –Seed of the global PyTorch RNG.
Returns:
-
dict[str, Any]–Dictionary with these keys.
config: Settings of the run, andpeak_memory, the most bytes a training step allocated beyond what the device already held (zero off CUDA).model_dict: Final parameters, as integer codes and scales when quantized.history: One record per logged step, withstep,elapsed(seconds spent training so far), the metrics of the step's batch and, if the step evaluated, the averaged evaluation metrics undereval.
Examples:
>>> from inro import ImageCoordinateDataset
>>> dataset = ImageCoordinateDataset(torch.zeros(3, 8, 8, dtype=torch.uint8))
>>> results = train(nn.Linear(2, 3), dataset, num_steps=2, device="cpu")
>>> sorted(results)
['config', 'history', 'model_dict']
Source code in inro/training.py
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
evaluation
¶
Chunked inference and evaluation of implicit neural representations (INRs).
chunked_inference
¶
chunked_inference(model: Module, x: Tensor, *, chunk_size: int | None = None, device: str | device | None = None) -> Tensor
Evaluate coordinates in chunks under torch.no_grad().
Moves model to device and leaves it in evaluation mode. Chunking flattens
the leading dimensions, which the output restores.
Parameters:
-
model(Module) –INR to evaluate.
-
x(Tensor) –Coordinates.
-
chunk_size(int | None, default:None) –Coordinates per forward pass;
Noneor a non-positive value evaluates all at once. -
device(str | device | None, default:None) –Device to run on;
Noneuses CUDA when available, else the CPU.
Returns:
-
Tensor–Output on
device.
Shape
- Input:
(..., C). - Output:
(..., D).
Examples:
>>> x = torch.rand(4, 5, 2)
>>> chunked_inference(nn.Linear(2, 3), x, chunk_size=8, device="cpu").shape
torch.Size([4, 5, 3])
Source code in inro/evaluation.py
evaluate
¶
evaluate(model: Module, dataset: Dataset, *, model_dict: dict[str, Any] | None = None, metrics: Mapping[str, Callable[[Tensor, Tensor], float]] | None = None, rate_metrics: Mapping[str, Callable[[bytes, Tensor], float]] | None = None, chunk_size: int | None = None, device: str | device = 'cpu', ckpt_path: str | PathLike[str] | None = None, log_dir: str | PathLike[str] | None = None, save_reconstruction: bool = True) -> dict[str, Any]
Reconstruct each dataset item, compute metrics and optionally save the result.
Items must hold id and input, and _original for metrics. The output
passes through dataset.postprocess, when it exists, and moves to the CPU for
metrics. The model moves to device and stays in evaluation mode.
Parameters:
-
model(Module) –INR to evaluate.
-
dataset(Dataset) –Dataset evaluated one item at a time.
-
model_dict(dict[str, Any] | None, default:None) –Parameters encoded for rate metrics;
Noneusesmodel.state_dict(). -
metrics(Mapping[str, Callable[[Tensor, Tensor], float]] | None, default:None) –Distortion metrics by name, called as
fn(reconstruction, original). -
rate_metrics(Mapping[str, Callable[[bytes, Tensor], float]] | None, default:None) –Rate metrics by name, called as
fn(encoded_bytes, original). -
chunk_size(int | None, default:None) –Coordinates per forward pass;
Noneor a non-positive value evaluates all at once. -
device(str | device, default:'cpu') –Device to run on.
-
ckpt_path(str | PathLike[str] | None, default:None) –State dict to load first, if the file exists.
-
log_dir(str | PathLike[str] | None, default:None) –Directory for
log.txtandlog.json(both appended) and reconstructions;Nonewrites no files. -
save_reconstruction(bool, default:True) –Whether to save each reconstruction with
dataset.saveaslog_dir/{id}_reconstructed.
Returns:
-
dict[str, Any]–Dictionary with these keys.
config: Holdsmodel,num_paramsandchunk_size.history: One record per item, withid,elapsed(seconds since the evaluation started),duration(seconds of its reconstruction, metrics left out),peak_memory(the most bytes it allocated beyond what the device already held, zero off CUDA) and the metric values.
Raises:
-
ValueError–If metrics are given for an item without
_original.
Examples:
>>> from inro import ImageCoordinateDataset, psnr
>>> dataset = ImageCoordinateDataset(torch.zeros(3, 8, 8, dtype=torch.uint8))
>>> results = evaluate(nn.Linear(2, 3), dataset, metrics={"psnr": psnr})
>>> sorted(results["history"][0])
['duration', 'elapsed', 'id', 'peak_memory', 'psnr']
Source code in inro/evaluation.py
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 202 203 204 | |