forked from NVlabs/instant-ngp
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathtestbed_nerf.cu
2785 lines (2309 loc) · 107 KB
/
testbed_nerf.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_nerf.cu
* @author Thomas Müller & Alex Evans, NVIDIA
*/
#include <neural-graphics-primitives/adam_optimizer.h>
#include <neural-graphics-primitives/common.h>
#include <neural-graphics-primitives/common_device.cuh>
#include <neural-graphics-primitives/envmap.cuh>
#include <neural-graphics-primitives/nerf_loader.h>
#include <neural-graphics-primitives/nerf_network.h>
#include <neural-graphics-primitives/marching_cubes.h>
#include <neural-graphics-primitives/render_buffer.h>
#include <neural-graphics-primitives/testbed.h>
#include <neural-graphics-primitives/trainable_buffer.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 <filesystem/directory.h>
#include <filesystem/path.h>
#ifdef copysign
#undef copysign
#endif
using namespace Eigen;
using namespace tcnn;
namespace fs = filesystem;
NGP_NAMESPACE_BEGIN
inline constexpr __device__ float NERF_RENDERING_NEAR_DISTANCE() { return 0.05f; }
inline constexpr __device__ uint32_t NERF_STEPS() { return 1024; } // finest number of steps per unit length
inline constexpr __device__ uint32_t NERF_CASCADES() { return 5; }
inline constexpr __device__ float SQRT3() { return 1.73205080757f; }
inline constexpr __device__ float STEPSIZE() { return (SQRT3() / NERF_STEPS()); } // for nerf raymarch
inline constexpr __device__ float MIN_CONE_STEPSIZE() { return STEPSIZE(); }
// Maximum step size is the width of the coarsest gridsize cell.
inline constexpr __device__ float MAX_CONE_STEPSIZE() { return STEPSIZE() * (1<<(NERF_CASCADES()-1)) * NERF_STEPS() / NERF_GRIDSIZE(); }
// Used to index into the PRNG stream. Must be larger than the number of
// samples consumed by any given training ray.
inline constexpr __device__ uint32_t N_MAX_RANDOM_SAMPLES_PER_RAY() { return 8; }
// Any alpha below this is considered "invisible" and is thus culled away.
inline constexpr __device__ float NERF_MIN_OPTICAL_THICKNESS() { return 0.01f; }
static constexpr uint32_t MARCH_ITER = 10000;
static constexpr uint32_t MIN_STEPS_INBETWEEN_COMPACTION = 1;
static constexpr uint32_t MAX_STEPS_INBETWEEN_COMPACTION = 8;
inline __host__ __device__ uint32_t grid_mip_offset(uint32_t mip) {
return (NERF_GRIDSIZE() * NERF_GRIDSIZE() * NERF_GRIDSIZE()) * mip;
}
inline __host__ __device__ float calc_cone_angle(float cosine, const Eigen::Vector2f& focal_length, float cone_angle_constant) {
// Pixel size. Doesn't always yield a good performance vs. quality
// trade off. Especially if training pixels have a much different
// size than rendering pixels.
// return cosine*cosine / focal_length.mean();
return cone_angle_constant;
}
inline __host__ __device__ float calc_dt(float t, float cone_angle) {
return tcnn::clamp(t*cone_angle, MIN_CONE_STEPSIZE(), MAX_CONE_STEPSIZE());
}
struct LossAndGradient {
Eigen::Array3f loss;
Eigen::Array3f gradient;
};
inline __device__ Array3f copysign(const Array3f& a, const Array3f& b) {
return {
copysignf(a.x(), b.x()),
copysignf(a.y(), b.y()),
copysignf(a.z(), b.z()),
};
}
inline __device__ LossAndGradient l2_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
return {
difference * difference,
2.0f * difference
};
}
inline __device__ LossAndGradient relative_l2_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
Array3f factor = (prediction * prediction + Array3f::Constant(1e-2f)).inverse();
return {
difference * difference * factor,
2.0f * difference * factor
};
}
inline __device__ LossAndGradient l1_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
return {
difference.abs(),
copysign(Array3f::Ones(), difference),
};
}
inline __device__ LossAndGradient smooth_l1_loss(const Array3f& target, const Array3f& prediction, float alpha = 1) {
Array3f difference = prediction - target;
Array3f abs_diff = difference.abs();
Array3f square = 0.5f/alpha * difference * difference;
return {
{
abs_diff.x() > alpha ? (abs_diff.x() - 0.5f * alpha) : square.x(),
abs_diff.y() > alpha ? (abs_diff.y() - 0.5f * alpha) : square.y(),
abs_diff.z() > alpha ? (abs_diff.z() - 0.5f * alpha) : square.z(),
},
{
abs_diff.x() > alpha ? (difference.x() > 0 ? 1.0f : -1.0f) : (difference.x() / alpha),
abs_diff.y() > alpha ? (difference.y() > 0 ? 1.0f : -1.0f) : (difference.y() / alpha),
abs_diff.z() > alpha ? (difference.z() > 0 ? 1.0f : -1.0f) : (difference.z() / alpha),
},
};
}
inline __device__ LossAndGradient log_l1_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
Array3f divisor = difference.abs() + Array3f::Ones();
return {
divisor.log(),
copysign(divisor.inverse(), difference),
};
}
inline __device__ LossAndGradient smape_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
Array3f factor = (0.5f * (prediction.abs() + target.abs()) + Array3f::Constant(1e-2f)).inverse();
return {
difference.abs() * factor,
copysign(factor, difference),
};
}
inline __device__ LossAndGradient mape_loss(const Array3f& target, const Array3f& prediction) {
Array3f difference = prediction - target;
Array3f factor = (prediction.abs() + Array3f::Constant(1e-2f)).inverse();
return {
difference.abs() * factor,
copysign(factor, difference),
};
}
inline __device__ float distance_to_next_voxel(const Vector3f& pos, const Vector3f& dir, const Vector3f& idir, uint32_t res) { // dda like step
Vector3f p = res * pos;
float tx = (floorf(p.x() + 0.5f + 0.5f * sign(dir.x())) - p.x()) * idir.x();
float ty = (floorf(p.y() + 0.5f + 0.5f * sign(dir.y())) - p.y()) * idir.y();
float tz = (floorf(p.z() + 0.5f + 0.5f * sign(dir.z())) - p.z()) * idir.z();
float t = min(min(tx, ty), tz);
return fmaxf(t / res, 0.0f);
}
inline __device__ float advance_to_next_voxel(float t, float cone_angle, const Vector3f& pos, const Vector3f& dir, const Vector3f& idir, uint32_t res) {
// Analytic stepping by a multiple of dt. Make empty space unequal to non-empty space
// due to the different stepping.
// float dt = calc_dt(t, cone_angle);
// return t + ceilf(fmaxf(distance_to_next_voxel(pos, dir, idir, res) / dt, 0.5f)) * dt;
// Regular stepping (may be slower but matches non-empty space)
float t_target = t + distance_to_next_voxel(pos, dir, idir, res);
do {
t += calc_dt(t, cone_angle);
} while (t < t_target);
return t;
}
__device__ float network_to_rgb(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return val;
case ENerfActivation::ReLU: return val > 0.0f ? val : 0.0f;
case ENerfActivation::Logistic: return tcnn::logistic(val);
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -10.0f, 10.0f));
default: assert(false);
}
return 0.0f;
}
__device__ float network_to_rgb_derivative(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return 1.0f;
case ENerfActivation::ReLU: return val > 0.0f ? 1.0f : 0.0f;
case ENerfActivation::Logistic: { float density = tcnn::logistic(val); return density * (1 - density); };
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -10.0f, 10.0f));
default: assert(false);
}
return 0.0f;
}
__device__ float network_to_density(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return val;
case ENerfActivation::ReLU: return val > 0.0f ? val : 0.0f;
case ENerfActivation::Logistic: return tcnn::logistic(val);
case ENerfActivation::Exponential: return __expf(val);
default: assert(false);
}
return 0.0f;
}
__device__ float network_to_density_derivative(float val, ENerfActivation activation) {
switch (activation) {
case ENerfActivation::None: return 1.0f;
case ENerfActivation::ReLU: return val > 0.0f ? 1.0f : 0.0f;
case ENerfActivation::Logistic: { float density = tcnn::logistic(val); return density * (1 - density); };
case ENerfActivation::Exponential: return __expf(tcnn::clamp(val, -15.0f, 15.0f));
default: assert(false);
}
return 0.0f;
}
__device__ Array3f network_to_rgb(const tcnn::vector_t<tcnn::network_precision_t, 4>& local_network_output, ENerfActivation activation) {
return {
network_to_rgb(float(local_network_output[0]), activation),
network_to_rgb(float(local_network_output[1]), activation),
network_to_rgb(float(local_network_output[2]), activation)
};
}
__device__ Vector3f warp_position(const Vector3f& pos, const BoundingBox& aabb) {
// return {tcnn::logistic(pos.x() - 0.5f), tcnn::logistic(pos.y() - 0.5f), tcnn::logistic(pos.z() - 0.5f)};
// return pos;
return aabb.relative_pos(pos);
}
__device__ Vector3f unwarp_position(const Vector3f& pos, const BoundingBox& aabb) {
// return {logit(pos.x()) + 0.5f, logit(pos.y()) + 0.5f, logit(pos.z()) + 0.5f};
// return pos;
return aabb.min + pos.cwiseProduct(aabb.diag());
}
__device__ Vector3f unwarp_position_derivative(const Vector3f& pos, const BoundingBox& aabb) {
// return {logit(pos.x()) + 0.5f, logit(pos.y()) + 0.5f, logit(pos.z()) + 0.5f};
// return pos;
return aabb.diag();
}
__device__ Vector3f warp_position_derivative(const Vector3f& pos, const BoundingBox& aabb) {
return unwarp_position_derivative(pos, aabb).cwiseInverse();
}
__device__ Vector3f warp_direction(const Vector3f& dir) {
return (dir + Vector3f::Ones()) * 0.5f;
}
__device__ Vector3f unwarp_direction(const Vector3f& dir) {
return dir * 2.0f - Vector3f::Ones();
}
__device__ Vector3f warp_direction_derivative(const Vector3f& dir) {
return Vector3f::Constant(0.5f);
}
__device__ Vector3f unwarp_direction_derivative(const Vector3f& dir) {
return Vector3f::Constant(2.0f);
}
__device__ float warp_dt(float dt) {
float max_stepsize = MIN_CONE_STEPSIZE() * (1<<(NERF_CASCADES()-1));
return (dt - MIN_CONE_STEPSIZE()) / (max_stepsize - MIN_CONE_STEPSIZE());
}
__device__ float unwarp_dt(float dt) {
float max_stepsize = MIN_CONE_STEPSIZE() * (1<<(NERF_CASCADES()-1));
return dt * (max_stepsize - MIN_CONE_STEPSIZE()) + MIN_CONE_STEPSIZE();
}
__device__ uint32_t cascaded_grid_idx_at(Vector3f pos, uint32_t mip) {
float mip_scale = scalbnf(1.0f, -mip);
pos -= Vector3f::Constant(0.5f);
pos *= mip_scale;
pos += Vector3f::Constant(0.5f);
Vector3i i = (pos * NERF_GRIDSIZE()).cast<int>();
if (i.x() < -1 || i.x() > NERF_GRIDSIZE() || i.y() < -1 || i.y() > NERF_GRIDSIZE() || i.z() < -1 || i.z() > NERF_GRIDSIZE()) {
printf("WTF %d %d %d\n", i.x(), i.y(), i.z());
}
uint32_t idx = tcnn::morton3D(
tcnn::clamp(i.x(), 0, (int)NERF_GRIDSIZE()-1),
tcnn::clamp(i.y(), 0, (int)NERF_GRIDSIZE()-1),
tcnn::clamp(i.z(), 0, (int)NERF_GRIDSIZE()-1)
);
return idx;
}
__device__ bool density_grid_occupied_at(const Vector3f& pos, const uint8_t* density_grid_bitfield, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
return density_grid_bitfield[idx/8+grid_mip_offset(mip)/8] & (1<<(idx%8));
}
__device__ float cascaded_grid_at(Vector3f pos, const float* cascaded_grid, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
return cascaded_grid[idx+grid_mip_offset(mip)];
}
__device__ float& cascaded_grid_at(Vector3f pos, float* cascaded_grid, uint32_t mip) {
uint32_t idx = cascaded_grid_idx_at(pos, mip);
return cascaded_grid[idx+grid_mip_offset(mip)];
}
__global__ void extract_srgb_with_activation(const uint32_t n_elements, const uint32_t rgb_stride, const float* __restrict__ rgbd, float* __restrict__ rgb, ENerfActivation rgb_activation, bool from_linear) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
const uint32_t elem_idx = i / 3;
const uint32_t dim_idx = i - elem_idx * 3;
float c = network_to_rgb(rgbd[elem_idx*4 + dim_idx], rgb_activation);
if (from_linear) {
c = linear_to_srgb(c);
}
rgb[elem_idx*rgb_stride + dim_idx] = c;
}
__global__ void mark_untrained_density_grid(const uint32_t n_elements, float* __restrict__ grid_out,
const uint32_t n_training_images,
const Vector2f* __restrict__ focal_lengths,
const Matrix<float, 3, 4>* training_xforms,
Vector2i resolution
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint32_t level = i / (NERF_GRIDSIZE()*NERF_GRIDSIZE()*NERF_GRIDSIZE());
uint32_t pos_idx = i % (NERF_GRIDSIZE()*NERF_GRIDSIZE()*NERF_GRIDSIZE());
uint32_t x = tcnn::morton3D_invert(pos_idx>>0);
uint32_t y = tcnn::morton3D_invert(pos_idx>>1);
uint32_t z = tcnn::morton3D_invert(pos_idx>>2);
float half_resx=resolution.x()*0.5f;
float half_resy=resolution.y()*0.5f;
Vector3f pos = ((Vector3f{(float)x+0.5f, (float)y+0.5f, (float)z+0.5f}) / NERF_GRIDSIZE() - Vector3f::Constant(0.5f)) * scalbnf(1.0f, level) + Vector3f::Constant(0.5f);
float voxel_radius = 0.5f*SQRT3()*scalbnf(1.0f, level) / NERF_GRIDSIZE();
int count=0;
for (uint32_t j=0; j < n_training_images; ++j) {
Matrix<float, 3, 4> xform = training_xforms[j];
Vector3f ploc = pos-xform.col(3);
float x=ploc.dot(xform.col(0));
float y=ploc.dot(xform.col(1));
float z=ploc.dot(xform.col(2));
if (z>0.f) {
auto focal = focal_lengths[j];
// TODO - add a box / plane intersection to stop thomas from murdering me
if (fabsf(x)-voxel_radius < z/focal.x()*half_resx && fabsf(y)-voxel_radius < z/focal.y()*half_resy) {
count++;
if (count > 0) break;
}
}
}
grid_out[i] = (count > 0) ? 0.f : -1.f;
}
__global__ void generate_grid_samples_nerf_uniform(Eigen::Vector3i res_3d, const uint32_t step, BoundingBox render_aabb, BoundingBox train_aabb, NerfPosition* __restrict__ out) {
// check grid_in for negative values -> must be negative on output
uint32_t x = threadIdx.x + blockIdx.x * blockDim.x;
uint32_t y = threadIdx.y + blockIdx.y * blockDim.y;
uint32_t z = threadIdx.z + blockIdx.z * blockDim.z;
if (x>=res_3d.x() || y>=res_3d.y() || z>=res_3d.z())
return;
uint32_t i = x+ y*res_3d.x() + z*res_3d.x()*res_3d.y();
Vector3f pos = Array3f{(float)x, (float)y, (float)z} * Array3f{1.f/res_3d.x(),1.f/res_3d.y(),1.f/res_3d.z()};
pos = pos.cwiseProduct(render_aabb.max - render_aabb.min) + render_aabb.min;
out[i] = { warp_position(pos, train_aabb), warp_dt(MIN_CONE_STEPSIZE()) };
}
inline __device__ int mip_from_pos(const Vector3f& pos) {
int exponent;
float maxval = (pos - Vector3f::Constant(0.5f)).cwiseAbs().maxCoeff();
frexpf(maxval, &exponent);
return min(NERF_CASCADES()-1, max(0, exponent+1));
}
inline __device__ int mip_from_dt(float dt, const Vector3f& pos) {
int mip = mip_from_pos(pos);
dt *= 2*NERF_GRIDSIZE();
if (dt<1.f) return mip;
int exponent;
frexpf(dt, &exponent);
return min(NERF_CASCADES()-1, max(exponent, mip));
}
__global__ void generate_grid_samples_nerf_nonuniform(const uint32_t n_elements, default_rng_t rng, const uint32_t step, BoundingBox aabb, const float* __restrict__ grid_in, NerfPosition* __restrict__ out, uint32_t* __restrict__ indices, uint32_t n_cascades, float thresh) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
// 1 random number to select the level, 3 to select the position.
rng.advance(i*4);
uint32_t level = (uint32_t)(random_val(rng) * n_cascades) % n_cascades;
// Select grid cell that has density
uint32_t idx;
for (uint32_t j = 0; j < 10; ++j) {
idx = ((i+step*n_elements) * 56924617 + j * 19349663 + 96925573) % (NERF_GRIDSIZE()*NERF_GRIDSIZE()*NERF_GRIDSIZE());
idx += level * NERF_GRIDSIZE()*NERF_GRIDSIZE()*NERF_GRIDSIZE();
if (grid_in[idx] > thresh) {
break;
}
}
// Random position within that cellq
uint32_t pos_idx = idx % (NERF_GRIDSIZE()*NERF_GRIDSIZE()*NERF_GRIDSIZE());
uint32_t x = tcnn::morton3D_invert(pos_idx>>0);
uint32_t y = tcnn::morton3D_invert(pos_idx>>1);
uint32_t z = tcnn::morton3D_invert(pos_idx>>2);
Vector3f pos = ((Vector3f{(float)x, (float)y, (float)z} + random_val_3d(rng)) / NERF_GRIDSIZE() - Vector3f::Constant(0.5f)) * scalbnf(1.0f, level) + Vector3f::Constant(0.5f);
out[i] = { warp_position(pos, aabb), warp_dt(MIN_CONE_STEPSIZE()) };
indices[i] = idx;
}
__global__ void splat_grid_samples_nerf_max_nearest_neighbor(const uint32_t n_elements, const uint32_t* __restrict__ indices, int padded_output_width, const tcnn::network_precision_t* network_output, float* __restrict__ grid_out, ENerfActivation rgb_activation, ENerfActivation density_activation) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint32_t local_idx = indices[i];
// Current setting: optical thickness of the smallest possible stepsize.
// Uncomment for: optical thickness of the ~expected step size when the observer is in the middle of the scene
uint32_t level = 0;//local_idx / (NERF_GRIDSIZE() * NERF_GRIDSIZE() * NERF_GRIDSIZE());
float mlp = network_to_density(float(network_output[i * padded_output_width]), density_activation);
float optical_thickness = mlp * scalbnf(MIN_CONE_STEPSIZE(), level);
// Positive floats are monotonically ordered when their bit pattern is interpretes as uint.
// uint atomicMax is thus perfectly acceptable.
atomicMax((uint32_t*)&grid_out[local_idx], __float_as_uint(optical_thickness));
}
__global__ void grid_samples_half_to_float(const uint32_t n_elements, BoundingBox aabb, float *dst, int padded_output_width, const tcnn::network_precision_t* network_output, ENerfActivation density_activation, const NerfPosition* __restrict__ coords_in, const float* __restrict__ grid_in) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
// let's interpolate for marching cubes based on the raw MLP output, not the density (exponentiated) version
//float mlp = network_to_density(float(network_output[i * padded_output_width]), density_activation);
float mlp = float(network_output[i * padded_output_width]);
if (grid_in) {
Vector3f pos = unwarp_position(coords_in[i].p, aabb);
float grid_density = cascaded_grid_at(pos, grid_in, mip_from_pos(pos));
if (grid_density < NERF_MIN_OPTICAL_THICKNESS()) {
mlp = -10000.f;
}
}
dst[i] = mlp;
}
__global__ void ema_grid_samples_nerf(const uint32_t n_elements,
float decay,
const uint32_t count,
float* __restrict__ grid_out,
const float* __restrict__ grid_in
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
float importance = grid_in[i];
// float ema_debias_old = 1 - (float)powf(decay, count);
// float ema_debias_new = 1 - (float)powf(decay, count+1);
// float filtered_val = ((grid_out[i] * decay * ema_debias_old + importance * (1 - decay)) / ema_debias_new);
// grid_out[i] = filtered_val;
// Maximum instead of EMA allows capture of very thin features.
// Basically, we want the grid cell turned on as soon as _ANYTHING_ visible is in there.
float prev_val = grid_out[i];
float val = (prev_val<0.f) ? prev_val : fmaxf(prev_val * decay, importance);
grid_out[i] = val;
}
__global__ void decay_sharpness_grid_nerf(const uint32_t n_elements, float decay, float* __restrict__ grid) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
grid[i] *= decay;
}
__global__ void grid_to_bitfield(const uint32_t n_elements,
const float* __restrict__ grid,
uint8_t* __restrict__ grid_bitfield,
const float* __restrict__ mean_density_ptr
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint8_t bits = 0;
float thresh = std::min(NERF_MIN_OPTICAL_THICKNESS(), *mean_density_ptr);
#pragma unroll
for (uint8_t j = 0; j < 8; ++j) {
bits |= grid[i*8+j] > thresh ? ((uint8_t)1 << j) : 0;
}
grid_bitfield[i] = bits;
}
__global__ void bitfield_max_pool(const uint32_t n_elements,
const uint8_t* __restrict__ prev_level,
uint8_t* __restrict__ next_level
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
uint8_t bits = 0;
#pragma unroll
for (uint8_t j = 0; j < 8; ++j) {
// If any bit is set in the previous level, set this
// level's bit. (Max pooling.)
bits |= prev_level[i*8+j] > 0 ? ((uint8_t)1 << j) : 0;
}
uint32_t x = tcnn::morton3D_invert(i>>0) + NERF_GRIDSIZE()/8;
uint32_t y = tcnn::morton3D_invert(i>>1) + NERF_GRIDSIZE()/8;
uint32_t z = tcnn::morton3D_invert(i>>2) + NERF_GRIDSIZE()/8;
next_level[tcnn::morton3D(x, y, z)] |= bits;
}
__global__ void advance_pos_nerf(
const uint32_t n_elements,
BoundingBox render_aabb,
Vector3f camera_fwd,
Vector2f focal_length,
uint32_t spp,
NerfPayload* __restrict__ payloads,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
float cone_angle_constant
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
NerfPayload& payload = payloads[i];
if (!payload.alive) {
return;
}
Vector3f origin = payload.origin;
Vector3f dir = payload.dir;
Vector3f idir = dir.cwiseInverse();
float cone_angle = calc_cone_angle(dir.dot(camera_fwd), focal_length, cone_angle_constant);
float t = payload.t;
float dt = calc_dt(t, cone_angle);
t += ld_random_val(spp, i * 786433) * dt;
Vector3f pos;
while (1) {
if (!render_aabb.contains(pos = origin + dir * t)) {
payload.alive = false;
break;
}
dt = calc_dt(t, cone_angle);
uint32_t mip = max(min_mip, mip_from_dt(dt, pos));
if (!density_grid || density_grid_occupied_at(pos, density_grid, mip)) {
break;
}
uint32_t res = NERF_GRIDSIZE()>>mip;
t = advance_to_next_voxel(t, cone_angle, pos, dir, idir, res);
}
payload.t = t;
}
__global__ void generate_nerf_network_inputs_from_positions(const uint32_t n_elements, BoundingBox aabb, const Vector3f* __restrict__ pos, NerfCoordinate* __restrict__ network_input) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
Vector3f dir=(pos[i]-Vector3f::Constant(0.5f)).normalized(); // choose outward pointing directions, for want of a better choice
network_input[i] = { warp_position(pos[i], aabb), warp_direction(dir), warp_dt(MIN_CONE_STEPSIZE()) };
}
__global__ void generate_nerf_network_inputs_at_current_position(const uint32_t n_elements, BoundingBox aabb, const NerfPayload* __restrict__ payloads, NerfCoordinate* __restrict__ network_input) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
Vector3f dir = payloads[i].dir;
network_input[i] = { warp_position(payloads[i].origin + dir * payloads[i].t, aabb), warp_direction(dir), warp_dt(MIN_CONE_STEPSIZE()) };
}
__global__ void compute_nerf_density(const uint32_t n_elements, Array4f* network_output, ENerfActivation rgb_activation, ENerfActivation density_activation) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
Array4f rgba = network_output[i];
rgba.w() = tcnn::clamp(1.f - __expf(-network_to_density(rgba.w(), density_activation) / 100.0f), 0.0f, 1.0f);
rgba.x() = network_to_rgb(rgba.x(), rgb_activation) * rgba.w();
rgba.y() = network_to_rgb(rgba.y(), rgb_activation) * rgba.w();
rgba.z() = network_to_rgb(rgba.z(), rgb_activation) * rgba.w();
network_output[i] = rgba;
}
__global__ void generate_next_nerf_network_inputs(
const uint32_t n_elements,
BoundingBox render_aabb,
BoundingBox train_aabb,
Vector2f focal_length,
Vector3f camera_fwd,
NerfPayload* __restrict__ payloads,
NerfCoordinate* __restrict__ network_input,
uint32_t n_steps,
const uint8_t* __restrict__ density_grid,
uint32_t min_mip,
float cone_angle_constant
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
NerfPayload& payload = payloads[i];
if (!payload.alive) {
return;
}
Vector3f origin = payload.origin;
Vector3f dir = payload.dir;
Vector3f idir = dir.cwiseInverse();
float cone_angle = calc_cone_angle(dir.dot(camera_fwd), focal_length, cone_angle_constant);
float t = payload.t;
for (uint32_t j = 0; j < n_steps; ++j) {
Vector3f pos;
float dt = 0.0f;
while (1) {
if (!render_aabb.contains(pos = origin + dir * t)) {
payload.n_steps = j;
return;
}
dt = calc_dt(t, cone_angle);
uint32_t mip = max(min_mip, mip_from_dt(dt, pos));
if (!density_grid || density_grid_occupied_at(pos, density_grid, mip)) {
break;
}
uint32_t res = NERF_GRIDSIZE()>>mip;
t = advance_to_next_voxel(t, cone_angle, pos, dir, idir, res);
}
network_input[i*n_steps + j] = { warp_position(pos, train_aabb), warp_direction(dir), warp_dt(dt) }; // XXXCONE
t += dt;
}
payload.t = t;
payload.n_steps = n_steps;
}
__global__ void composite_kernel_nerf(
const uint32_t n_elements,
const uint32_t current_step,
BoundingBox aabb,
const uint32_t n_training_images,
const Matrix<float, 3, 4>* training_xforms,
Matrix<float, 3, 4> camera_matrix,
Vector2f focal_length,
float depth_scale,
Array4f* rgba,
NerfPayload* payloads,
const NerfCoordinate* network_input,
const tcnn::network_precision_t* network_output,
uint32_t padded_output_width,
uint32_t n_steps,
ERenderMode render_mode,
const uint8_t* density_grid,
ENerfActivation rgb_activation,
ENerfActivation density_activation,
int show_accel,
float min_alpha
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_elements) return;
NerfPayload& payload = payloads[i];
if (!payload.alive) {
return;
}
Array4f local_rgba = rgba[i];
Vector3f origin = payload.origin;
Vector3f cam_fwd = camera_matrix.col(2);
// Composite in the last n steps
uint32_t actual_n_steps = payload.n_steps;
uint32_t j = 0;
for (; j < actual_n_steps; ++j) {
const tcnn::vector_t<tcnn::network_precision_t, 4> local_network_output = *(tcnn::vector_t<tcnn::network_precision_t, 4>*)&network_output[(i*n_steps+j)*padded_output_width];
Vector3f warped_pos = network_input[i*n_steps+j].pos.p;
Vector3f pos = unwarp_position(warped_pos, aabb);
//Vector3f pos2 = pos-Vector3f::Constant(0.5f);
//float fog_scale = 1.f/max(1.f,pos2.dot(pos2)*4.f);
float T = 1.f - local_rgba.w();
float dt = unwarp_dt(network_input[i*n_steps+j].dt);
float alpha = 1.f - __expf(-network_to_density(float(local_network_output[3]), density_activation) * dt /* * fog_scale*/);
if (show_accel>=0)
alpha=1.f;
float weight = alpha * T;
Array3f rgb = network_to_rgb(local_network_output, rgb_activation);
if (render_mode == ERenderMode::Normals) {
// Network input contains the gradient of the network output w.r.t. input.
// So to compute density gradients, we need to apply the chain rule.
// The normal is then in the opposite direction of the density gradient (i.e. the direction of decreasing density)
Vector3f normal = -network_to_density_derivative(float(local_network_output[3]), density_activation) * warped_pos;
rgb = normal.normalized().array();
} else if (render_mode == ERenderMode::Positions || render_mode == ERenderMode::EncodingVis) {
if (show_accel>=0) {
uint32_t mip = max(show_accel, mip_from_pos(pos));
uint32_t res = NERF_GRIDSIZE() >> mip;
int ix = pos.x()*(res);
int iy = pos.y()*(res);
int iz = pos.z()*(res);
default_rng_t rng(ix+iy*232323+iz*727272);
rgb.x() = 1.f-mip*(1.f/(NERF_CASCADES()-1));
rgb.y() = rng.next_float();
rgb.z() = rng.next_float();
} else {
rgb = pos.array();
}
} else if (render_mode == ERenderMode::Depth) {
float z=cam_fwd.dot(pos-origin) * depth_scale;
rgb = {z,z,z};
} else if (render_mode == ERenderMode::Distance) {
float z=(pos-origin).norm() * depth_scale;
rgb = {z,z,z};
} else if (render_mode == ERenderMode::Stepsize) {
float warped_dt = warp_dt(dt);
rgb = {warped_dt,warped_dt,warped_dt};
} else if (render_mode == ERenderMode::AO) {
rgb = Array3f::Constant(alpha);
}
local_rgba.head<3>() += rgb * weight;
local_rgba.w() += weight;
if (local_rgba.w() > (1.0f - min_alpha)) {
rgba[i] = local_rgba / local_rgba.w();
break;
}
}
if (j < n_steps) {
payload.alive = false;
payload.n_steps = j + current_step;
}
rgba[i] = local_rgba;
}
static constexpr float UNIFORM_SAMPLING_FRACTION = 0.5f;
inline __device__ Vector2f sample_cdf_2d(Vector2f sample, uint32_t img, const Vector2i& res, const float* __restrict__ cdf_x_cond_y, const float* __restrict__ cdf_y, float* __restrict__ pdf) {
if (sample.x() < UNIFORM_SAMPLING_FRACTION) {
sample.x() /= UNIFORM_SAMPLING_FRACTION;
return sample;
}
sample.x() = (sample.x() - UNIFORM_SAMPLING_FRACTION) / (1.0f - UNIFORM_SAMPLING_FRACTION);
cdf_y += img * res.y();
// First select row according to cdf_y
uint32_t y = binary_search(sample.y(), cdf_y, res.y());
float prev = y > 0 ? cdf_y[y-1] : 0.0f;
float pmf_y = cdf_y[y] - prev;
sample.y() = (sample.y() - prev) / pmf_y;
cdf_x_cond_y += img * res.y() * res.x() + y * res.x();
// Then, select col according to x
uint32_t x = binary_search(sample.x(), cdf_x_cond_y, res.x());
prev = x > 0 ? cdf_x_cond_y[x-1] : 0.0f;
float pmf_x = cdf_x_cond_y[x] - prev;
sample.x() = (sample.x() - prev) / pmf_x;
if (pdf) {
*pdf = pmf_x * pmf_y * res.prod();
}
return {((float)x + sample.x()) / (float)res.x(), ((float)y + sample.y()) / (float)res.y()};
}
inline __device__ float pdf_2d(Vector2f sample, uint32_t img, const Vector2i& res, const float* __restrict__ cdf_x_cond_y, const float* __restrict__ cdf_y) {
Vector2i p = (sample.cwiseProduct(res.cast<float>())).cast<int>().cwiseMax(0).cwiseMin(res - Vector2i::Ones());
cdf_y += img * res.y();
cdf_x_cond_y += img * res.y() * res.x() + p.y() * res.x();
float pmf_y = cdf_y[p.y()];
if (p.y() > 0) {
pmf_y -= cdf_y[p.y()-1];
}
float pmf_x = cdf_x_cond_y[p.x()];
if (p.x() > 0) {
pmf_x -= cdf_x_cond_y[p.x()-1];
}
// Probability mass of picking the pixel
float pmf = pmf_x * pmf_y;
// To convert to probability density, divide by area of pixel
return UNIFORM_SAMPLING_FRACTION + pmf * res.prod() * (1.0f - UNIFORM_SAMPLING_FRACTION);
}
inline __device__ Vector2f nerf_random_image_pos_training(default_rng_t& rng, const Vector2i& resolution, bool snap_to_pixel_centers, const float* __restrict__ cdf_x_cond_y, const float* __restrict__ cdf_y, const Vector2i& cdf_res, uint32_t img, float* __restrict__ pdf = nullptr) {
Vector2f xy = random_val_2d(rng);
if (cdf_x_cond_y) {
xy = sample_cdf_2d(xy, img, cdf_res, cdf_x_cond_y, cdf_y, pdf);
} else if (pdf) {
*pdf = 1.0f;
}
if (snap_to_pixel_centers) {
xy = (xy.cwiseProduct(resolution.cast<float>()).cast<int>().cwiseMax(0).cwiseMin(resolution - Vector2i::Ones()).cast<float>() + Vector2f::Constant(0.5f)).cwiseQuotient(resolution.cast<float>());
}
return xy;
}
inline __device__ uint32_t image_idx(uint32_t base_idx, uint32_t n_rays, uint32_t n_rays_total, uint32_t n_training_images, const float* __restrict__ cdf = nullptr, float* __restrict__ pdf = nullptr) {
if (cdf) {
float sample = ld_random_val(base_idx + n_rays_total, 0xdeadbeef);
// float sample = random_val(base_idx + n_rays_total);
uint32_t img = binary_search(sample, cdf, n_training_images);
if (pdf) {
float prev = img > 0 ? cdf[img-1] : 0.0f;
*pdf = (cdf[img] - prev) * n_training_images;
}
return img;
}
// return ((base_idx + n_rays_total) * 56924617 + 96925573) % n_training_images;
// Neighboring threads in the warp process the same image. Increases locality.
if (pdf) {
*pdf = 1.0f;
}
return (((base_idx + n_rays_total) * n_training_images) / n_rays) % n_training_images;
}
inline __device__ Vector2i image_pos(const Vector2f& pos, const Vector2i& resolution) {
return pos.cwiseProduct(resolution.cast<float>()).cast<int>().cwiseMin(resolution - Vector2i::Constant(1)).cwiseMax(0);
}
inline __device__ uint64_t pixel_idx(const Vector2i& pos, const Vector2i& resolution, uint32_t img) {
return pos.x() + pos.y() * resolution.x() + img * (uint64_t)resolution.x() * resolution.y();
}
inline __device__ uint64_t pixel_idx(const Vector2f& xy, const Vector2i& resolution, uint32_t img) {
return pixel_idx(image_pos(xy, resolution), resolution, img);
}
__global__ void generate_training_samples_nerf(
const uint32_t n_rays,
BoundingBox aabb,
const uint32_t max_samples,
const uint32_t n_rays_total,
default_rng_t rng,
const Ray* __restrict__ rays_in,
uint32_t* __restrict__ ray_counter,
uint32_t* __restrict__ numsteps_counter,
uint32_t* __restrict__ ray_indices_out,
Ray* __restrict__ rays_out,
uint32_t* __restrict__ numsteps_out,
NerfCoordinate* __restrict__ coords_out,
Vector2i resolution,
const uint32_t n_training_images,
Vector2f principal_point,
const Vector2f* __restrict__ focal_lengths,
const Matrix<float, 3, 4>* training_xforms,
CameraDistortion camera_distortion,
const uint8_t* __restrict__ density_grid,
bool max_level_rand_training,
float* __restrict__ max_level_ptr,
bool snap_to_pixel_centers,
bool train_envmap,
float cone_angle_constant,
const float* __restrict__ distortion_data,
const Vector2i distortion_resolution,
const float* __restrict__ cdf_x_cond_y,
const float* __restrict__ cdf_y,
const float* __restrict__ cdf_img,
const Vector2i cdf_res,
float near_distance,
const __half* __restrict__ training_images
) {
const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= n_rays) return;
uint32_t img = image_idx(i, n_rays, n_rays_total, n_training_images, cdf_img);
rng.advance(i * N_MAX_RANDOM_SAMPLES_PER_RAY());
Vector2f xy = nerf_random_image_pos_training(rng, resolution, snap_to_pixel_centers, cdf_x_cond_y, cdf_y, cdf_res, img);
// Negative values indicate masked-away regions
if ((float)training_images[pixel_idx(xy, resolution, img)*4] < 0.0f) {
return;
}
float max_level = max_level_rand_training ? (random_val(rng) * 2.0f) : 1.0f; // Multiply by 2 to ensure 50% of training is at max level
Matrix<float, 3, 4> xform = training_xforms[img];
Vector2f focal_length = focal_lengths[img];
Ray ray;
if (rays_in) {
// Rays have been explicitly supplied. Read them.
ray = rays_in[pixel_idx(xy, resolution, img)];
} else {
// Rays need to be inferred from the camera matrix
ray.o = xform.col(3);
ray.d = {
(xy.x()-principal_point.x())*resolution.x() / focal_length.x(),
(xy.y()-principal_point.y())*resolution.y() / focal_length.y(),
1.0f,
};
if (!camera_distortion.is_zero()) {
iterative_camera_undistortion((float*)&camera_distortion, &ray.d.x(), &ray.d.y());
}
if (distortion_data) {
ray.d.head<2>() += read_image<2>(distortion_data, distortion_resolution, xy);
}
ray.d = (xform.block<3, 3>(0, 0) * ray.d).normalized();
}
Vector2f tminmax = aabb.ray_intersect(ray.o, ray.d);
float cone_angle = calc_cone_angle(ray.d.dot(xform.col(2)), focal_length, cone_angle_constant);
// The near distance prevents learning of camera-specific fudge right in front of the camera
tminmax.x() = fmaxf(tminmax.x(), near_distance);
float startt = tminmax.x();
startt += calc_dt(startt, cone_angle) * random_val(rng);
Vector3f idir = ray.d.cwiseInverse();
// first pass to compute an accurate number of steps
uint32_t j = 0;
float t=startt;
Vector3f pos;
while (aabb.contains(pos = ray.o + t * ray.d) && j < NERF_STEPS()) {