forked from google/nerfies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py
378 lines (334 loc) · 13.9 KB
/
eval.py
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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Evaluation script for Nerf."""
import collections
import functools
import time
from typing import Any, Dict, Optional, Sequence
from absl import app
from absl import flags
from absl import logging
from flax import jax_utils
from flax import optim
from flax.metrics import tensorboard
from flax.training import checkpoints
import gin
import jax
from jax import numpy as jnp
from jax import random
import tensorflow as tf
from nerfies import configs
from nerfies import datasets
from nerfies import evaluation
from nerfies import gpath
from nerfies import image_utils
from nerfies import model_utils
from nerfies import models
from nerfies import types
from nerfies import utils
from nerfies import visualization as viz
flags.DEFINE_string('exp_dir', None, 'where to store ckpts and logs')
flags.DEFINE_string('data_dir', None, 'input data directory.')
flags.mark_flag_as_required('exp_dir')
flags.DEFINE_multi_string('gin_bindings', None, 'Gin parameter bindings.')
flags.DEFINE_multi_string('gin_configs', (), 'Gin config files.')
FLAGS = flags.FLAGS
def compute_multiscale_ssim(image1: jnp.ndarray, image2: jnp.ndarray):
"""Compute the multiscale SSIM metric."""
image1 = tf.convert_to_tensor(image1)
image2 = tf.convert_to_tensor(image2)
return tf.image.ssim_multiscale(image1, image2, max_val=1.0)
def process_batch(*,
batch: Dict[str, jnp.ndarray],
rng: types.PRNGKey,
state: model_utils.TrainState,
tag: str,
item_id: str,
step: int,
summary_writer: tensorboard.SummaryWriter,
render_fn: Any,
save_dir: Optional[gpath.GPath],
datasource: datasets.DataSource):
"""Process and plot a single batch."""
rgb, depth_exp, depth_med, acc = render_fn(state, batch, rng=rng)
out = {}
if jax.host_id() != 0:
return out
colorize_depth = functools.partial(viz.colorize,
cmin=datasource.near,
cmax=datasource.far,
invert=True)
depth_exp_viz = colorize_depth(depth_exp[..., 0])
depth_med_viz = colorize_depth(depth_med[..., 0])
if save_dir:
save_dir.mkdir(parents=True, exist_ok=True)
image_utils.save_image(save_dir / f'rgb_{item_id}.png',
image_utils.image_to_uint8(rgb))
image_utils.save_image(save_dir / f'depth_expected_viz_{item_id}.png',
image_utils.image_to_uint8(depth_exp_viz))
image_utils.save_depth(save_dir / f'depth_expected_{item_id}.png',
depth_med[..., 0])
image_utils.save_image(save_dir / f'depth_median_viz_{item_id}.png',
image_utils.image_to_uint8(depth_med_viz))
image_utils.save_depth(save_dir / f'depth_median_{item_id}.png',
depth_med[..., 0])
summary_writer.image(f'rgb/{tag}/{item_id}', rgb, step)
summary_writer.image(f'depth-expected/{tag}/{item_id}', depth_exp_viz, step)
summary_writer.image(f'depth-median/{tag}/{item_id}', depth_med_viz, step)
summary_writer.image(f'acc/{tag}/{item_id}', acc, step)
if 'rgb' in batch:
rgb_target = batch['rgb']
mse = ((rgb - batch['rgb'])**2).mean()
psnr = utils.compute_psnr(mse)
ssim = compute_multiscale_ssim(rgb_target, rgb)
out['mse'] = mse
out['psnr'] = psnr
out['ssim'] = ssim
logging.info('\tMetrics: mse=%.04f, psnr=%.02f, ssim=%.02f',
mse, psnr, ssim)
rgb_abs_error = viz.colorize(
abs(rgb_target - rgb).sum(axis=-1), cmin=0, cmax=1)
rgb_sq_error = viz.colorize(
((rgb_target - rgb)**2).sum(axis=-1), cmin=0, cmax=1)
summary_writer.image(f'rgb-target/{tag}/{item_id}', rgb_target, step)
summary_writer.image(f'rgb-abs-error/{tag}/{item_id}', rgb_abs_error, step)
summary_writer.image(f'rgb-sq-error/{tag}/{item_id}', rgb_sq_error, step)
if 'depth' in batch:
depth_target = batch['depth']
depth_target_viz = colorize_depth(depth_target[..., 0])
out['depth_abs'] = jnp.nanmean(jnp.abs(depth_target - depth_med))
summary_writer.image(
f'depth-target/{tag}/{item_id}', depth_target_viz, step)
depth_med_error = viz.colorize(
abs(depth_target - depth_med).squeeze(axis=-1), cmin=0, cmax=1)
summary_writer.image(
f'depth-median-error/{tag}/{item_id}', depth_med_error, step)
depth_exp_error = viz.colorize(
abs(depth_target - depth_exp).squeeze(axis=-1), cmin=0, cmax=1)
summary_writer.image(
f'depth-expected-error/{tag}/{item_id}', depth_exp_error, step)
rel_disp_pred = viz.colorize(1.0 / depth_exp[..., 0])
summary_writer.image(
f'relative-disparity/{tag}/{item_id}', rel_disp_pred, step)
return out
def process_iterator(tag: str,
item_ids: Sequence[str],
iterator,
rng: types.PRNGKey,
state: model_utils.TrainState,
step: int,
render_fn: Any,
summary_writer: tensorboard.SummaryWriter,
save_dir: Optional[gpath.GPath],
datasource: datasets.DataSource):
"""Process a dataset iterator and compute metrics."""
save_dir = save_dir / f'{step:08d}' / tag if save_dir else None
meters = collections.defaultdict(utils.ValueMeter)
for i, (item_id, batch) in enumerate(zip(item_ids, iterator)):
logging.info('[%s:%d/%d] Processing %s ', tag, i+1, len(item_ids), item_id)
if tag == 'test':
test_rng = random.PRNGKey(step)
shape = batch['origins'][..., :1].shape
metadata = {}
if datasource.use_appearance_id:
appearance_id = random.choice(
test_rng, jnp.asarray(datasource.appearance_ids))
logging.info('\tUsing appearance_id = %d', appearance_id)
metadata['appearance'] = jnp.full(shape, fill_value=appearance_id,
dtype=jnp.uint32)
if datasource.use_warp_id:
warp_id = random.choice(test_rng, jnp.asarray(datasource.warp_ids))
logging.info('\tUsing warp_id = %d', warp_id)
metadata['warp'] = jnp.full(shape, fill_value=warp_id, dtype=jnp.uint32)
if datasource.use_camera_id:
camera_id = random.choice(test_rng, jnp.asarray(datasource.camera_ids))
logging.info('\tUsing camera_id = %d', camera_id)
metadata['camera'] = jnp.full(shape, fill_value=camera_id,
dtype=jnp.uint32)
batch['metadata'] = metadata
stats = process_batch(batch=batch,
rng=rng,
state=state,
tag=tag,
item_id=item_id,
step=step,
render_fn=render_fn,
summary_writer=summary_writer,
save_dir=save_dir,
datasource=datasource)
if jax.host_id() == 0:
for k, v in stats.items():
meters[k].update(v)
if jax.host_id() == 0:
for meter_name, meter in meters.items():
summary_writer.scalar(tag=f'metrics-eval/{meter_name}/{tag}',
value=meter.reduce('mean'),
step=step)
def main(argv):
del argv
logging.info('*** Starting experiment')
gin_configs = FLAGS.gin_configs
logging.info('*** Loading Gin configs from: %s', str(gin_configs))
gin.parse_config_files_and_bindings(
config_files=gin_configs,
bindings=FLAGS.gin_bindings,
skip_unknown=True)
# Load configurations.
exp_config = configs.ExperimentConfig()
model_config = configs.ModelConfig(use_stratified_sampling=False)
train_config = configs.TrainConfig()
eval_config = configs.EvalConfig()
# Get directory information.
exp_dir = gpath.GPath(FLAGS.exp_dir)
if exp_config.subname:
exp_dir = exp_dir / exp_config.subname
logging.info('\texp_dir = %s', exp_dir)
if not exp_dir.exists():
exp_dir.mkdir(parents=True, exist_ok=True)
summary_dir = exp_dir / 'summaries' / 'eval'
logging.info('\tsummary_dir = %s', summary_dir)
if not summary_dir.exists():
summary_dir.mkdir(parents=True, exist_ok=True)
renders_dir = exp_dir / 'renders'
logging.info('\trenders_dir = %s', renders_dir)
if not renders_dir.exists():
renders_dir.mkdir(parents=True, exist_ok=True)
checkpoint_dir = exp_dir / 'checkpoints'
logging.info('\tcheckpoint_dir = %s', checkpoint_dir)
rng = random.PRNGKey(20200823)
devices_to_use = jax.devices()
n_devices = len(
devices_to_use) if devices_to_use else jax.local_device_count()
datasource_spec = exp_config.datasource_spec
if datasource_spec is None:
datasource_spec = {
'type': exp_config.datasource_type,
'data_dir': FLAGS.data_dir,
}
logging.info('Creating datasource: %s', datasource_spec)
datasource = datasets.from_config(
datasource_spec,
image_scale=exp_config.image_scale,
use_appearance_id=model_config.use_appearance_metadata,
use_camera_id=model_config.use_camera_metadata,
use_warp_id=model_config.use_warp,
random_seed=exp_config.random_seed)
# Get training IDs to evaluate.
train_eval_ids = utils.strided_subset(
datasource.train_ids, eval_config.num_train_eval)
train_eval_iter = datasource.create_iterator(train_eval_ids, batch_size=0)
val_eval_ids = utils.strided_subset(
datasource.val_ids, eval_config.num_val_eval)
val_eval_iter = datasource.create_iterator(val_eval_ids, batch_size=0)
test_cameras = datasource.load_test_cameras(count=eval_config.num_test_eval)
if test_cameras:
test_dataset = datasource.create_cameras_dataset(test_cameras)
test_eval_ids = [f'{x:03d}' for x in range(len(test_cameras))]
test_eval_iter = datasets.iterator_from_dataset(test_dataset, batch_size=0)
else:
test_eval_ids = None
test_eval_iter = None
rng, key = random.split(rng)
params = {}
model, params['model'] = models.nerf(
key,
model_config,
batch_size=eval_config.chunk,
num_appearance_embeddings=len(datasource.appearance_ids),
num_camera_embeddings=len(datasource.camera_ids),
num_warp_embeddings=len(datasource.warp_ids),
near=datasource.near,
far=datasource.far,
use_warp_jacobian=False,
use_weights=False)
optimizer_def = optim.Adam(0.0)
optimizer = optimizer_def.create(params)
init_state = model_utils.TrainState(optimizer=optimizer, warp_alpha=0.0)
del params
def _model_fn(key_0, key_1, params, rays_dict, alpha):
out = model.apply({'params': params},
rays_dict,
warp_alpha=alpha,
rngs={
'coarse': key_0,
'fine': key_1
},
mutable=False)
return jax.lax.all_gather(out, axis_name='batch')
pmodel_fn = jax.pmap(
# Note rng_keys are useless in eval mode since there's no randomness.
_model_fn,
in_axes=(0, 0, 0, 0, None), # Only distribute the data input.
devices=devices_to_use,
donate_argnums=(3,), # Donate the 'rays' argument.
axis_name='batch',
)
render_fn = functools.partial(evaluation.render_image,
model_fn=pmodel_fn,
device_count=n_devices,
chunk=eval_config.chunk)
last_step = 0
summary_writer = tensorboard.SummaryWriter(str(summary_dir))
while True:
if not checkpoint_dir.exists():
logging.info('No checkpoints yet.')
time.sleep(10)
continue
state = checkpoints.restore_checkpoint(checkpoint_dir, init_state)
state = jax_utils.replicate(state, devices=devices_to_use)
step = int(state.optimizer.state.step[0])
if step <= last_step:
logging.info('No new checkpoints (%d <= %d).', step, last_step)
time.sleep(10)
continue
save_dir = renders_dir if eval_config.save_output else None
process_iterator(tag='train',
item_ids=train_eval_ids,
iterator=train_eval_iter,
state=state,
rng=rng,
step=step,
render_fn=render_fn,
summary_writer=summary_writer,
save_dir=save_dir,
datasource=datasource)
process_iterator(tag='val',
item_ids=val_eval_ids,
iterator=val_eval_iter,
state=state,
rng=rng,
step=step,
render_fn=render_fn,
summary_writer=summary_writer,
save_dir=save_dir,
datasource=datasource)
if test_eval_iter:
process_iterator(tag='test',
item_ids=test_eval_ids,
iterator=test_eval_iter,
state=state,
rng=rng,
step=step,
render_fn=render_fn,
summary_writer=summary_writer,
save_dir=save_dir,
datasource=datasource)
if eval_config.eval_once:
break
if step >= train_config.max_steps:
break
last_step = step
if __name__ == '__main__':
app.run(main)