-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathsplat_data.cpp
More file actions
1622 lines (1418 loc) · 74.7 KB
/
splat_data.cpp
File metadata and controls
1622 lines (1418 loc) · 74.7 KB
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
/* SPDX-FileCopyrightText: 2025 LichtFeld Studio Authors
*
* SPDX-License-Identifier: GPL-3.0-or-later */
#include "core/splat_data.hpp"
#include "core/cuda/sh_layout.cuh"
#include "core/logger.hpp"
#include "core/parameters.hpp"
#include "core/point_cloud.hpp"
#include "core/tensor/internal/tensor_serialization.hpp"
#include "nanoflann.hpp"
#include <algorithm>
#include <cmath>
#include <cuda_runtime.h>
#include <expected>
#include <format>
#include <vector>
namespace {
constexpr int MAX_SUPPORTED_SH_DEGREE = 3;
constexpr size_t SH_CHANNELS = 3;
template <typename Index>
[[nodiscard]] std::vector<lfs::core::SplatData::FrozenRange> remap_frozen_ranges_after_keep(
const std::vector<lfs::core::SplatData::FrozenRange>& ranges,
const size_t old_size,
const std::vector<Index>& kept_indices) {
if (ranges.empty() || old_size == 0 || kept_indices.empty()) {
return {};
}
std::vector<unsigned char> old_frozen(old_size, 0);
for (const auto& range : ranges) {
if (range.count == 0 || range.start >= old_size) {
continue;
}
const size_t end = range.count > old_size - range.start
? old_size
: range.start + range.count;
std::fill(old_frozen.begin() + static_cast<std::ptrdiff_t>(range.start),
old_frozen.begin() + static_cast<std::ptrdiff_t>(end),
1);
}
std::vector<lfs::core::SplatData::FrozenRange> remapped;
size_t range_start = 0;
while (range_start < kept_indices.size()) {
while (range_start < kept_indices.size()) {
const auto old_index = kept_indices[range_start];
if (old_index >= 0 &&
static_cast<size_t>(old_index) < old_frozen.size() &&
old_frozen[static_cast<size_t>(old_index)]) {
break;
}
++range_start;
}
if (range_start >= kept_indices.size()) {
break;
}
size_t range_end = range_start + 1;
while (range_end < kept_indices.size()) {
const auto old_index = kept_indices[range_end];
if (old_index < 0 ||
static_cast<size_t>(old_index) >= old_frozen.size() ||
!old_frozen[static_cast<size_t>(old_index)]) {
break;
}
++range_end;
}
remapped.push_back({range_start, range_end - range_start});
range_start = range_end;
}
return remapped;
}
// Point cloud adaptor for nanoflann
struct PointCloudAdaptor {
const float* points;
size_t num_points;
PointCloudAdaptor(const float* pts, size_t n)
: points(pts),
num_points(n) {}
inline size_t kdtree_get_point_count() const { return num_points; }
inline float kdtree_get_pt(const size_t idx, const size_t dim) const {
return points[idx * 3 + dim];
}
template <class BBOX>
bool kdtree_get_bbox(BBOX& /* bb */) const { return false; }
};
using KDTree = nanoflann::KDTreeSingleIndexAdaptor<
nanoflann::L2_Simple_Adaptor<float, PointCloudAdaptor>,
PointCloudAdaptor,
3>;
/**
* @brief Compute mean distance to 3 nearest neighbors for each point
*/
lfs::core::Tensor compute_mean_neighbor_distances(const lfs::core::Tensor& points) {
auto cpu_points = points.cpu();
const int num_points = cpu_points.size(0);
if (cpu_points.ndim() != 2 || cpu_points.size(1) != 3) {
LOG_ERROR("Input points must have shape [N, 3], got {}", cpu_points.shape().str());
return lfs::core::Tensor();
}
if (cpu_points.dtype() != lfs::core::DataType::Float32) {
LOG_ERROR("Input points must be float32");
return lfs::core::Tensor();
}
if (num_points <= 1) {
return lfs::core::Tensor::full({static_cast<size_t>(num_points)}, 0.01f, points.device());
}
const float* data = cpu_points.ptr<float>();
PointCloudAdaptor cloud(data, num_points);
KDTree index(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10));
index.buildIndex();
auto result = lfs::core::Tensor::zeros({static_cast<size_t>(num_points)}, lfs::core::Device::CPU);
float* result_data = result.ptr<float>();
#pragma omp parallel for if (num_points > 1000)
for (int i = 0; i < num_points; i++) {
const float query_pt[3] = {
data[i * 3 + 0],
data[i * 3 + 1],
data[i * 3 + 2]};
const size_t num_results = std::min(4, num_points);
std::vector<size_t> ret_indices(num_results);
std::vector<float> out_dists_sqr(num_results);
nanoflann::KNNResultSet<float> resultSet(num_results);
resultSet.init(&ret_indices[0], &out_dists_sqr[0]);
index.findNeighbors(resultSet, &query_pt[0], nanoflann::SearchParameters(10));
float sum_dist = 0.0f;
int valid_neighbors = 0;
for (size_t j = 0; j < num_results && valid_neighbors < 3; j++) {
if (out_dists_sqr[j] > 1e-8f) {
sum_dist += std::sqrt(out_dists_sqr[j]);
valid_neighbors++;
}
}
result_data[i] = (valid_neighbors > 0) ? (sum_dist / valid_neighbors) : 0.01f;
}
return result.to(points.device());
}
lfs::core::Tensor compute_mrnf_knn_log_scales(const lfs::core::Tensor& points) {
auto cpu_points = points.cpu();
const int num_points = cpu_points.size(0);
if (cpu_points.ndim() != 2 || cpu_points.size(1) != 3) {
LOG_ERROR("Input points must have shape [N, 3], got {}", cpu_points.shape().str());
return lfs::core::Tensor();
}
if (cpu_points.dtype() != lfs::core::DataType::Float32) {
LOG_ERROR("Input points must be float32");
return lfs::core::Tensor();
}
// Match MRNF: if there are too few points, use log_scale=0.
if (num_points < 3) {
auto zeros = lfs::core::Tensor::zeros(
{static_cast<size_t>(num_points), 3},
lfs::core::Device::CPU);
return zeros.to(points.device());
}
const float* data = cpu_points.ptr<float>();
constexpr float percentile = 0.75f;
std::vector<float> x_vals;
std::vector<float> y_vals;
std::vector<float> z_vals;
x_vals.reserve(num_points);
y_vals.reserve(num_points);
z_vals.reserve(num_points);
for (int i = 0; i < num_points; ++i) {
const float x = data[i * 3 + 0];
const float y = data[i * 3 + 1];
const float z = data[i * 3 + 2];
if (std::isfinite(x))
x_vals.push_back(x);
if (std::isfinite(y))
y_vals.push_back(y);
if (std::isfinite(z))
z_vals.push_back(z);
}
if (x_vals.empty() || y_vals.empty() || z_vals.empty()) {
auto zeros = lfs::core::Tensor::zeros(
{static_cast<size_t>(num_points), 3},
lfs::core::Device::CPU);
return zeros.to(points.device());
}
std::sort(x_vals.begin(), x_vals.end());
std::sort(y_vals.begin(), y_vals.end());
std::sort(z_vals.begin(), z_vals.end());
const auto idx_pair = [percentile](const size_t len) {
const size_t lower_idx = static_cast<size_t>(((1.0f - percentile) / 2.0f) * static_cast<float>(len));
const size_t upper_idx =
std::min(len - 1, static_cast<size_t>(((1.0f + percentile) / 2.0f) * static_cast<float>(len)));
return std::pair<size_t, size_t>{lower_idx, upper_idx};
};
const auto [lx, ux] = idx_pair(x_vals.size());
const auto [ly, uy] = idx_pair(y_vals.size());
const auto [lz, uz] = idx_pair(z_vals.size());
const float ex = (x_vals[ux] - x_vals[lx]) * 0.5f;
const float ey = (y_vals[uy] - y_vals[ly]) * 0.5f;
const float ez = (z_vals[uz] - z_vals[lz]) * 0.5f;
float sorted_extents[3] = {ex, ey, ez};
std::sort(sorted_extents, sorted_extents + 3);
const float median_size = std::max(sorted_extents[1] * 2.0f, 0.01f);
const float max_scale = median_size * 0.1f;
PointCloudAdaptor cloud(data, num_points);
KDTree index(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10));
index.buildIndex();
auto result = lfs::core::Tensor::zeros(
{static_cast<size_t>(num_points), 3},
lfs::core::Device::CPU);
float* result_data = result.ptr<float>();
#pragma omp parallel for if (num_points > 1000)
for (int i = 0; i < num_points; i++) {
const float query_pt[3] = {
data[i * 3 + 0],
data[i * 3 + 1],
data[i * 3 + 2]};
constexpr size_t num_results = 3; // self + 2 nearest neighbors
std::vector<size_t> ret_indices(num_results);
std::vector<float> out_dists_sqr(num_results);
nanoflann::KNNResultSet<float> result_set(num_results);
result_set.init(&ret_indices[0], &out_dists_sqr[0]);
index.findNeighbors(result_set, &query_pt[0], nanoflann::SearchParameters(10));
const float a1 = std::sqrt(std::max(out_dists_sqr[1], 0.0f));
const float a2 = std::sqrt(std::max(out_dists_sqr[2], 0.0f));
const float dist = (a1 + a2) * 0.25f;
const float log_scale = std::log(std::clamp(dist, 1e-3f, max_scale));
result_data[i * 3 + 0] = log_scale;
result_data[i * 3 + 1] = log_scale;
result_data[i * 3 + 2] = log_scale;
}
return result.to(points.device());
}
// Allocate a 1D swizzled-layout shN tensor sized for `n` primitives with `capacity`
// primitive-row slots reserved. Zero-initialised so dead lanes & inactive coefficient
// slots contribute nothing in Adam updates.
//
// The swizzled layout is intrinsically CUDA-only: every reader / writer
// (reorder_sh_to_swizzled, undo_reorder_sh_from_swizzled, shN_swizzled_gather_self,
// the rasterizer's load_shN_coeffs, the fused Adam path) is a CUDA kernel. There is no
// CPU swizzle path, so this buffer always lives on Device::CUDA regardless of where
// the other SplatData tensors live.
lfs::core::Tensor allocate_param_tensor(const lfs::core::TensorShape& shape,
size_t capacity,
const lfs::core::SplatTensorAllocator& allocator,
std::string_view name) {
using namespace lfs::core;
Tensor tensor = allocator
? allocator(shape, capacity, DataType::Float32, name)
: Tensor::zeros_direct(shape, capacity, Device::CUDA);
tensor.set_name(std::string{name});
return tensor;
}
[[nodiscard]] uint32_t infer_swizzled_rest_coefficients(size_t n, size_t numel) {
using namespace lfs::core;
const size_t blocks = sh_swizzled_block_count(n);
if (blocks == 0 || numel == 0) {
return 0;
}
const size_t denom = blocks * kShReorderSize * 4u;
const size_t slots = denom > 0 ? numel / denom : 0;
if (slots == 0) {
return 0;
}
if (slots <= 3) {
return sh_rest_coefficients_for_degree(1);
}
if (slots <= 6) {
return sh_rest_coefficients_for_degree(2);
}
return sh_rest_coefficients_for_degree(3);
}
lfs::core::Tensor allocate_swizzled_shN(size_t n, size_t capacity, uint32_t layout_coeffs_rest) {
using namespace lfs::core;
const size_t cap = std::max(capacity, n);
const size_t logical_floats = sh_swizzled_float_count(n, layout_coeffs_rest);
const size_t capacity_floats = sh_swizzled_float_count(cap, layout_coeffs_rest);
if (capacity_floats == 0) {
return Tensor::zeros({0}, Device::CUDA);
}
return Tensor::zeros_direct(TensorShape({logical_floats}), capacity_floats, Device::CUDA);
}
lfs::core::Tensor allocate_swizzled_shN(size_t n,
size_t capacity,
uint32_t layout_coeffs_rest,
const lfs::core::SplatTensorAllocator& allocator,
std::string_view name) {
using namespace lfs::core;
const size_t cap = std::max(capacity, n);
const size_t logical_floats = sh_swizzled_float_count(n, layout_coeffs_rest);
const size_t capacity_floats = sh_swizzled_float_count(cap, layout_coeffs_rest);
if (capacity_floats == 0) {
Tensor tensor = Tensor::zeros({0}, Device::CUDA);
tensor.set_name(std::string{name});
return tensor;
}
if (allocator) {
return allocate_param_tensor(TensorShape({logical_floats}),
capacity_floats,
allocator,
name);
}
Tensor tensor = Tensor::zeros_direct(TensorShape({logical_floats}),
capacity_floats,
Device::CUDA);
tensor.set_name(std::string{name});
return tensor;
}
[[nodiscard]] uint32_t canonical_rest_coefficients(const lfs::core::Tensor& canonical) {
if (!canonical.is_valid() || canonical.numel() == 0) {
return 0;
}
if (canonical.ndim() == 3) {
return static_cast<uint32_t>(std::min<size_t>(
canonical.size(1), lfs::core::kShMaxCoeffsRest));
}
if (canonical.ndim() == 2) {
return static_cast<uint32_t>(std::min<size_t>(
canonical.size(1) / SH_CHANNELS, lfs::core::kShMaxCoeffsRest));
}
return 0;
}
// Reorder a canonical-layout shN tensor into the swizzled `dst` buffer.
// canonical may be [N, K, 3] or [N, K*3]. K may be smaller than the resident
// layout; missing coefficients are zero-filled.
void reorder_canonical_into_swizzled(
const lfs::core::Tensor& canonical,
float* dst_swizzled,
size_t n_primitives,
uint32_t src_coeffs_rest,
uint32_t layout_coeffs_rest) {
using namespace lfs::core;
if (n_primitives == 0) {
return;
}
if (src_coeffs_rest == 0 || layout_coeffs_rest == 0) {
return;
}
Tensor src = canonical;
Tensor truncated;
if (canonical.ndim() == 3 &&
canonical.size(1) > src_coeffs_rest) {
truncated = canonical.slice(1, 0, static_cast<int>(src_coeffs_rest)).contiguous();
src = truncated;
} else if (canonical.ndim() == 2 &&
canonical.size(1) > static_cast<size_t>(src_coeffs_rest) * SH_CHANNELS) {
truncated = canonical.slice(
1,
0,
static_cast<int>(src_coeffs_rest * SH_CHANNELS))
.contiguous();
src = truncated;
}
Tensor src_cuda = src.device() == Device::CUDA ? src : src.cuda();
if (!src_cuda.is_contiguous()) {
src_cuda = src_cuda.contiguous();
}
reorder_sh_to_swizzled(src_cuda.ptr<float>(),
dst_swizzled,
n_primitives,
src_coeffs_rest,
layout_coeffs_rest);
}
[[nodiscard]] bool swizzled_storage_matches(const lfs::core::Tensor& shN,
size_t n,
size_t capacity,
uint32_t layout_coeffs_rest) {
using namespace lfs::core;
const size_t cap = std::max(capacity, n);
return shN.is_valid() &&
shN.ndim() == 1 &&
static_cast<size_t>(shN.shape()[0]) == sh_swizzled_float_count(n, layout_coeffs_rest) &&
shN.capacity() >= sh_swizzled_float_count(cap, layout_coeffs_rest);
}
void resize_swizzled_storage_preserving(lfs::core::Tensor& shN,
size_t n,
size_t capacity,
uint32_t layout_coeffs_rest) {
using namespace lfs::core;
const size_t cap = std::max(capacity, n);
const uint32_t old_layout_rest =
(shN.is_valid() && shN.ndim() == 1 && n > 0)
? infer_swizzled_rest_coefficients(n, static_cast<size_t>(shN.numel()))
: 0u;
Tensor old_canonical;
if (shN.is_valid() && shN.numel() > 0 && n > 0 && old_layout_rest > 0) {
old_canonical = Tensor::empty({n, static_cast<size_t>(old_layout_rest), SH_CHANNELS}, shN.device());
undo_reorder_sh_from_swizzled(shN.ptr<float>(),
old_canonical.ptr<float>(),
n,
old_layout_rest,
old_layout_rest);
}
Tensor resized = allocate_swizzled_shN(n, cap, layout_coeffs_rest);
const auto copy_rest = std::min(old_layout_rest, layout_coeffs_rest);
if (copy_rest > 0 && old_canonical.is_valid() && old_canonical.numel() > 0) {
reorder_canonical_into_swizzled(old_canonical,
resized.ptr<float>(),
n,
copy_rest,
layout_coeffs_rest);
}
shN = std::move(resized);
}
} // anonymous namespace
namespace lfs::core {
// ========== CONSTRUCTOR & DESTRUCTOR ==========
SplatData::SplatData(int sh_degree,
Tensor means_,
Tensor sh0_,
Tensor shN_,
Tensor scaling_,
Tensor rotation_,
Tensor opacity_,
float scene_scale_,
ShNLayout shN_layout)
: _max_sh_degree(sh_degree),
_active_sh_degree(sh_degree), // Set to max degree when loading; training will override this
_scene_scale(scene_scale_),
_means(std::move(means_)),
_sh0(std::move(sh0_)),
_scaling(std::move(scaling_)),
_rotation(std::move(rotation_)),
_opacity(std::move(opacity_)) {
_means.set_name("splat.positions");
_sh0.set_name("splat.sh0");
_scaling.set_name("splat.scaling");
_rotation.set_name("splat.rotation");
_opacity.set_name("splat.opacity");
const size_t n = _means.is_valid() ? static_cast<size_t>(_means.shape()[0]) : 0;
const size_t capacity = _means.is_valid() ? std::max<size_t>(_means.capacity(), n) : n;
uint32_t layout_coeffs_rest =
static_cast<uint32_t>(sh_rest_coefficients_for_degree(_max_sh_degree));
if (shN_layout == ShNLayout::Swizzled) {
_shN = std::move(shN_);
_shN.set_name("splat.shN");
if (_shN.is_valid() && _shN.ndim() == 1 && n > 0) {
const auto stored_rest = infer_swizzled_rest_coefficients(n, static_cast<size_t>(_shN.numel()));
const size_t expected_for_requested_degree = sh_swizzled_float_count(n, layout_coeffs_rest);
if (stored_rest > 0 && stored_rest != layout_coeffs_rest &&
static_cast<size_t>(_shN.numel()) == sh_swizzled_float_count(n, stored_rest)) {
Tensor old_canonical = Tensor::empty({n, static_cast<size_t>(stored_rest), SH_CHANNELS}, _shN.device());
undo_reorder_sh_from_swizzled(_shN.ptr<float>(),
old_canonical.ptr<float>(),
n,
stored_rest,
stored_rest);
Tensor resized = allocate_swizzled_shN(n, capacity, layout_coeffs_rest);
const auto copy_rest = std::min(stored_rest, layout_coeffs_rest);
reorder_canonical_into_swizzled(old_canonical,
resized.ptr<float>(),
n,
copy_rest,
layout_coeffs_rest);
_shN = std::move(resized);
} else if (stored_rest > 0 &&
static_cast<size_t>(_shN.numel()) < expected_for_requested_degree) {
_max_sh_degree = sh_degree_for_rest_coefficients(stored_rest);
_active_sh_degree = std::min(_active_sh_degree, _max_sh_degree);
layout_coeffs_rest =
static_cast<uint32_t>(sh_rest_coefficients_for_degree(_max_sh_degree));
}
}
const size_t expected_floats = sh_swizzled_float_count(n, layout_coeffs_rest);
if (!_shN.is_valid() || _shN.ndim() != 1 ||
static_cast<size_t>(_shN.shape()[0]) != expected_floats) {
_shN = allocate_swizzled_shN(n, capacity, layout_coeffs_rest);
}
_shN.set_name("splat.shN");
return;
}
// Convert the canonical-layout shN argument into swizzled storage.
_shN = allocate_swizzled_shN(n, capacity, layout_coeffs_rest);
_shN.set_name("splat.shN");
const auto src_rest = std::min(canonical_rest_coefficients(shN_), layout_coeffs_rest);
if (shN_.is_valid() && shN_.numel() > 0 && n > 0 && src_rest > 0 && layout_coeffs_rest > 0) {
reorder_canonical_into_swizzled(shN_, _shN.ptr<float>(), n, src_rest, layout_coeffs_rest);
}
}
SplatData::~SplatData() = default;
// ========== MOVE SEMANTICS ==========
SplatData::SplatData(SplatData&& other) noexcept
: _active_sh_degree(other._active_sh_degree),
_max_sh_degree(other._max_sh_degree),
_scene_scale(other._scene_scale),
_means(std::move(other._means)),
_sh0(std::move(other._sh0)),
_shN(std::move(other._shN)),
_scaling(std::move(other._scaling)),
_rotation(std::move(other._rotation)),
_opacity(std::move(other._opacity)),
_densification_info(std::move(other._densification_info)),
_deleted(std::move(other._deleted)),
_deleted_count(other._deleted_count.load(std::memory_order_relaxed)),
_tensor_allocator(std::move(other._tensor_allocator)),
lod_tree(std::move(other.lod_tree)),
_frozen_ranges(std::move(other._frozen_ranges)) {
// Reset the moved-from object
other._active_sh_degree = 0;
other._max_sh_degree = 0;
other._scene_scale = 0.0f;
other._deleted_count.store(0, std::memory_order_relaxed);
other._frozen_ranges.clear();
}
SplatData& SplatData::operator=(SplatData&& other) noexcept {
if (this != &other) {
// Move scalar members
_active_sh_degree = other._active_sh_degree;
_max_sh_degree = other._max_sh_degree;
_scene_scale = other._scene_scale;
// Move tensors
_means = std::move(other._means);
_sh0 = std::move(other._sh0);
_shN = std::move(other._shN);
_scaling = std::move(other._scaling);
_rotation = std::move(other._rotation);
_opacity = std::move(other._opacity);
_densification_info = std::move(other._densification_info);
_deleted = std::move(other._deleted);
// Move LOD tree
lod_tree = std::move(other.lod_tree);
_deleted_count.store(other._deleted_count.load(std::memory_order_relaxed),
std::memory_order_relaxed);
_tensor_allocator = std::move(other._tensor_allocator);
_frozen_ranges = std::move(other._frozen_ranges);
other._deleted_count.store(0, std::memory_order_relaxed);
other._frozen_ranges.clear();
}
return *this;
}
void SplatData::remap_frozen_ranges_after_keep(
const size_t old_size,
const std::vector<int>& kept_old_indices) {
_frozen_ranges = ::remap_frozen_ranges_after_keep(
_frozen_ranges,
old_size,
kept_old_indices);
}
void SplatData::remap_frozen_ranges_after_keep(
const size_t old_size,
const std::vector<int64_t>& kept_old_indices) {
_frozen_ranges = ::remap_frozen_ranges_after_keep(
_frozen_ranges,
old_size,
kept_old_indices);
}
// ========== COMPUTED GETTERS ==========
Tensor SplatData::get_means() const {
return _means;
}
Tensor SplatData::get_opacity() const {
return _opacity.sigmoid().squeeze(-1);
}
Tensor SplatData::get_rotation() const {
// Normalize quaternions along the last dimension
// _rotation is [N, 4], we want to normalize each quaternion
// norm = sqrt(sum(x^2)) along dim=1, keepdim=true to get [N, 1]
auto squared = _rotation.square();
auto sum_squared = squared.sum({1}, true); // [N, 1]
auto norm = sum_squared.sqrt(); // [N, 1]
return _rotation.div(norm.clamp_min(1e-12f)); // Avoid division by zero
}
Tensor SplatData::get_scaling() const {
return _scaling.exp();
}
Tensor SplatData::get_shs() const {
// _sh0 is [N, 1, 3]; _shN is the swizzled flat buffer. Deswizzle on demand
// and concatenate to produce [N, K_total, 3].
const size_t active_rest = active_sh_coeffs_rest();
if (active_rest == 0) {
return _sh0;
}
auto shN = shN_canonical();
if (shN.ndim() == 3 && shN.size(1) > active_rest) {
shN = shN.slice(1, 0, static_cast<int>(active_rest)).contiguous();
}
if (shN.device() != _sh0.device()) {
shN = shN.to(_sh0.device());
}
return _sh0.cat(shN, 1);
}
Tensor SplatData::shN_canonical() const {
const size_t n = static_cast<size_t>(size());
const size_t k = max_sh_coeffs_rest();
// The swizzled buffer is CUDA-only (see allocate_swizzled_shN); align the canonical
// output device with where the source data actually lives.
const Device dst_device = _shN.is_valid() ? _shN.device() : Device::CUDA;
if (n == 0 || k == 0) {
return Tensor::zeros({n, k, SH_CHANNELS}, dst_device);
}
Tensor out = Tensor::empty({n, k, SH_CHANNELS}, dst_device);
undo_reorder_sh_from_swizzled(_shN.ptr<float>(),
out.ptr<float>(),
n,
static_cast<uint32_t>(k),
static_cast<uint32_t>(k));
return out;
}
Tensor SplatData::shN_canonical_cpu() const {
const size_t n = static_cast<size_t>(size());
const size_t k = max_sh_coeffs_rest();
if (n == 0 || k == 0) {
return Tensor::zeros({n, k, SH_CHANNELS}, Device::CPU);
}
Tensor out = Tensor::empty({n, k, SH_CHANNELS}, Device::CPU, DataType::Float32);
if (!_shN.is_valid() || _shN.numel() == 0) {
out.zero_();
return out;
}
const Tensor shN_cpu = _shN.cpu().contiguous();
const auto* const src = shN_cpu.ptr<float>();
auto* const dst = out.ptr<float>();
const size_t src_floats = shN_cpu.numel();
const size_t active_floats = k * SH_CHANNELS;
for (size_t p = 0; p < n; ++p) {
float* const dst_row = dst + p * active_floats;
for (size_t offset = 0; offset < active_floats; ++offset) {
const auto slot = static_cast<std::uint32_t>(offset / 4u);
const auto component = static_cast<std::uint32_t>(offset % 4u);
const size_t src_offset =
static_cast<size_t>(sh_swizzled_index(static_cast<std::uint32_t>(p), slot, static_cast<uint32_t>(k))) * 4u +
component;
dst_row[offset] = src_offset < src_floats ? src[src_offset] : 0.0f;
}
}
return out;
}
void SplatData::shN_set_from_canonical(const Tensor& canonical, size_t capacity) {
const size_t n = static_cast<size_t>(size());
const size_t cap = std::max<size_t>(capacity, n);
const uint32_t layout_rest = static_cast<uint32_t>(max_sh_coeffs_rest());
const size_t needed_floats = sh_swizzled_float_count(n, layout_rest);
const size_t needed_capacity = sh_swizzled_float_count(cap, layout_rest);
// Adjust _shN's logical size to match the new N without losing reserved capacity
// when possible. Reallocating drops the pre-alloc buffer and can break async
// pointer aliasing for downstream kernels; we only do it when capacity is short.
if (_shN.is_valid() && _shN.capacity() >= needed_capacity) {
if (_shN.numel() < needed_floats) {
_shN.append_zeros(needed_floats - _shN.numel());
} else if (_shN.numel() > needed_floats) {
// N shrank (e.g. random_choose, crop, prune-then-compact). The Tensor lib
// doesn't have a "shrink logical size" op other than reassigning shape.
// Allocate a smaller buffer in this case — it's a one-shot edit operation.
_shN = allocate_swizzled_shN(n, cap, layout_rest);
}
// else: numel() == needed_floats, nothing to do.
} else {
_shN = allocate_swizzled_shN(n, cap, layout_rest);
}
const auto src_rest = std::min(canonical_rest_coefficients(canonical), layout_rest);
if (n > 0 && layout_rest > 0 && src_rest == 0 && _shN.is_valid() && _shN.numel() > 0) {
_shN.zero_();
}
if (canonical.is_valid() && canonical.numel() > 0 && n > 0 && src_rest > 0 && layout_rest > 0) {
reorder_canonical_into_swizzled(canonical, _shN.ptr<float>(), n, src_rest, layout_rest);
}
}
size_t SplatData::active_sh_coeffs_rest() const {
return sh_rest_coefficients_for_degree(_active_sh_degree);
}
size_t SplatData::max_sh_coeffs_rest() const {
return sh_rest_coefficients_for_degree(_max_sh_degree);
}
// ========== UTILITY METHODS ==========
void SplatData::increment_sh_degree() {
if (_active_sh_degree < _max_sh_degree) {
set_active_sh_degree(_active_sh_degree + 1);
}
}
void SplatData::set_active_sh_degree(int sh_degree) {
const int target_degree = std::clamp(sh_degree, 0, _max_sh_degree);
const size_t n = static_cast<size_t>(size());
const size_t cap = _means.is_valid() ? std::max<size_t>(_means.capacity(), n) : n;
const auto layout_rest = static_cast<uint32_t>(max_sh_coeffs_rest());
if (!swizzled_storage_matches(_shN, n, cap, layout_rest)) {
resize_swizzled_storage_preserving(_shN, n, cap, layout_rest);
}
_active_sh_degree = target_degree;
}
void SplatData::set_max_sh_degree(int sh_degree) {
const int target_degree = std::clamp(sh_degree, 0, MAX_SUPPORTED_SH_DEGREE);
if (_max_sh_degree == target_degree) {
if (_active_sh_degree > _max_sh_degree) {
_active_sh_degree = _max_sh_degree;
}
const size_t n = static_cast<size_t>(size());
const size_t cap = _means.is_valid() ? std::max<size_t>(_means.capacity(), n) : n;
const auto layout_rest = static_cast<uint32_t>(max_sh_coeffs_rest());
if (!swizzled_storage_matches(_shN, n, cap, layout_rest)) {
resize_swizzled_storage_preserving(_shN, n, cap, layout_rest);
}
return;
}
_max_sh_degree = target_degree;
if (_active_sh_degree > _max_sh_degree) {
_active_sh_degree = _max_sh_degree;
}
const size_t n = static_cast<size_t>(size());
const size_t cap = _means.is_valid() ? std::max<size_t>(_means.capacity(), n) : n;
resize_swizzled_storage_preserving(_shN,
n,
cap,
static_cast<uint32_t>(max_sh_coeffs_rest()));
}
bool SplatData::set_sh_degree(const int sh_degree) {
assert(_means.is_valid());
const int target_degree = std::clamp(sh_degree, 0, MAX_SUPPORTED_SH_DEGREE);
bool changed = _max_sh_degree != target_degree || _active_sh_degree != target_degree;
set_max_sh_degree(target_degree);
_active_sh_degree = target_degree;
return changed;
}
void SplatData::reserve_capacity(const size_t capacity) {
if (_means.is_valid())
_means.reserve(capacity);
if (_sh0.is_valid())
_sh0.reserve(capacity);
if (_shN.is_valid()) {
// shN is 1D swizzled — reserve in float count.
_shN.reserve(sh_swizzled_float_count(capacity, static_cast<uint32_t>(max_sh_coeffs_rest())));
}
if (_scaling.is_valid())
_scaling.reserve(capacity);
if (_rotation.is_valid())
_rotation.reserve(capacity);
if (_opacity.is_valid())
_opacity.reserve(capacity);
}
// ========== SOFT DELETION ==========
unsigned long SplatData::visible_count() const {
if (!_deleted.is_valid()) {
return size();
}
return size() - static_cast<unsigned long>(_deleted.sum_scalar());
}
void SplatData::refresh_deleted_count() {
// sum_scalar() reduces + syncs, so this must run on the thread that owns the
// mask (the trainer), never the render thread. Re-deriving from the live mask
// each call keeps the cache correct regardless of which path mutated _deleted.
_deleted_count.store(
_deleted.is_valid() ? static_cast<std::size_t>(_deleted.sum_scalar()) : 0,
std::memory_order_relaxed);
}
Tensor SplatData::soft_delete(const Tensor& mask) {
if (!_means.is_valid() || _means.size(0) == 0) {
LOG_WARN("soft_delete: invalid or empty SplatData");
return Tensor();
}
const size_t n = size();
if (mask.size(0) != n) {
LOG_ERROR("soft_delete: mask size {} != SplatData size {}", mask.size(0), n);
return Tensor();
}
if (!_deleted.is_valid()) {
_deleted = Tensor::zeros({n}, _means.device(), DataType::Bool);
_deleted.set_name("splat.deleted_mask");
}
Tensor old_deleted = _deleted.clone();
_deleted = _deleted || mask;
return old_deleted;
}
void SplatData::undelete(const Tensor& mask) {
if (!_deleted.is_valid()) {
return;
}
const size_t n = size();
if (mask.size(0) != n) {
LOG_ERROR("undelete: mask size {} != SplatData size {}", mask.size(0), n);
return;
}
_deleted = _deleted && mask.logical_not();
}
void SplatData::clear_deleted() {
if (_deleted.is_valid()) {
_deleted = Tensor();
}
_deleted_count.store(0, std::memory_order_relaxed);
}
size_t SplatData::apply_deleted() {
if (!_deleted.is_valid() || !_means.is_valid()) {
return 0;
}
const size_t old_size = size();
// Validate mask dimensions match data
if (_deleted.size(0) != old_size) {
LOG_ERROR("apply_deleted: mask size {} != data size {}, aborting",
_deleted.size(0), old_size);
_deleted = Tensor();
return 0;
}
// Validate mask is boolean type
if (_deleted.dtype() != DataType::Bool) {
LOG_ERROR("apply_deleted: mask is not Bool type, aborting");
_deleted = Tensor();
return 0;
}
// Validate all required tensors have matching sizes
if (_sh0.size(0) != old_size || _scaling.size(0) != old_size ||
_rotation.size(0) != old_size || _opacity.size(0) != old_size) {
LOG_ERROR("apply_deleted: tensor size mismatch, aborting");
_deleted = Tensor();
return 0;
}
const auto keep_mask = _deleted.logical_not();
const size_t new_size = static_cast<size_t>(keep_mask.sum_scalar());
// Nothing to delete
if (new_size == old_size) {
_deleted = Tensor();
return 0;
}
// Would delete everything
if (new_size == 0) {
LOG_WARN("apply_deleted: would remove all gaussians, aborting");
return 0;
}
LOG_DEBUG("apply_deleted: filtering {} -> {} gaussians", old_size, new_size);
// Int32 indices of kept primitives, computed once and reused for the param
// gathers and the shN block-aware gather. nonzero() returns [num_kept, 1].
Tensor kept_indices = keep_mask.nonzero();
const auto kept_numel = static_cast<int>(kept_indices.numel());
if (kept_indices.ndim() > 1)
kept_indices = kept_indices.reshape({kept_numel});
kept_indices = kept_indices.to(DataType::Int32);
const auto kept_indices_host = _frozen_ranges.empty()
? std::vector<int>{}
: kept_indices.to_vector_int();
// Gather kept rows for each parameter directly into a destination allocated
// from the model's backing storage (Vulkan-external interop when set, the
// default device allocator otherwise). Gathering into the destination avoids
// the transient copy of an index_select() + re-home, and keeps the tensors in
// the storage the viewport renderer requires.
const auto gather_param = [&](const Tensor& src, std::string_view name) {
auto dims = src.shape().dims();
dims[0] = new_size;
Tensor out = allocate_param_tensor(TensorShape(dims), new_size,
_tensor_allocator, name);
src.index_select_into(out, 0, kept_indices, BoundaryMode::Assert);
return out;
};
auto new_means = gather_param(_means, "SplatData.means");
auto new_sh0 = gather_param(_sh0, "SplatData.sh0");
auto new_scaling = gather_param(_scaling, "SplatData.scaling");
auto new_rotation = gather_param(_rotation, "SplatData.rotation");
auto new_opacity = gather_param(_opacity, "SplatData.opacity");
// Verify new sizes are correct before committing
if (new_means.size(0) != new_size || new_sh0.size(0) != new_size ||
new_scaling.size(0) != new_size || new_rotation.size(0) != new_size ||
new_opacity.size(0) != new_size) {
LOG_ERROR("apply_deleted: post-filter size mismatch - means:{} sh0:{} scaling:{} rotation:{} opacity:{} expected:{}",
new_means.size(0), new_sh0.size(0), new_scaling.size(0),
new_rotation.size(0), new_opacity.size(0), new_size);
return 0;
}
// Commit the changes
_means = std::move(new_means);
_sh0 = std::move(new_sh0);
_scaling = std::move(new_scaling);
_rotation = std::move(new_rotation);
_opacity = std::move(new_opacity);
// shN is in swizzled layout — block-aware gather of kept primitives.
const auto layout_rest = static_cast<uint32_t>(max_sh_coeffs_rest());
if (_shN.is_valid() && _shN.numel() > 0 && layout_rest > 0) {
auto new_shN = allocate_swizzled_shN(new_size, new_size, layout_rest,
_tensor_allocator, "SplatData.shN");
shN_swizzled_gather_self(_shN.ptr<float>(), new_shN.ptr<float>(),
kept_indices.ptr<int>(), new_size, 0, layout_rest);
_shN = std::move(new_shN);
}
// Clear densification info
_densification_info = Tensor();
if (!_frozen_ranges.empty()) {
remap_frozen_ranges_after_keep(old_size, kept_indices_host);
}
// Clear deletion mask
_deleted = Tensor();
const size_t removed = old_size - new_size;
LOG_INFO("apply_deleted: removed {} gaussians ({} -> {})", removed, old_size, new_size);
return removed;
}
// ========== SERIALIZATION ==========