-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathtestbed.cu
5009 lines (4171 loc) · 176 KB
/
testbed.cu
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
/** @file testbed.cu
* @author Thomas Müller & Alex Evans, NVIDIA
*/
#include <neural-graphics-primitives/common.h>
#include <neural-graphics-primitives/common_device.cuh>
#include <neural-graphics-primitives/json_binding.h>
#include <neural-graphics-primitives/marching_cubes.h>
#include <neural-graphics-primitives/nerf_loader.h>
#include <neural-graphics-primitives/nerf_network.h>
#include <neural-graphics-primitives/render_buffer.h>
#include <neural-graphics-primitives/takikawa_encoding.cuh>
#include <neural-graphics-primitives/testbed.h>
#include <neural-graphics-primitives/tinyexr_wrapper.h>
#include <neural-graphics-primitives/trainable_buffer.cuh>
#include <neural-graphics-primitives/triangle_bvh.cuh>
#include <neural-graphics-primitives/triangle_octree.cuh>
#include <tiny-cuda-nn/encodings/grid.h>
#include <tiny-cuda-nn/loss.h>
#include <tiny-cuda-nn/network.h>
#include <tiny-cuda-nn/network_with_input_encoding.h>
#include <tiny-cuda-nn/optimizer.h>
#include <tiny-cuda-nn/trainer.h>
#include <json/json.hpp>
#include <filesystem/directory.h>
#include <filesystem/path.h>
#include <zstr.hpp>
#include <fstream>
#include <set>
#include <unordered_set>
#ifdef NGP_GUI
# include <imgui/backends/imgui_impl_glfw.h>
# include <imgui/backends/imgui_impl_opengl3.h>
# include <imgui/imgui.h>
# include <imguizmo/ImGuizmo.h>
# ifdef _WIN32
# include <GL/gl3w.h>
# else
# include <GL/glew.h>
# endif
# include <GLFW/glfw3.h>
# include <GLFW/glfw3native.h>
# include <cuda_gl_interop.h>
#endif
// Windows.h is evil
#undef min
#undef max
#undef near
#undef far
using namespace std::literals::chrono_literals;
namespace ngp {
int do_system(const std::string& cmd) {
#ifdef _WIN32
tlog::info() << "> " << cmd;
return _wsystem(utf8_to_utf16(cmd).c_str());
#else
tlog::info() << "$ " << cmd;
return system(cmd.c_str());
#endif
}
std::atomic<size_t> g_total_n_bytes_allocated{0};
json merge_parent_network_config(const json& child, const fs::path& child_path) {
if (!child.contains("parent")) {
return child;
}
fs::path parent_path = child_path.parent_path() / std::string(child["parent"]);
tlog::info() << "Loading parent network config from: " << parent_path.str();
std::ifstream f{native_string(parent_path)};
json parent = json::parse(f, nullptr, true, true);
parent = merge_parent_network_config(parent, parent_path);
parent.merge_patch(child);
return parent;
}
std::string get_filename_in_data_path_with_suffix(fs::path data_path, fs::path network_config_path, const char* suffix) {
// use the network config name along with the data path to build a filename with the requested suffix & extension
std::string default_name = network_config_path.basename();
if (default_name == "") {
default_name = "base";
}
if (data_path.empty()) {
return default_name + std::string(suffix);
}
if (data_path.is_directory()) {
return (data_path / (default_name + std::string{suffix})).str();
}
return data_path.stem().str() + "_" + default_name + std::string(suffix);
}
void Testbed::update_imgui_paths() {
snprintf(m_imgui.cam_path_path, sizeof(m_imgui.cam_path_path), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, "_cam.json").c_str());
snprintf(m_imgui.extrinsics_path, sizeof(m_imgui.extrinsics_path), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, "_extrinsics.json").c_str());
snprintf(m_imgui.mesh_path, sizeof(m_imgui.mesh_path), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, ".obj").c_str());
snprintf(m_imgui.snapshot_path, sizeof(m_imgui.snapshot_path), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, ".ingp").c_str());
snprintf(m_imgui.video_path, sizeof(m_imgui.video_path), "%s", get_filename_in_data_path_with_suffix(m_data_path, m_network_config_path, "_video.mp4").c_str());
}
void Testbed::load_training_data(const fs::path& path) {
if (!path.exists()) {
throw std::runtime_error{fmt::format("Data path '{}' does not exist.", path.str())};
}
// Automatically determine the mode from the first scene that's loaded
ETestbedMode scene_mode = mode_from_scene(path.str());
if (scene_mode == ETestbedMode::None) {
throw std::runtime_error{fmt::format("Unknown scene format for path '{}'.", path.str())};
}
set_mode(scene_mode);
m_data_path = path;
switch (m_testbed_mode) {
case ETestbedMode::Nerf: load_nerf(path); break;
case ETestbedMode::Sdf: load_mesh(path); break;
case ETestbedMode::Image: load_image(path); break;
case ETestbedMode::Volume: load_volume(path); break;
default: throw std::runtime_error{"Invalid testbed mode."};
}
m_training_data_available = true;
update_imgui_paths();
}
void Testbed::reload_training_data() {
if (m_data_path.exists()) {
load_training_data(m_data_path.str());
}
}
void Testbed::clear_training_data() {
m_training_data_available = false;
m_nerf.training.dataset.metadata.clear();
}
void Testbed::set_mode(ETestbedMode mode) {
if (mode == m_testbed_mode) {
return;
}
// Reset mode-specific members
m_image = {};
m_mesh = {};
m_nerf = {};
m_sdf = {};
m_volume = {};
// Kill training-related things
m_encoding = {};
m_loss = {};
m_network = {};
m_nerf_network = {};
m_optimizer = {};
m_trainer = {};
m_envmap = {};
m_distortion = {};
m_training_data_available = false;
// Clear device-owned data that might be mode-specific
for (auto&& device : m_devices) {
device.clear();
}
// Reset paths that might be attached to the chosen mode
m_data_path = {};
m_testbed_mode = mode;
// Set various defaults depending on mode
if (m_testbed_mode == ETestbedMode::Nerf) {
if (m_devices.size() > 1) {
m_use_aux_devices = true;
}
if (m_dlss_provider && m_aperture_size == 0.0f) {
m_dlss = true;
}
} else {
m_use_aux_devices = false;
m_dlss = false;
}
reset_camera();
#ifdef NGP_GUI
update_vr_performance_settings();
#endif
}
fs::path Testbed::find_network_config(const fs::path& network_config_path) {
if (network_config_path.exists()) {
return network_config_path;
}
// The following resolution steps do not work if the path is absolute. Treat it as nonexistent.
if (network_config_path.is_absolute()) {
return network_config_path;
}
fs::path candidate = root_dir()/"configs"/to_string(m_testbed_mode)/network_config_path;
if (candidate.exists()) {
return candidate;
}
return network_config_path;
}
json Testbed::load_network_config(const fs::path& network_config_path) {
bool is_snapshot = equals_case_insensitive(network_config_path.extension(), "msgpack") || equals_case_insensitive(network_config_path.extension(), "ingp");
if (network_config_path.empty() || !network_config_path.exists()) {
throw std::runtime_error{fmt::format("Network {} '{}' does not exist.", is_snapshot ? "snapshot" : "config", network_config_path.str())};
}
tlog::info() << "Loading network " << (is_snapshot ? "snapshot" : "config") << " from: " << network_config_path;
json result;
if (is_snapshot) {
std::ifstream f{native_string(network_config_path), std::ios::in | std::ios::binary};
if (equals_case_insensitive(network_config_path.extension(), "ingp")) {
// zstr::ifstream applies zlib compression.
zstr::istream zf{f};
result = json::from_msgpack(zf);
} else {
result = json::from_msgpack(f);
}
// we assume parent pointers are already resolved in snapshots.
} else if (equals_case_insensitive(network_config_path.extension(), "json")) {
std::ifstream f{native_string(network_config_path)};
result = json::parse(f, nullptr, true, true);
result = merge_parent_network_config(result, network_config_path);
}
return result;
}
void Testbed::reload_network_from_file(const fs::path& path) {
if (!path.empty()) {
fs::path candidate = find_network_config(path);
if (candidate.exists() || !m_network_config_path.exists()) {
// Store the path _argument_ in the member variable. E.g. for the base config,
// it'll store `base.json`, even though the loaded config will be
// config/<mode>/base.json. This has the benefit of switching to the
// appropriate config when switching modes.
m_network_config_path = path;
}
}
// If the testbed mode hasn't been decided yet, don't load a network yet, but
// still keep track of the requested config (see above).
if (m_testbed_mode == ETestbedMode::None) {
return;
}
fs::path full_network_config_path = find_network_config(m_network_config_path);
bool is_snapshot = equals_case_insensitive(full_network_config_path.extension(), "msgpack");
if (!full_network_config_path.exists()) {
tlog::warning() << "Network " << (is_snapshot ? "snapshot" : "config") << " path '" << full_network_config_path << "' does not exist.";
} else {
m_network_config = load_network_config(full_network_config_path);
}
// Reset training if we haven't loaded a snapshot of an already trained model, in which case, presumably the network
// configuration changed and the user is interested in seeing how it trains from scratch.
if (!is_snapshot) {
reset_network();
}
}
void Testbed::reload_network_from_json(const json& json, const std::string& config_base_path) {
// config_base_path is needed so that if the passed in json uses the 'parent' feature, we know where to look...
// be sure to use a filename, or if a directory, end with a trailing slash
m_network_config = merge_parent_network_config(json, config_base_path);
reset_network();
}
void Testbed::load_file(const fs::path& path) {
if (!path.exists()) {
// If the path doesn't exist, but a network config can be resolved, load that.
if (equals_case_insensitive(path.extension(), "json") && find_network_config(path).exists()) {
reload_network_from_file(path);
return;
}
tlog::error() << "File '" << path.str() << "' does not exist.";
return;
}
if (equals_case_insensitive(path.extension(), "ingp") || equals_case_insensitive(path.extension(), "msgpack")) {
load_snapshot(path);
return;
}
// If we get a json file, we need to parse it to determine its purpose.
if (equals_case_insensitive(path.extension(), "json")) {
json file;
{
std::ifstream f{native_string(path)};
file = json::parse(f, nullptr, true, true);
}
// Snapshot in json format... inefficient, but technically supported.
if (file.contains("snapshot")) {
load_snapshot(path);
return;
}
// Regular network config
if (file.contains("parent") || file.contains("network") || file.contains("encoding") || file.contains("loss") || file.contains("optimizer")) {
reload_network_from_file(path);
return;
}
// Camera path
if (file.contains("path")) {
load_camera_path(path);
return;
}
}
// If the dragged file isn't any of the above, assume that it's training data
try {
bool was_training_data_available = m_training_data_available;
load_training_data(path);
if (!was_training_data_available) {
// If we previously didn't have any training data and only now dragged
// some into the window, it is very unlikely that the user doesn't
// want to immediately start training on that data. So: go for it.
m_train = true;
}
} catch (const std::runtime_error& e) {
tlog::error() << "Failed to load training data: " << e.what();
}
}
void Testbed::reset_accumulation(bool due_to_camera_movement, bool immediate_redraw) {
if (immediate_redraw) {
redraw_next_frame();
}
if (!due_to_camera_movement || !reprojection_available()) {
m_windowless_render_surface.reset_accumulation();
for (auto& view : m_views) {
view.render_buffer->reset_accumulation();
}
}
}
void Testbed::set_visualized_dim(int dim) {
m_visualized_dimension = dim;
reset_accumulation();
}
void Testbed::translate_camera(const vec3& rel, const mat3& rot, bool allow_up_down) {
vec3 movement = rot * rel;
if (!allow_up_down) {
movement -= dot(movement, m_up_dir) * m_up_dir;
}
m_camera[3] += movement;
reset_accumulation(true);
}
void Testbed::set_nerf_camera_matrix(const mat4x3& cam) {
m_camera = m_nerf.training.dataset.nerf_matrix_to_ngp(cam);
}
vec3 Testbed::look_at() const {
return view_pos() + view_dir() * m_scale;
}
void Testbed::set_look_at(const vec3& pos) {
m_camera[3] += pos - look_at();
}
void Testbed::set_scale(float scale) {
auto prev_look_at = look_at();
m_camera[3] = (view_pos() - prev_look_at) * (scale / m_scale) + prev_look_at;
m_scale = scale;
}
void Testbed::set_view_dir(const vec3& dir) {
auto old_look_at = look_at();
m_camera[0] = normalize(cross(dir, m_up_dir));
m_camera[1] = normalize(cross(dir, m_camera[0]));
m_camera[2] = normalize(dir);
set_look_at(old_look_at);
}
void Testbed::first_training_view() {
m_nerf.training.view = 0;
set_camera_to_training_view(m_nerf.training.view);
}
void Testbed::last_training_view() {
m_nerf.training.view = m_nerf.training.dataset.n_images-1;
set_camera_to_training_view(m_nerf.training.view);
}
void Testbed::previous_training_view() {
if (m_nerf.training.view != 0) {
m_nerf.training.view -= 1;
}
set_camera_to_training_view(m_nerf.training.view);
}
void Testbed::next_training_view() {
if (m_nerf.training.view != m_nerf.training.dataset.n_images-1) {
m_nerf.training.view += 1;
}
set_camera_to_training_view(m_nerf.training.view);
}
void Testbed::set_camera_to_training_view(int trainview) {
auto old_look_at = look_at();
m_camera = m_smoothed_camera = get_xform_given_rolling_shutter(m_nerf.training.transforms[trainview], m_nerf.training.dataset.metadata[trainview].rolling_shutter, vec2{0.5f, 0.5f}, 0.0f);
m_relative_focal_length = m_nerf.training.dataset.metadata[trainview].focal_length / (float)m_nerf.training.dataset.metadata[trainview].resolution[m_fov_axis];
m_scale = std::max(dot(old_look_at - view_pos(), view_dir()), 0.1f);
m_nerf.render_with_lens_distortion = true;
m_nerf.render_lens = m_nerf.training.dataset.metadata[trainview].lens;
if (!supports_dlss(m_nerf.render_lens.mode)) {
m_dlss = false;
}
m_screen_center = vec2(1.0f) - m_nerf.training.dataset.metadata[trainview].principal_point;
m_nerf.training.view = trainview;
reset_accumulation(true);
}
void Testbed::reset_camera() {
m_fov_axis = 1;
m_zoom = 1.0f;
m_screen_center = vec2(0.5f);
if (m_testbed_mode == ETestbedMode::Image) {
// Make image full-screen at the given view distance
m_relative_focal_length = vec2(1.0f);
m_scale = 1.0f;
} else {
set_fov(50.625f);
m_scale = 1.5f;
}
m_camera = transpose(mat3x4{
1.0f, 0.0f, 0.0f, 0.5f,
0.0f, -1.0f, 0.0f, 0.5f,
0.0f, 0.0f, -1.0f, 0.5f
});
m_camera[3] -= m_scale * view_dir();
m_smoothed_camera = m_camera;
m_sun_dir = normalize(vec3(1.0f));
reset_accumulation();
}
void Testbed::set_train(bool mtrain) {
if (m_train && !mtrain && m_max_level_rand_training) {
set_max_level(1.f);
}
m_train = mtrain;
}
void Testbed::compute_and_save_marching_cubes_mesh(const fs::path& filename, ivec3 res3d , BoundingBox aabb, float thresh, bool unwrap_it) {
mat3 render_aabb_to_local = mat3::identity();
if (aabb.is_empty()) {
aabb = m_testbed_mode == ETestbedMode::Nerf ? m_render_aabb : m_aabb;
render_aabb_to_local = m_render_aabb_to_local;
}
marching_cubes(res3d, aabb, render_aabb_to_local, thresh);
save_mesh(m_mesh.verts, m_mesh.vert_normals, m_mesh.vert_colors, m_mesh.indices, filename, unwrap_it, m_nerf.training.dataset.scale, m_nerf.training.dataset.offset);
}
ivec3 Testbed::compute_and_save_png_slices(const fs::path& filename, int res, BoundingBox aabb, float thresh, float density_range, bool flip_y_and_z_axes) {
mat3 render_aabb_to_local = mat3::identity();
if (aabb.is_empty()) {
aabb = m_testbed_mode == ETestbedMode::Nerf ? m_render_aabb : m_aabb;
render_aabb_to_local = m_render_aabb_to_local;
}
if (thresh == std::numeric_limits<float>::max()) {
thresh = m_mesh.thresh;
}
float range = density_range;
if (m_testbed_mode == ETestbedMode::Sdf) {
auto res3d = get_marching_cubes_res(res, aabb);
aabb.inflate(range * aabb.diag().x/res3d.x);
}
auto res3d = get_marching_cubes_res(res, aabb);
if (m_testbed_mode == ETestbedMode::Sdf) {
// rescale the range to be in output voxels. ie this scale factor is mapped back to the original world space distances.
// negated so that black = outside, white = inside
range *= -aabb.diag().x / res3d.x;
}
std::string fname = fmt::format(".density_slices_{}x{}x{}.png", res3d.x, res3d.y, res3d.z);
GPUMemory<float> density = (m_render_ground_truth && m_testbed_mode == ETestbedMode::Sdf) ? get_sdf_gt_on_grid(res3d, aabb, render_aabb_to_local) : get_density_on_grid(res3d, aabb, render_aabb_to_local);
save_density_grid_to_png(density, filename.str() + fname, res3d, thresh, flip_y_and_z_axes, range);
return res3d;
}
fs::path Testbed::root_dir() {
if (m_root_dir.empty()) {
set_root_dir(discover_root_dir());
}
return m_root_dir;
}
void Testbed::set_root_dir(const fs::path& dir) {
m_root_dir = dir;
}
inline float linear_to_db(float x) {
return -10.f*logf(x)/logf(10.f);
}
template <typename T>
void Testbed::dump_parameters_as_images(const T* params, const std::string& filename_base) {
if (!m_network) {
return;
}
size_t non_layer_params_width = 2048;
size_t layer_params = 0;
for (auto size : m_network->layer_sizes()) {
layer_params += size.first * size.second;
}
size_t n_params = m_network->n_params();
size_t n_non_layer_params = n_params - layer_params;
std::vector<T> params_cpu_network_precision(layer_params + next_multiple(n_non_layer_params, non_layer_params_width));
std::vector<float> params_cpu(params_cpu_network_precision.size(), 0.0f);
CUDA_CHECK_THROW(cudaMemcpy(params_cpu_network_precision.data(), params, n_params * sizeof(T), cudaMemcpyDeviceToHost));
for (size_t i = 0; i < n_params; ++i) {
params_cpu[i] = (float)params_cpu_network_precision[i];
}
size_t offset = 0;
size_t layer_id = 0;
for (auto size : m_network->layer_sizes()) {
save_exr(params_cpu.data() + offset, size.second, size.first, 1, 1, fmt::format("{}-layer-{}.exr", filename_base, layer_id).c_str());
offset += size.first * size.second;
++layer_id;
}
if (n_non_layer_params > 0) {
std::string filename = fmt::format("{}-non-layer.exr", filename_base);
save_exr(params_cpu.data() + offset, non_layer_params_width, n_non_layer_params / non_layer_params_width, 1, 1, filename.c_str());
}
}
template void Testbed::dump_parameters_as_images<__half>(const __half*, const std::string&);
template void Testbed::dump_parameters_as_images<float>(const float*, const std::string&);
mat4x3 Testbed::crop_box(bool nerf_space) const {
vec3 cen = transpose(m_render_aabb_to_local) * m_render_aabb.center();
vec3 radius = m_render_aabb.diag() * 0.5f;
vec3 x = row(m_render_aabb_to_local, 0) * radius.x;
vec3 y = row(m_render_aabb_to_local, 1) * radius.y;
vec3 z = row(m_render_aabb_to_local, 2) * radius.z;
mat4x3 rv;
rv[0] = x;
rv[1] = y;
rv[2] = z;
rv[3] = cen;
if (nerf_space) {
rv = m_nerf.training.dataset.ngp_matrix_to_nerf(rv, true);
}
return rv;
}
void Testbed::set_crop_box(mat4x3 m, bool nerf_space) {
if (nerf_space) {
m = m_nerf.training.dataset.nerf_matrix_to_ngp(m, true);
}
vec3 radius{length(m[0]), length(m[1]), length(m[2])};
vec3 cen(m[3]);
m_render_aabb_to_local = row(m_render_aabb_to_local, 0, m[0] / radius.x);
m_render_aabb_to_local = row(m_render_aabb_to_local, 1, m[1] / radius.y);
m_render_aabb_to_local = row(m_render_aabb_to_local, 2, m[2] / radius.z);
cen = m_render_aabb_to_local * cen;
m_render_aabb.min = cen - radius;
m_render_aabb.max = cen + radius;
}
std::vector<vec3> Testbed::crop_box_corners(bool nerf_space) const {
mat4x3 m = crop_box(nerf_space);
std::vector<vec3> rv(8);
for (int i = 0; i < 8; ++i) {
rv[i] = m * vec4{(i & 1) ? 1.f : -1.f, (i & 2) ? 1.f : -1.f, (i & 4) ? 1.f : -1.f, 1.f};
/* debug print out corners to check math is all lined up */
if (0) {
tlog::info() << rv[i].x << "," << rv[i].y << "," << rv[i].z << " [" << i << "]";
vec3 mn = m_render_aabb.min;
vec3 mx = m_render_aabb.max;
mat3 m = transpose(m_render_aabb_to_local);
vec3 a;
a.x = (i&1) ? mx.x : mn.x;
a.y = (i&2) ? mx.y : mn.y;
a.z = (i&4) ? mx.z : mn.z;
a = m * a;
if (nerf_space) {
a = m_nerf.training.dataset.ngp_position_to_nerf(a);
}
tlog::info() << a.x << "," << a.y << "," << a.z << " [" << i << "]";
}
}
return rv;
}
#ifdef NGP_GUI
bool imgui_colored_button(const char *name, float hue) {
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
bool rv = ImGui::Button(name);
ImGui::PopStyleColor(3);
return rv;
}
void Testbed::imgui() {
// If a GUI interaction causes an error, write that error to the following string and call
// ImGui::OpenPopup("Error");
static std::string imgui_error_string = "";
m_picture_in_picture_res = 0;
if (ImGui::Begin("Camera path", 0, ImGuiWindowFlags_NoScrollbar)) {
if (ImGui::CollapsingHeader("Path manipulation", ImGuiTreeNodeFlags_DefaultOpen)) {
if (int read = m_camera_path.imgui(
m_imgui.cam_path_path,
m_render_ms.val(),
m_camera,
m_slice_plane_z,
m_scale,
fov(),
m_aperture_size,
m_bounding_radius,
!m_nerf.training.dataset.xforms.empty() ? m_nerf.training.dataset.xforms[0].start : mat4x3::identity(),
m_nerf.glow_mode,
m_nerf.glow_y_cutoff
)) {
if (!m_camera_path.rendering) {
reset_accumulation(true);
if (m_camera_path.update_cam_from_path) {
set_camera_from_time(m_camera_path.play_time);
// A value of larger than 1 indicates that the camera path wants
// to override camera smoothing.
if (read > 1) {
m_smoothed_camera = m_camera;
}
} else {
m_pip_render_buffer->reset_accumulation();
}
}
}
if (!m_camera_path.keyframes.empty()) {
float w = ImGui::GetContentRegionAvail().x;
if (m_camera_path.update_cam_from_path) {
m_picture_in_picture_res = 0;
ImGui::Image((ImTextureID)(size_t)m_rgba_render_textures.front()->texture(), ImVec2(w, w * 9.0f / 16.0f));
} else {
m_picture_in_picture_res = (float)std::min((int(w)+31)&(~31), 1920/4);
ImGui::Image((ImTextureID)(size_t)m_pip_render_texture->texture(), ImVec2(w, w * 9.0f / 16.0f));
}
}
}
if (!m_camera_path.keyframes.empty() && ImGui::CollapsingHeader("Export video", ImGuiTreeNodeFlags_DefaultOpen)) {
// Render a video
if (imgui_colored_button(m_camera_path.rendering ? "Abort rendering" : "Render video", 0.4)) {
m_camera_path.rendering = !m_camera_path.rendering;
if (!clear_tmp_dir()) {
imgui_error_string = "Failed to clear temporary directory 'tmp' to hold rendered images.";
ImGui::OpenPopup("Error");
m_camera_path.rendering = false;
}
if (m_camera_path.rendering) {
m_camera_path.render_start_time = std::chrono::steady_clock::now();
m_camera_path.update_cam_from_path = true;
m_camera_path.play_time = 0.0f;
m_camera_path.auto_play_speed = 1.0f;
m_camera_path.render_frame_idx = 0;
m_dlss = false;
m_train = false;
reset_accumulation(true);
set_camera_from_time(m_camera_path.play_time);
m_smoothed_camera = m_camera;
} else {
m_camera_path.update_cam_from_path = false;
m_camera_path.play_time = 0.0f;
m_camera_path.auto_play_speed = 0.0f;
}
}
if (m_camera_path.rendering) {
ImGui::SameLine();
auto elapsed = std::chrono::steady_clock::now() - m_camera_path.render_start_time;
uint32_t progress = m_camera_path.render_frame_idx * m_camera_path.render_settings.spp + m_views.front().render_buffer->spp();
uint32_t goal = m_camera_path.render_settings.n_frames() * m_camera_path.render_settings.spp;
auto est_remaining = elapsed * (float)(goal - progress) / std::max(progress, 1u);
ImGui::Text("%s", fmt::format(
"Frame {}/{}, Elapsed: {}, Remaining: {}",
m_camera_path.render_frame_idx+1,
m_camera_path.render_settings.n_frames(),
tlog::durationToString(std::chrono::steady_clock::now() - m_camera_path.render_start_time),
tlog::durationToString(est_remaining)
).c_str());
}
if (m_camera_path.rendering) { ImGui::BeginDisabled(); }
ImGui::InputText("File##Video file path", m_imgui.video_path, sizeof(m_imgui.video_path));
m_camera_path.render_settings.filename = m_imgui.video_path;
ImGui::InputInt2("Resolution", &m_camera_path.render_settings.resolution.x);
ImGui::InputFloat("Duration (seconds)", &m_camera_path.render_settings.duration_seconds);
ImGui::InputFloat("FPS (frames/second)", &m_camera_path.render_settings.fps);
ImGui::InputInt("SPP (samples/pixel)", &m_camera_path.render_settings.spp);
ImGui::SliderInt("Quality", &m_camera_path.render_settings.quality, 0, 10);
ImGui::SliderFloat("Shutter fraction", &m_camera_path.render_settings.shutter_fraction, 0.0f, 1.0f);
if (m_camera_path.rendering) { ImGui::EndDisabled(); }
}
}
ImGui::End();
bool train_extra_dims = m_nerf.training.dataset.n_extra_learnable_dims > 0;
if (train_extra_dims && m_nerf.training.n_images_for_training > 0) {
if (ImGui::Begin("Latent space 2D embedding")) {
ImVec2 size = ImGui::GetContentRegionAvail();
if (size.x<100.f) size.x = 100.f;
if (size.y<100.f) size.y = 100.f;
ImGui::InvisibleButton("##empty", size);
static std::vector<float> X;
static std::vector<float> Y;
uint32_t n_extra_dims = m_nerf.training.dataset.n_extra_dims();
std::vector<float> mean(n_extra_dims, 0.0f);
uint32_t n = m_nerf.training.n_images_for_training;
float norm = 1.0f / n;
for (uint32_t i = 0; i < n; ++i) {
for (uint32_t j = 0; j < n_extra_dims; ++j) {
mean[j] += m_nerf.training.extra_dims_opt[i].variable()[j] * norm;
}
}
std::vector<float> cov(n_extra_dims * n_extra_dims, 0.0f);
float scale = 0.001f; // compute scale
for (uint32_t i = 0; i < n; ++i) {
std::vector<float> v = m_nerf.training.extra_dims_opt[i].variable();
for (uint32_t j = 0; j < n_extra_dims; ++j) {
v[j] -= mean[j];
}
for (uint32_t m = 0; m < n_extra_dims; ++m) {
for (uint32_t n = 0; n < n_extra_dims; ++n) {
cov[m + n * n_extra_dims] += v[m] * v[n];
}
}
}
scale = 3.0f; // fixed scale
if (X.size() != mean.size()) { X = std::vector<float>(mean.size(), 0.0f); }
if (Y.size() != mean.size()) { Y = std::vector<float>(mean.size(), 0.0f); }
// power iteration to get X and Y. TODO: modified gauss siedel to orthonormalize X and Y jointly?
// X = (X * cov); if (X.norm() == 0.f) { X.setZero(); X.x() = 1.f; } else X.normalize();
// Y = (Y * cov); Y -= Y.dot(X) * X; if (Y.norm() == 0.f) { Y.setZero(); Y.y() = 1.f; } else Y.normalize();
std::vector<float> tmp(mean.size(), 0.0f);
norm = 0.0f;
for (uint32_t m = 0; m < n_extra_dims; ++m) {
tmp[m] = 0.0f;
for (uint32_t n = 0; n < n_extra_dims; ++n) {
tmp[m] += X[n] * cov[m + n * n_extra_dims];
}
norm += tmp[m] * tmp[m];
}
norm = std::sqrt(norm);
for (uint32_t m = 0; m < n_extra_dims; ++m) {
if (norm == 0.0f) {
X[m] = m == 0 ? 1.0f : 0.0f;
continue;
}
X[m] = tmp[m] / norm;
}
float y_dot_x = 0.0f;
for (uint32_t m = 0; m < n_extra_dims; ++m) {
tmp[m] = 0.0f;
for (uint32_t n = 0; n < n_extra_dims; ++n) {
tmp[m] += Y[n] * cov[m + n * n_extra_dims];
}
y_dot_x += tmp[m] * X[m];
}
norm = 0.0f;
for (uint32_t m = 0; m < n_extra_dims; ++m) {
Y[m] = tmp[m] - y_dot_x * X[m];
norm += Y[m] * Y[m];
}
norm = std::sqrt(norm);
for (uint32_t m = 0; m < n_extra_dims; ++m) {
if (norm == 0.0f) {
Y[m] = m == 1 ? 1.0f : 0.0f;
continue;
}
Y[m] = Y[m] / norm;
}
const ImVec2 p0 = ImGui::GetItemRectMin();
const ImVec2 p1 = ImGui::GetItemRectMax();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(p0, p1, IM_COL32(0, 0, 0, 255));
draw_list->AddRect(p0, p1, IM_COL32(255, 255, 255, 128));
ImGui::PushClipRect(p0, p1, true);
vec2 mouse = {ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y};
for (uint32_t i = 0; i < n; ++i) {
vec2 p = vec2(0.0f);
std::vector<float> v = m_nerf.training.extra_dims_opt[i].variable();
for (uint32_t j = 0; j < n_extra_dims; ++j) {
p.x += (v[j] - mean[j]) * X[j] / scale;
p.y += (v[j] - mean[j]) * Y[j] / scale;
}
p = ((p * vec2{p1.x - p0.x - 20.f, p1.y - p0.y - 20.f}) + vec2{p0.x + p1.x, p0.y + p1.y}) * 0.5f;
if (distance(p, mouse) < 10.0f) {
ImGui::SetTooltip("%d", i);
}
float theta = i * PI() * 2.0f / n;
ImColor col(sinf(theta) * 0.4f + 0.5f, sinf(theta + PI() * 2.0f / 3.0f) * 0.4f + 0.5f, sinf(theta + PI() * 4.0f / 3.0f) * 0.4f + 0.5f);
draw_list->AddCircleFilled(ImVec2{p.x, p.y}, 10.f, col);
draw_list->AddCircle(ImVec2{p.x, p.y}, 10.f, IM_COL32(255, 255, 255, 64));
}
ImGui::PopClipRect();
}
ImGui::End();
}
ImGui::Begin("instant-ngp v" NGP_VERSION);
size_t n_bytes = tcnn::total_n_bytes_allocated() + g_total_n_bytes_allocated;
if (m_dlss_provider) {
n_bytes += m_dlss_provider->allocated_bytes();
}
ImGui::Text("Frame: %.2f ms (%.1f FPS); Mem: %s", m_frame_ms.ema_val(), 1000.0f / m_frame_ms.ema_val(), bytes_to_string(n_bytes).c_str());
bool accum_reset = false;
if (!m_training_data_available) { ImGui::BeginDisabled(); }
if (ImGui::CollapsingHeader("Training", m_training_data_available ? ImGuiTreeNodeFlags_DefaultOpen : 0)) {
if (imgui_colored_button(m_train ? "Stop training" : "Start training", 0.4)) {
set_train(!m_train);
}
ImGui::SameLine();
if (imgui_colored_button("Reset training", 0.f)) {
reload_network_from_file();
}
ImGui::SameLine();
ImGui::Checkbox("encoding", &m_train_encoding);
ImGui::SameLine();
ImGui::Checkbox("network", &m_train_network);
ImGui::SameLine();
ImGui::Checkbox("rand levels", &m_max_level_rand_training);
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::Checkbox("envmap", &m_nerf.training.train_envmap);
ImGui::SameLine();
ImGui::Checkbox("extrinsics", &m_nerf.training.optimize_extrinsics);
ImGui::SameLine();
ImGui::Checkbox("distortion", &m_nerf.training.optimize_distortion);
ImGui::SameLine();
ImGui::Checkbox("per-image latents", &m_nerf.training.optimize_extra_dims);
static bool export_extrinsics_in_quat_format = true;
static bool extrinsics_have_been_optimized = false;
if (m_nerf.training.optimize_extrinsics) {
extrinsics_have_been_optimized = true;
}
if (extrinsics_have_been_optimized) {
if (imgui_colored_button("Export extrinsics", 0.4f)) {
m_nerf.training.export_camera_extrinsics(m_imgui.extrinsics_path, export_extrinsics_in_quat_format);
}
ImGui::SameLine();
ImGui::Checkbox("as quaternions", &export_extrinsics_in_quat_format);
ImGui::InputText("File##Extrinsics file path", m_imgui.extrinsics_path, sizeof(m_imgui.extrinsics_path));
}
}
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.3f);
ImGui::SliderInt("Batch size", (int*)&m_training_batch_size, 1 << 12, 1 << 22, "%d", ImGuiSliderFlags_Logarithmic);
ImGui::SameLine();
ImGui::DragInt("Seed", (int*)&m_seed, 1.0f, 0, std::numeric_limits<int>::max());
ImGui::PopItemWidth();
m_training_batch_size = next_multiple(m_training_batch_size, BATCH_SIZE_GRANULARITY);
if (m_train) {
std::vector<std::string> timings;
if (m_testbed_mode == ETestbedMode::Nerf) {
timings.emplace_back(fmt::format("Grid: {:.01f}ms", m_training_prep_ms.ema_val()));
} else {
timings.emplace_back(fmt::format("Datagen: {:.01f}ms", m_training_prep_ms.ema_val()));
}
timings.emplace_back(fmt::format("Training: {:.01f}ms", m_training_ms.ema_val()));
ImGui::Text("%s", join(timings, ", ").c_str());
} else {
ImGui::Text("Training paused");
}
if (m_testbed_mode == ETestbedMode::Nerf) {
ImGui::Text("Rays/batch: %d, Samples/ray: %.2f, Batch size: %d/%d", m_nerf.training.counters_rgb.rays_per_batch, (float)m_nerf.training.counters_rgb.measured_batch_size / (float)m_nerf.training.counters_rgb.rays_per_batch, m_nerf.training.counters_rgb.measured_batch_size, m_nerf.training.counters_rgb.measured_batch_size_before_compaction);
}
float elapsed_training = std::chrono::duration<float>(std::chrono::steady_clock::now() - m_training_start_time_point).count();
ImGui::Text("Steps: %d, Loss: %0.6f (%0.2f dB), Elapsed: %.1fs", m_training_step, m_loss_scalar.ema_val(), linear_to_db(m_loss_scalar.ema_val()), elapsed_training);
ImGui::PlotLines("loss graph", m_loss_graph.data(), std::min(m_loss_graph_samples, m_loss_graph.size()), (m_loss_graph_samples < m_loss_graph.size()) ? 0 : (m_loss_graph_samples % m_loss_graph.size()), 0, FLT_MAX, FLT_MAX, ImVec2(0, 50.f));
if (m_testbed_mode == ETestbedMode::Nerf && ImGui::TreeNode("NeRF training options")) {
ImGui::Checkbox("Random bg color", &m_nerf.training.random_bg_color);
ImGui::SameLine();
ImGui::Checkbox("Snap to pixel centers", &m_nerf.training.snap_to_pixel_centers);
ImGui::SliderFloat("Near distance", &m_nerf.training.near_distance, 0.0f, 1.0f);
accum_reset |= ImGui::Checkbox("Linear colors", &m_nerf.training.linear_colors);
ImGui::Combo("Loss", (int*)&m_nerf.training.loss_type, LossTypeStr);
ImGui::Combo("Depth Loss", (int*)&m_nerf.training.depth_loss_type, LossTypeStr);
ImGui::Combo("RGB activation", (int*)&m_nerf.rgb_activation, NerfActivationStr);
ImGui::Combo("Density activation", (int*)&m_nerf.density_activation, NerfActivationStr);
ImGui::SliderFloat("Cone angle", &m_nerf.cone_angle_constant, 0.0f, 1.0f/128.0f);
ImGui::SliderFloat("Depth supervision strength", &m_nerf.training.depth_supervision_lambda, 0.f, 1.f);
// Importance sampling options, but still related to training
ImGui::Checkbox("Sample focal plane ~error", &m_nerf.training.sample_focal_plane_proportional_to_error);
ImGui::SameLine();
ImGui::Checkbox("Sample focal plane ~sharpness", &m_nerf.training.include_sharpness_in_error);
ImGui::Checkbox("Sample image ~error", &m_nerf.training.sample_image_proportional_to_error);