forked from pierotofy/OpenSplat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.cpp
467 lines (380 loc) · 19.1 KB
/
model.cpp
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
#include "model.hpp"
#include "constants.hpp"
#include "tile_bounds.hpp"
#include "project_gaussians.hpp"
#include "rasterize_gaussians.hpp"
#include "vendor/gsplat/config.h"
namespace ns{
torch::Tensor randomQuatTensor(long long n){
torch::Tensor u = torch::rand(n);
torch::Tensor v = torch::rand(n);
torch::Tensor w = torch::rand(n);
return torch::stack({
torch::sqrt(1 - u) * torch::sin(2 * PI * v),
torch::sqrt(1 - u) * torch::cos(2 * PI * v),
torch::sqrt(u) * torch::sin(2 * PI * w),
torch::sqrt(u) * torch::cos(2 * PI * w)
}, -1);
}
torch::Tensor quatToRotMat(const torch::Tensor &quat){
auto u = torch::unbind(torch::nn::functional::normalize(quat, torch::nn::functional::NormalizeFuncOptions().dim(-1)), -1);
torch::Tensor w = u[0];
torch::Tensor x = u[1];
torch::Tensor y = u[2];
torch::Tensor z = u[3];
return torch::stack({
torch::stack({
1.0 - 2.0 * (y.pow(2) + z.pow(2)),
2.0 * (x * y - w * z),
2.0 * (x * z + w * y)
}, -1),
torch::stack({
2.0 * (x * y + w * z),
1.0 - 2.0 * (x.pow(2) + z.pow(2)),
2.0 * (y * z - w * x)
}, -1),
torch::stack({
2.0 * (x * z - w * y),
2.0 * (y * z + w * x),
1.0 - 2.0 * (x.pow(2) + y.pow(2))
}, -1)
}, -2);
}
torch::Tensor projectionMatrix(float zNear, float zFar, float fovX, float fovY, const torch::Device &device){
// OpenGL perspective projection matrix
float t = zNear * std::tan(0.5f * fovY);
float b = -t;
float r = zNear * std::tan(0.5f * fovX);
float l = -r;
return torch::tensor({
{2.0f * zNear / (r - l), 0.0f, (r + l) / (r - l), 0.0f},
{0.0f, 2 * zNear / (t - b), (t + b) / (t - b), 0.0f},
{0.0f, 0.0f, (zFar + zNear) / (zFar - zNear), -1.0f * zFar * zNear / (zFar - zNear)},
{0.0f, 0.0f, 1.0f, 0.0f}
}, device);
}
torch::Tensor psnr(const torch::Tensor& rendered, const torch::Tensor& gt){
torch::Tensor mse = (rendered - gt).pow(2).mean();
return (10.f * torch::log10(1.0 / mse));
}
torch::Tensor l1(const torch::Tensor& rendered, const torch::Tensor& gt){
return torch::abs(gt - rendered).mean();
}
torch::Tensor Model::forward(Camera& cam, int step){
float scaleFactor = 1.0f / static_cast<float>(getDownscaleFactor(step));
cam.scaleOutputResolution(scaleFactor);
// TODO: these can be moved to Camera and computed only once?
torch::Tensor R = cam.camToWorld.index({Slice(None, 3), Slice(None, 3)});
torch::Tensor T = cam.camToWorld.index({Slice(None, 3), Slice(3,4)});
// Flip the z and y axes to align with gsplat conventions
R = torch::matmul(R, torch::diag(torch::tensor({1.0f, -1.0f, -1.0f}, R.device())));
// worldToCam
torch::Tensor Rinv = R.transpose(0, 1);
torch::Tensor Tinv = torch::matmul(-Rinv, T);
lastHeight = cam.height;
lastWidth = cam.width;
torch::Tensor viewMat = torch::eye(4, device);
viewMat.index_put_({Slice(None, 3), Slice(None, 3)}, Rinv);
viewMat.index_put_({Slice(None, 3), Slice(3, 4)}, Tinv);
float fovX = 2.0f * std::atan(cam.width / (2.0f * cam.fx));
float fovY = 2.0f * std::atan(cam.height / (2.0f * cam.fy));
torch::Tensor projMat = projectionMatrix(0.001f, 1000.0f, fovX, fovY, device);
TileBounds tileBounds = std::make_tuple((cam.width + BLOCK_X - 1) / BLOCK_X,
(cam.height + BLOCK_Y - 1) / BLOCK_Y,
1);
torch::Tensor colors = torch::cat({featuresDc.index({Slice(), None, Slice()}), featuresRest}, 1);
auto p = ProjectGaussians::apply(means,
torch::exp(scales),
1,
quats / quats.norm(2, {-1}, true),
viewMat,
torch::matmul(projMat, viewMat),
cam.fx,
cam.fy,
cam.cx,
cam.cy,
cam.height,
cam.width,
tileBounds);
xys = p[0];
torch::Tensor depths = p[1];
radii = p[2];
torch::Tensor conics = p[3];
torch::Tensor numTilesHit = p[4];
if (radii.sum().item<float>() == 0.0f){
// Rescale resolution back
cam.scaleOutputResolution(1.0f / scaleFactor);
return backgroundColor.repeat({cam.height, cam.width, 1});
}
// TODO: is this needed?
xys.retain_grad();
torch::Tensor viewDirs = means.detach() - T.transpose(0, 1).to(device);
viewDirs = viewDirs / viewDirs.norm(2, {-1}, true);
int degreesToUse = (std::min<int>)(step / shDegreeInterval, shDegree);
torch::Tensor rgbs = SphericalHarmonics::apply(degreesToUse, viewDirs, colors);
rgbs = torch::clamp_min(rgbs + 0.5f, 0.0f);
torch::Tensor rgb = RasterizeGaussians::apply(
xys,
depths,
radii,
conics,
numTilesHit,
rgbs, // TODO: why not sigmod?
torch::sigmoid(opacities),
cam.height,
cam.width,
backgroundColor);
rgb = torch::clamp_max(rgb, 1.0f);
// Rescale resolution back
cam.scaleOutputResolution(1.0f / scaleFactor);
return rgb;
}
void Model::optimizersZeroGrad(){
meansOpt->zero_grad();
scalesOpt->zero_grad();
quatsOpt->zero_grad();
featuresDcOpt->zero_grad();
featuresRestOpt->zero_grad();
opacitiesOpt->zero_grad();
}
void Model::optimizersStep(){
meansOpt->step();
scalesOpt->step();
quatsOpt->step();
featuresDcOpt->step();
featuresRestOpt->step();
opacitiesOpt->step();
}
void Model::schedulersStep(int step){
meansOptScheduler->step(step);
}
int Model::getDownscaleFactor(int step){
return std::pow(2, (std::max<int>)(numDownscales - step / resolutionSchedule, 0));
}
void Model::addToOptimizer(torch::optim::Adam *optimizer, const torch::Tensor &newParam, const torch::Tensor &idcs, int nSamples){
torch::Tensor param = optimizer->param_groups()[0].params()[0];
auto pId = c10::guts::to_string(param.unsafeGetTensorImpl());
auto paramState = std::make_unique<torch::optim::AdamParamState>(static_cast<torch::optim::AdamParamState&>(*optimizer->state()[pId]));
std::vector<int64_t> repeats;
repeats.push_back(nSamples);
for (long int i = 0; i < paramState->exp_avg().dim() - 1; i++){
repeats.push_back(1);
}
paramState->exp_avg(torch::cat({
paramState->exp_avg(),
torch::zeros_like(paramState->exp_avg().index({idcs.squeeze()})).repeat(repeats)
}, 0));
paramState->exp_avg_sq(torch::cat({
paramState->exp_avg_sq(),
torch::zeros_like(paramState->exp_avg_sq().index({idcs.squeeze()})).repeat(repeats)
}, 0));
optimizer->state().erase(pId);
auto newPId = c10::guts::to_string(newParam.unsafeGetTensorImpl());
optimizer->state()[newPId] = std::move(paramState);
optimizer->param_groups()[0].params()[0] = newParam;
}
void Model::removeFromOptimizer(torch::optim::Adam *optimizer, const torch::Tensor &newParam, const torch::Tensor &deletedMask){
torch::Tensor param = optimizer->param_groups()[0].params()[0];
auto pId = c10::guts::to_string(param.unsafeGetTensorImpl());
auto paramState = std::make_unique<torch::optim::AdamParamState>(static_cast<torch::optim::AdamParamState&>(*optimizer->state()[pId]));
paramState->exp_avg(paramState->exp_avg().index({~deletedMask}));
paramState->exp_avg_sq(paramState->exp_avg_sq().index({~deletedMask}));
optimizer->state().erase(pId);
auto newPId = c10::guts::to_string(newParam.unsafeGetTensorImpl());
optimizer->param_groups()[0].params()[0] = newParam;
optimizer->state()[newPId] = std::move(paramState);
}
void Model::afterTrain(int step){
torch::NoGradGuard noGrad;
if (step < stopSplitAt){
torch::Tensor visibleMask = (radii > 0).flatten();
torch::Tensor grads = torch::linalg::vector_norm(xys.grad().detach(), 2, { -1 }, false, torch::kFloat32);
if (!xysGradNorm.numel()){
xysGradNorm = grads;
visCounts = torch::ones_like(xysGradNorm);
}else{
visCounts.index_put_({visibleMask}, visCounts.index({visibleMask}) + 1);
xysGradNorm.index_put_({visibleMask}, grads.index({visibleMask}) + xysGradNorm.index({visibleMask}));
}
if (!max2DSize.numel()){
max2DSize = torch::zeros_like(radii, torch::kFloat32);
}
torch::Tensor newRadii = radii.detach().index({visibleMask});
max2DSize.index_put_({visibleMask}, torch::maximum(
max2DSize.index({visibleMask}), newRadii / static_cast<float>( (std::max)(lastHeight, lastWidth) )
));
}
if (step % refineEvery == 0 && step > warmupLength){
int resetInterval = resetAlphaEvery * refineEvery;
bool doDensification = step < stopSplitAt && step % resetInterval > numCameras + refineEvery;
torch::Tensor splitsMask;
const float cullAlphaThresh = 0.1f;
if (doDensification){
int numPointsBefore = means.size(0);
torch::Tensor avgGradNorm = (xysGradNorm / visCounts) * 0.5f * static_cast<float>( (std::max)(lastWidth, lastHeight) );
torch::Tensor highGrads = (avgGradNorm > densifyGradThresh).squeeze();
// Split gaussians that are too large
torch::Tensor splits = (std::get<0>(scales.exp().max(-1)) > densifySizeThresh).squeeze();
if (step < stopScreenSizeAt){
splits |= (max2DSize > splitScreenSize).squeeze();
}
splits &= highGrads;
const int nSplitSamples = 2;
int nSplits = splits.sum().item<int>();
torch::Tensor centeredSamples = torch::randn({nSplitSamples * nSplits, 3}, device); // Nx3 of axis-aligned scales
torch::Tensor scaledSamples = torch::exp(scales.index({splits}).repeat({nSplitSamples, 1})) * centeredSamples;
torch::Tensor qs = quats.index({splits}) / torch::linalg::vector_norm(quats.index({splits}), 2, { -1 }, true, torch::kFloat32);
torch::Tensor rots = quatToRotMat(qs.repeat({nSplitSamples, 1}));
torch::Tensor rotatedSamples = torch::bmm(rots, scaledSamples.index({"...", None})).squeeze();
torch::Tensor splitMeans = rotatedSamples + means.index({splits}).repeat({nSplitSamples, 1});
torch::Tensor splitFeaturesDc = featuresDc.index({splits}).repeat({nSplitSamples, 1});
torch::Tensor splitFeaturesRest = featuresRest.index({splits}).repeat({nSplitSamples, 1, 1});
torch::Tensor splitOpacities = opacities.index({splits}).repeat({nSplitSamples, 1});
const float sizeFac = 1.6f;
torch::Tensor splitScales = torch::log(torch::exp(scales.index({splits})) / sizeFac).repeat({nSplitSamples, 1});
scales.index({splits}) = torch::log(torch::exp(scales.index({splits})) / sizeFac);
torch::Tensor splitQuats = quats.index({splits}).repeat({nSplitSamples, 1});
// Duplicate gaussians that are too small
torch::Tensor dups = (std::get<0>(scales.exp().max(-1)) <= densifySizeThresh).squeeze();
dups &= highGrads;
torch::Tensor dupMeans = means.index({dups});
torch::Tensor dupFeaturesDc = featuresDc.index({dups});
torch::Tensor dupFeaturesRest = featuresRest.index({dups});
torch::Tensor dupOpacities = opacities.index({dups});
torch::Tensor dupScales = scales.index({dups});
torch::Tensor dupQuats = quats.index({dups});
means = torch::cat({means.detach(), splitMeans, dupMeans}, 0).requires_grad_();
featuresDc = torch::cat({featuresDc.detach(), splitFeaturesDc, dupFeaturesDc}, 0).requires_grad_();
featuresRest = torch::cat({featuresRest.detach(), splitFeaturesRest, dupFeaturesRest}, 0).requires_grad_();
opacities = torch::cat({opacities.detach(), splitOpacities, dupOpacities}, 0).requires_grad_();
scales = torch::cat({scales.detach(), splitScales, dupScales}, 0).requires_grad_();
quats = torch::cat({quats.detach(), splitQuats, dupQuats}, 0).requires_grad_();
max2DSize = torch::cat({
max2DSize,
torch::zeros_like(splitScales.index({Slice(), 0})),
torch::zeros_like(dupScales.index({Slice(), 0}))
}, 0);
torch::Tensor splitIdcs = torch::where(splits)[0];
addToOptimizer(meansOpt, means, splitIdcs, nSplitSamples);
addToOptimizer(scalesOpt, scales, splitIdcs, nSplitSamples);
addToOptimizer(quatsOpt, quats, splitIdcs, nSplitSamples);
addToOptimizer(featuresDcOpt, featuresDc, splitIdcs, nSplitSamples);
addToOptimizer(featuresRestOpt, featuresRest, splitIdcs, nSplitSamples);
addToOptimizer(opacitiesOpt, opacities, splitIdcs, nSplitSamples);
torch::Tensor dupIdcs = torch::where(dups)[0];
addToOptimizer(meansOpt, means, dupIdcs, 1);
addToOptimizer(scalesOpt, scales, dupIdcs, 1);
addToOptimizer(quatsOpt, quats, dupIdcs, 1);
addToOptimizer(featuresDcOpt, featuresDc, dupIdcs, 1);
addToOptimizer(featuresRestOpt, featuresRest, dupIdcs, 1);
addToOptimizer(opacitiesOpt, opacities, dupIdcs, 1);
splitsMask = torch::cat({
splits,
torch::full({nSplitSamples * splits.sum().item<int>() + dups.sum().item<int>()}, false, torch::TensorOptions().dtype(torch::kBool).device(device))
}, 0);
std::cout << "Added " << (means.size(0) - numPointsBefore) << " gaussians, new count " << means.size(0) << std::endl;
}
if (doDensification || step >= stopSplitAt){
// Cull
int numPointsBefore = means.size(0);
torch::Tensor culls = (torch::sigmoid(opacities) < cullAlphaThresh).squeeze();
if (splitsMask.numel()){
culls |= splitsMask;
}
if (step > refineEvery * resetAlphaEvery){
const float cullScaleThresh = 0.5f; // cull huge gaussians
const float cullScreenSize = 0.15f; // % of screen space
torch::Tensor huge = std::get<0>(torch::exp(scales).max(-1)) > cullScaleThresh;
if (step < stopScreenSizeAt){
huge |= max2DSize > cullScreenSize;
}
culls |= huge;
}
int cullCount = torch::sum(culls).item<int>();
if (cullCount > 0){
means = means.index({~culls}).detach().requires_grad_();
scales = scales.index({~culls}).detach().requires_grad_();
quats = quats.index({~culls}).detach().requires_grad_();
featuresDc = featuresDc.index({~culls}).detach().requires_grad_();
featuresRest = featuresRest.index({~culls}).detach().requires_grad_();
opacities = opacities.index({~culls}).detach().requires_grad_();
removeFromOptimizer(meansOpt, means, culls);
removeFromOptimizer(scalesOpt, scales, culls);
removeFromOptimizer(quatsOpt, quats, culls);
removeFromOptimizer(featuresDcOpt, featuresDc, culls);
removeFromOptimizer(featuresRestOpt, featuresRest, culls);
removeFromOptimizer(opacitiesOpt, opacities, culls);
std::cout << "Culled " << (numPointsBefore - means.size(0)) << " gaussians, remaining " << means.size(0) << std::endl;
}
}
if (step < stopSplitAt && step % resetInterval == refineEvery){
float resetValue = cullAlphaThresh * 2.0f;
opacities = torch::clamp_max(opacities, torch::logit(torch::tensor(resetValue)).item<float>());
// Reset optimizer
torch::Tensor param = opacitiesOpt->param_groups()[0].params()[0];
auto pId = c10::guts::to_string(param.unsafeGetTensorImpl());
auto paramState = std::make_unique<torch::optim::AdamParamState>(static_cast<torch::optim::AdamParamState&>(*opacitiesOpt->state()[pId]));
paramState->exp_avg(torch::zeros_like(paramState->exp_avg()));
paramState->exp_avg_sq(torch::zeros_like(paramState->exp_avg_sq()));
std::cout << "Alpha reset" << std::endl;
}
// Clear
xysGradNorm = torch::Tensor();
visCounts = torch::Tensor();
max2DSize = torch::Tensor();
}
}
void Model::savePlySplat(const std::string &filename){
std::ofstream o(filename, std::ios::binary);
int numPoints = means.size(0);
o << "ply" << std::endl;
o << "format binary_little_endian 1.0" << std::endl;
o << "comment Generated by opensplat" << std::endl;
o << "element vertex " << numPoints << std::endl;
o << "property float x" << std::endl;
o << "property float y" << std::endl;
o << "property float z" << std::endl;
o << "property float nx" << std::endl;
o << "property float ny" << std::endl;
o << "property float nz" << std::endl;
for (int i = 0; i < featuresDc.size(1); i++){
o << "property float f_dc_" << i << std::endl;
}
// Match Inria's version
torch::Tensor featuresRestCpu = featuresRest.cpu().transpose(1, 2).reshape({numPoints, -1});
for (int i = 0; i < featuresRestCpu.size(1); i++){
o << "property float f_rest_" << i << std::endl;
}
o << "property float opacity" << std::endl;
o << "property float scale_0" << std::endl;
o << "property float scale_1" << std::endl;
o << "property float scale_2" << std::endl;
o << "property float rot_0" << std::endl;
o << "property float rot_1" << std::endl;
o << "property float rot_2" << std::endl;
o << "property float rot_3" << std::endl;
o << "end_header" << std::endl;
float zeros[] = { 0.0f, 0.0f, 0.0f };
torch::Tensor meansCpu = means.cpu();
torch::Tensor featuresDcCpu = featuresDc.cpu();
torch::Tensor opacitiesCpu = opacities.cpu();
torch::Tensor scalesCpu = scales.cpu();
torch::Tensor quatsCpu = quats.cpu();
for (size_t i = 0; i < numPoints; i++) {
o.write(reinterpret_cast<const char *>(meansCpu[i].data_ptr()), sizeof(float) * 3);
o.write(reinterpret_cast<const char *>(zeros), sizeof(float) * 3); // TODO: do we need to write zero normals?
o.write(reinterpret_cast<const char *>(featuresDcCpu[i].data_ptr()), sizeof(float) * featuresDcCpu.size(1));
o.write(reinterpret_cast<const char *>(featuresRestCpu[i].data_ptr()), sizeof(float) * featuresRestCpu.size(1));
o.write(reinterpret_cast<const char *>(opacitiesCpu[i].data_ptr()), sizeof(float) * 1);
o.write(reinterpret_cast<const char *>(scalesCpu[i].data_ptr()), sizeof(float) * 3);
o.write(reinterpret_cast<const char *>(quatsCpu[i].data_ptr()), sizeof(float) * 4);
}
o.close();
std::cout << "Wrote " << filename << std::endl;
}
torch::Tensor Model::mainLoss(torch::Tensor &rgb, torch::Tensor >, float ssimWeight){
torch::Tensor ssimLoss = 1.0f - ssim.eval(rgb, gt);
torch::Tensor l1Loss = l1(rgb, gt);
return (1.0f - ssimWeight) * l1Loss + ssimWeight * ssimLoss;
}
}