-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextureSet.cpp
2207 lines (1841 loc) · 85.7 KB
/
TextureSet.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
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: Copyright (c) 2023-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: LicenseRef-NvidiaProprietary
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "TextureSet.h"
#include "Context.h"
#include "CudaDeviceGuard.h"
#include "CudaRandomGen.h"
#include "Errors.h"
#include "JsonFileFormat.h"
#include "MathUtils.h"
#include "MlpDesc.h"
#include "Optimizer.h"
#include "Quantizer.h"
#include "Regression.h"
#include "SharedTexture.h"
#include "TextureMetadata.h"
#include <cassert>
#include <cinttypes>
/* Note on the data formats and layouts used in various places...
=== Training and CUDA decompression ===
Training and CUDA decompression use FP16 weights and bias vectors. They are stored in the `m_mlpWeightsBase`
and `m_mlpWeightsQuantized` arrays. The "Base" array contains non-quantized weights that are used by the optimizer:
it takes the gradients from the regression kernel and applies them to the base weights. The "Quantized" weights are
used by the regression kernel. They are produced by the optimizer and at that point are not yet quantized. They become
quantized on the next step using the `QuantizeNetwork` calls in the final part of the training session.
Both of these arrays contain two copies of weights: the first set at offset 0 that get Int8 quantization, and
the second set at offset `m_numNetworkParams` that optionally get the FP8 quantization.
There are two parts in each set of weights: the actual layer weights, and the bias vectors. The layer weights are
stored in the obscure "MMA" layout that is compatible with the tensor core matrix multiplication operations. Their size
is equal to the number of elements in all layer matrices, i.e. there are no holes in the layout. Weights for layer 0
are immediately followed by weights for layer 1, and so on until layer 3. After the matrix weights, all bias vectors
are stored consecutively: dense bias vector for layer 0, followed by bias for layer 1, and so on until layer 3.
The FP16 weights and bias vectors are converted into the Int8 or FP8 format and row-major layout by the
`QuantizeNetwork` function after training is complete. These Int8 or FP8 weights are stored in the NTC files.
Before CUDA decompression, these low-precision weights are converted back into FP16 using the
`ConvertNetworkFromQuantizedToFp16` function.
=== Int8 inference ===
There are two flavors of Int8 inference weights: the generic weights that work with any GPU, and the CoopVec specific
weights. The CoopVec weights are derived from the regular (row-major) weights when the texture set is loaded from disk.
See `TextureSetMetadata::LoadWeightsFromStream` and `CoopVecWeightConverter.cpp`.
The generic weights contain three components: the matrix weights, the scale vectors, and the bias vectors. The matrix
weights for all layers are stored in Int8 format and densely packed one after another. Then the scale vectors for all
layers are stored in Float32 format and are densely packed one after another. Finally, the bias vectors for all layers
are stored in Float32 format and also densely packed.
The CoopVec weights follow the same general layout with the matrix weights followed by scale and bias vectors. But the
matrix weights are stored in an opaque CoopVec-compatible layout defined by the GPU driver, potentially different for
various GPUs. This format contains duplicate elements, and normally consumes 2x the space used for regular row-major
weights.
=== FP8 inference ===
Technically, it's hybrid FP8 and Int8 inference: layers 0-2 are using FP8 weights, and the output layer uses Int8
weights. This is done to improve the output precision, which is lacking with FP8 because that format cannot even
represent all integers in the range 0-255.
FP8 weights also come in two flavors, the generic one and the CoopVec specific one. One important difference from Int8
weights is that the generic weights are only used for storage, and not used by any GPU for inference because there are
currently no scalar FP8 operations in GPUs.
The generic weights contain the same 3 components but in 2 types. They are laid out in the following order:
- Matrix weights for layers 0-2 using the FP8 type, in row-major layout
- Matrix weights for layer 3 using the Int8 type, in row-major layout
- Bias vectors for layers 0-2 using the FP16 type
- Scale vector for layer 3 using the FP32 type
- Bias vector for layer 3 using the FP32 type
The CoopVec weights follow the same general layout. Similar to Int8, the matrix weights are converted to the CoopVec-
compatible layout on load, which is normally larger than the dense row-major layout.
=== Important code locations using these layouts ===
| FP16 | GI8* | GFP8 | CVI8 | CVFP8 |
------------------------------------------------+------+------+------+------+-------+
CUDA training and inference | | | | | |
RegressionKernels.h | X | | | | |
Weight quantization and conversion | | | | | |
Quantizer.cu | X | X | X | | |
Serialization | | | | | |
TextureSet::SaveToStream | | X | X | | |
Deserialization | | | | | |
TextureSetMetadata::LoadWeightsFromStream | | X | X | | |
CoopVec layout conversion | | | | | |
CoopVecWeightConverter.cpp | | X | X | X | X |
GAPI decompression | | | | | |
* DecompressINT8.hlsl | | X | | | |
* DecompressCoopVecInt8.slang | | | | X | |
* DecompressCoopVecFP8.slang | | | | | X |
GAPI inference | | | | | |
* Inference.hlsli | | X | | | |
* InferenceCoopVec.hlsli | | | | X | X |
[*] GI8 = GenericInt8, GFP8 = GenericFP8, CVI8 = CoopVecInt8, CVFP8 = CoopVecFP8
These layout descriptions and names match the InferenceWeightType enum declared in ntc.h
*/
namespace ntc
{
constexpr int c_PixelsPerKPixel = 1024; // Obvious, but literals are worse
static const char* NetworkStateToString(TextureSetNetworkState state)
{
switch(state)
{
case TextureSetNetworkState::Empty:
return "Empty";
case TextureSetNetworkState::Initialized:
return "Initialized";
case TextureSetNetworkState::TrainingInProgress:
return "TrainingInProgress";
case TextureSetNetworkState::TrainingFinished:
return "TrainingFinished";
case TextureSetNetworkState::Complete:
return "Complete";
default:
static char string[16];
snprintf(string, sizeof(string), "%d", int(state));
return string;
}
}
TextureSet::TextureSet(IAllocator* allocator, Context const* context, const TextureSetDesc& desc)
: TextureSetMetadata(allocator, desc, LatentShape::Empty())
, m_context(context)
, m_featureGrid(allocator)
, m_lowPrecMlpData(allocator)
, m_lossReduction(allocator)
{
}
TextureSet::~TextureSet()
{
if (m_eventStart)
{
cudaEventDestroy(m_eventStart);
m_eventStart = nullptr;
}
if (m_eventStop)
{
cudaEventDestroy(m_eventStop);
m_eventStop = nullptr;
}
}
Status TextureSet::Initialize(const TextureSetFeatures& features)
{
m_features = features;
// Round up the channel count to a multiple of 2
m_desc.channels = (m_desc.channels + 1) & ~1;
int mipWidth = m_desc.width;
int mipHeight = m_desc.height;
uint64_t mipDataOffset = 0;
m_textureMipOffsets.fill(0);
for (int mipLevel = 0; mipLevel < m_desc.mips; ++mipLevel)
{
int mipSize = mipWidth * mipHeight;
m_textureMipOffsets[mipLevel] = mipDataOffset;
mipDataOffset += mipSize;
mipWidth = std::max(1, mipWidth >> 1);
mipHeight = std::max(1, mipHeight >> 1);
}
m_textureMipOffsets[m_desc.mips] = mipDataOffset;
const size_t textureDataLength = mipDataOffset * m_desc.channels;
if (!m_textureData.Allocate(textureDataLength))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory for the reference texture data.",
m_textureData.Size());
return Status::OutOfMemory;
}
if (features.separateRefOutData && !m_textureDataOut.Allocate(textureDataLength))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory for the output texture data.",
m_textureDataOut.Size());
return Status::OutOfMemory;
}
cudaError_t err;
err = cudaMemset(m_textureData.DevicePtr(), 0, m_textureData.Size());
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaMemset", err);
return Status::CudaError;
}
int const stagingWidth = features.stagingWidth > 0 ? features.stagingWidth : m_desc.width;
int const stagingHeight = features.stagingHeight > 0 ? features.stagingHeight : m_desc.height;
size_t stagingSize = size_t(stagingWidth * stagingHeight) * features.stagingBytesPerPixel;
if (stagingSize != 0 && !m_textureStaging.Allocate(stagingSize))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory for the staging buffer.",
m_textureStaging.Size());
return Status::OutOfMemory;
}
err = cudaEventCreate(&m_eventStart);
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaEventCreate", err);
return Status::CudaError;
}
err = cudaEventCreate(&m_eventStop);
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaEventCreate", err);
return Status::CudaError;
}
return Status::Ok;
}
Status TextureSet::LoadFromStreamPostHeader(json::Document const& document, uint64_t binaryChunkOffset,
uint64_t binaryChunkSize, IStream* inputStream, LatentShape latentShape)
{
Status status = LoadMetadataFromStream(document, binaryChunkOffset, binaryChunkSize, latentShape, inputStream);
if (status != Status::Ok)
return status;
// Validate the neural LOD dimensions here because TextureSetMetadata doesn't do that,
// it is supposed to accept any sizes of latent images and any color->neural mapping.
// The full TextureSet implementation relies on a specific geometry though.
for (int neuralLod = 0; neuralLod < m_latentImages.size(); ++neuralLod)
{
LatentImageDesc const& latentImage = m_latentImages[neuralLod];
int const highResWidth = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::HighRes,
m_desc.width, neuralLod, latentShape.gridSizeScale);
int const highResHeight = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::HighRes,
m_desc.height, neuralLod, latentShape.gridSizeScale);
int const lowResWidth = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::LowRes,
m_desc.width, neuralLod, latentShape.gridSizeScale);
int const lowResHeight = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::LowRes,
m_desc.height, neuralLod, latentShape.gridSizeScale);
if (latentImage.highResWidth != highResWidth || latentImage.highResHeight != highResHeight ||
latentImage.lowResWidth != lowResWidth || latentImage.lowResHeight != lowResHeight)
{
SetErrorMessage("Neural MIP %d dimensions (%dx%d and %dx%d) don't match "
"the expected dimensions (%dx%d and %dx%d)",
neuralLod,
latentImage.highResWidth,
latentImage.highResHeight,
latentImage.lowResWidth,
latentImage.lowResHeight,
highResWidth,
highResHeight,
lowResWidth,
lowResHeight);
return Status::FileUnrecognized;
}
}
// Validate the color->neural LOD mapping, same reason as neural LOD dimensions above.
for (int mipLevel = 0; mipLevel < m_desc.mips; ++mipLevel)
{
int const expectedNeuralLod = FeatureGridMath::LodToNeuralLod(mipLevel,
m_latentShape.gridSizeScale, GetNumLatentImages());
if (m_colorMips[mipLevel].neuralLod != expectedNeuralLod)
{
SetErrorMessage("Color MIP %d specifies latent image index %d, but it is expected to be %d.",
mipLevel, m_colorMips[mipLevel].neuralLod, expectedNeuralLod);
return Status::FileUnrecognized;
}
}
// Reset m_mlpDesc and m_latentShape so that SetLatentShape doesn't exit right away
int const networkVersion = m_mlpDesc->networkVersion;
m_mlpDesc = nullptr;
m_latentShape = LatentShape::Empty();
status = SetLatentShape(latentShape, networkVersion);
if (status != Status::Ok)
return status;
// MLP data
status = LoadWeightsFromStream(document, inputStream, m_context->GetGraphicsResources());
if (status != Status::Ok)
return status;
if (m_rowMajorWeightDataInt8.data())
{
if (m_lowPrecMlpData.Size() < m_rowMajorWeightDataInt8.size())
{
SetErrorMessage("Inconsistent sizes for MLP data");
return Status::InternalError;
}
memcpy(m_lowPrecMlpData.HostPtr(), m_rowMajorWeightDataInt8.data(), m_rowMajorWeightDataInt8.size());
}
if (m_rowMajorWeightDataFP8.data())
{
if (m_lowPrecMlpData.Size() < m_mlpDataSizeInt8 + m_rowMajorWeightDataFP8.size())
{
SetErrorMessage("Inconsistent sizes for MLP data");
return Status::InternalError;
}
memcpy(m_lowPrecMlpData.HostPtr() + m_mlpDataSizeInt8,
m_rowMajorWeightDataFP8.data(), m_rowMajorWeightDataFP8.size());
m_networkHasFP8Weights = true;
}
else
{
m_networkHasFP8Weights = false;
}
// Grid (latents) data
for (int i = 0; i < m_featureGrid.GetNumMipLevels(); ++i)
{
json::LatentImage const& latentImage = document.latents[i];
if (!ReadViewFromStream(inputStream, document, latentImage.highResView,
m_featureGrid.GetEncodedLatentsHostPtr(FeatureGrid::Grid::HighRes, i),
m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::HighRes, i)))
return Status::IOError;
if (!ReadViewFromStream(inputStream, document, latentImage.lowResView,
m_featureGrid.GetEncodedLatentsHostPtr(FeatureGrid::Grid::LowRes, i),
m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::LowRes, i)))
return Status::IOError;
}
// Deserialized network is equivalent to one that's just completed training, both can be decompressed.
m_networkState = TextureSetNetworkState::Complete;
ClearErrorMessage();
return Status::Ok;
}
Status TextureSet::SetLatentShape(LatentShape const& newShape, int networkVersion)
{
// Early out if we already have the same shape
if (m_latentShape == newShape &&
((GetNetworkVersion() == networkVersion) || (networkVersion == NTC_NETWORK_UNKNOWN)))
return Status::Ok;
Status status = ValidateLatentShape(newShape, networkVersion);
if (status != Status::Ok)
return status;
CudaDeviceGuard cudaGuard(m_context);
if (!cudaGuard.Success())
return Status::CudaError;
m_latentShape = newShape;
m_networkState = TextureSetNetworkState::Empty;
// Deallocate all the TextureSet buffers in case they existed before
m_featureGrid.Deallocate();
m_mlpWeightsQuantized.Deallocate();
m_lowPrecMlpData.Deallocate();
m_weightGradients.Deallocate();
m_mlpWeightsBase.Deallocate();
m_mlpMoment1.Deallocate();
m_mlpMoment2.Deallocate();
m_loss.Deallocate();
m_lossReduction.Deallocate();
// Early out if the new shape is empty
if (newShape.IsEmpty())
{
m_mlpDesc = nullptr;
ClearErrorMessage();
return Status::Ok;
}
if (networkVersion == NTC_NETWORK_UNKNOWN)
m_mlpDesc = MlpDesc::PickOptimalConfig(m_latentShape.highResFeatures, m_latentShape.lowResFeatures);
else
m_mlpDesc = MlpDesc::FromNetworkVersion(networkVersion);
status = m_featureGrid.Initialize(m_desc.width, m_desc.height, m_desc.mips, m_latentShape.gridSizeScale,
m_latentShape.highResFeatures, m_latentShape.lowResFeatures, m_latentShape.highResQuantBits,
m_latentShape.lowResQuantBits, m_features.enableCompression);
if (status != Status::Ok)
{
// TODO: move this to FeatureGrid, expand the specific errors.
SetErrorMessage("Failed to initialize the feature grid.");
return status;
}
// Trainable MLP parameters: weights and bias. No scales at training time, they are added during quantization.
m_numNetworkParams = m_mlpDesc->GetWeightCount() + m_mlpDesc->GetLayerOutputCount();
if (!m_mlpWeightsQuantized.Allocate(m_numNetworkParams * 2))
{
SetErrorMessage("Failed to allocate %zu bytes of device+host memory for the MLP "
"weights buffer (quantized).", m_mlpWeightsQuantized.Size());
return Status::OutOfMemory;
}
// Int8: One int8 per weight + two floats per output (scale and bias)
// FP8: One uint8 per weight + two half per output <-- smaller than int8
m_mlpDataSizeInt8 = size_t(m_mlpDesc->GetWeightCount())
+ size_t(m_mlpDesc->GetLayerOutputCount()) * 2 * sizeof(float);
if (!m_lowPrecMlpData.Allocate(m_mlpDataSizeInt8 * 2))
{
SetErrorMessage("Failed to allocate %zu bytes of device+host memory "
"for the Int8 MLP data buffer.", m_lowPrecMlpData.Size());
return Status::OutOfMemory;
}
size_t requiredLossLength = 0;
if (m_features.enableCompression)
{
// Allocate the loss array for the maximum supported batch size.
// With the current values (NTC_MAX_KPIXELS_PER_BATCH = 2048, LOCAL_PIXELS = 64), that's just 32K floats.
constexpr size_t maxPixelsPerBatch = NTC_MAX_KPIXELS_PER_BATCH * c_PixelsPerKPixel;
constexpr size_t lossLength = maxPixelsPerBatch / LOCAL_PIXELS;
requiredLossLength = lossLength;
constexpr size_t maxGradientSlices = (NTC_MAX_KPIXELS_PER_BATCH * c_PixelsPerKPixel)
/ (TILE_SIZE_X * TB_SIZE_Y); // assume NW_GRAD_ATOMICS = false
if (!m_weightGradients.Allocate(m_numNetworkParams * maxGradientSlices))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory "
"for the weight gradients buffer.", m_weightGradients.Size());
return Status::OutOfMemory;
}
// Two versions of MLP weights - for int8 and fp8 optimization
if (!m_mlpWeightsBase.Allocate(m_numNetworkParams * 2))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory "
"for the MLP weights buffer (base).", m_mlpWeightsBase.Size());
return Status::OutOfMemory;
}
if (!m_mlpMoment1.Allocate(m_numNetworkParams))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory "
"for the MLP 1st moments buffer.", m_mlpMoment1.Size());
return Status::OutOfMemory;
}
if (!m_mlpMoment2.Allocate(m_numNetworkParams))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory "
"for the MLP 2nd moments buffer.", m_mlpMoment2.Size());
return Status::OutOfMemory;
}
}
// Loss for the CUDA decompression pass
size_t const lossLength = (m_desc.width * m_desc.height + LOCAL_PIXELS - 1) / LOCAL_PIXELS * NTC_MAX_CHANNELS;
requiredLossLength = std::max(requiredLossLength, lossLength);
if (!m_loss.Allocate(requiredLossLength))
{
SetErrorMessage("Failed to allocate %zu bytes of device memory "
"for the loss buffer.", m_loss.Size());
return Status::OutOfMemory;
}
size_t lossReductionLength = (requiredLossLength + cuda::LOSS_ITEMS_PER_GROUP - 1) / cuda::LOSS_ITEMS_PER_GROUP;
if (!m_lossReduction.Allocate(lossReductionLength))
{
SetErrorMessage("Failed to allocate %zu bytes of device+host memory "
"for the loss reduction buffer.", m_lossReduction.Size());
return Status::OutOfMemory;
}
// Fill the neural LOD indexing cache
m_colorMips.fill(ColorMipDesc());
for (int mipLevel = 0; mipLevel < m_desc.mips; ++mipLevel)
{
ColorMipDesc& colorMip = m_colorMips[mipLevel];
colorMip.neuralLod = m_featureGrid.LodToNeuralLod(mipLevel);
FeatureGridMath::GetPositionLodAndScale(colorMip.neuralLod, mipLevel,
colorMip.positionLod,
colorMip.positionScale);
}
// Fill the latent image dimension cache
m_latentImages.clear();
for (int neuralLod = 0; neuralLod < m_featureGrid.GetNumMipLevels(); ++neuralLod)
{
LatentImageDesc& imageDesc = m_latentImages.emplace_back();
imageDesc.highResWidth = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::HighRes,
m_desc.width, neuralLod, m_latentShape.gridSizeScale);
imageDesc.highResHeight = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::HighRes,
m_desc.height, neuralLod, m_latentShape.gridSizeScale);
imageDesc.lowResWidth = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::LowRes,
m_desc.width, neuralLod, m_latentShape.gridSizeScale);
imageDesc.lowResHeight = FeatureGridMath::GetGridDimension(FeatureGridMath::Grid::LowRes,
m_desc.height, neuralLod, m_latentShape.gridSizeScale);
}
ClearErrorMessage();
return Status::Ok;
}
uint64_t TextureSet::GetOutputStreamSize()
{
// Headers
uint64_t size = json::JsonChunkSizeLimit;
// Texture names and BC acceleration data
for (const auto& info : m_textureInfos)
{
size_t bcDataSize = 0;
info->GetBlockCompressionModeHistogram(nullptr, &bcDataSize);
size += info->GetNameString().size() + bcDataSize;
}
// MLP
size += m_lowPrecMlpData.Size();
// Grids
for (int i = 0; i < m_featureGrid.GetNumMipLevels(); ++i)
{
size += m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::HighRes, i);
size += m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::LowRes, i);
}
size = RoundUp4(size);
return size;
}
// If the current output position in the stream is not a multiple of 4 bytes, write some zeros until it is.
// Note: alignment of MLP and latent data in the stream is important for GAPI decompression, so that
// we can load the entire file into a RawAddressBuffer and safely read uint's from it on the GPU.
static bool PadStreamTo4Bytes(IStream* outputStream)
{
uint64_t actualOffset = outputStream->Tell();
uint32_t padding = 0;
if (actualOffset & 3)
return outputStream->Write(&padding, 4 - (actualOffset & 3));
return true;
}
Status TextureSet::SaveToStream(IStream* outputStream)
{
if (!outputStream)
{
SetErrorMessage("outputStream is NULL.");
return Status::InvalidArgument;
}
if (m_networkState != TextureSetNetworkState::Complete)
{
SetErrorMessage("Invalid network state for SaveToStream (%s), must be Complete.",
NetworkStateToString(m_networkState));
return Status::InvalidState;
}
json::Document document(m_allocator);
document.width = m_desc.width;
document.height = m_desc.height;
document.numChannels = m_desc.channels;
document.numColorMips = m_desc.mips;
document.latentShape = json::LatentShape(m_allocator);
document.latentShape->highResFeatures = m_latentShape.highResFeatures;
document.latentShape->lowResFeatures = m_latentShape.lowResFeatures;
document.latentShape->highResQuantBits = m_latentShape.highResQuantBits;
document.latentShape->lowResQuantBits = m_latentShape.lowResQuantBits;
// Store the int8 MLP in the legacy descriptor for file compatibility with older code.
// Note: When moving it to the mlpVersions vector, use mlpVersions.reserve(2) to avoid segfaults.
document.mlp = json::MLP(m_allocator);
json::MLP& mlpInt8 = *document.mlp;
mlpInt8.activation = json::ActivationType::HGELUClamp;
mlpInt8.weightLayout = json::MatrixLayout::RowMajor;
mlpInt8.weightType = json::MlpDataType::Int8;
mlpInt8.scaleBiasType = json::MlpDataType::Float32;
uint64_t binaryChunkSize = 0;
auto appendView = [&document, &binaryChunkSize](uint64_t size) {
uint32_t const viewIndex = uint32_t(document.views.size());
json::BufferView& view = document.views.emplace_back(document.allocator);
view.offset = binaryChunkSize;
view.storedSize = size;
binaryChunkSize += RoundUp4(size);
return viewIndex;
};
// Fill out the MLP layers - Int8
for (int layerIndex = 0; layerIndex < NTC_MLP_LAYERS; ++layerIndex)
{
json::MLPLayer& layer = mlpInt8.layers.emplace_back(m_allocator);
layer.inputChannels = m_mlpDesc->GetLayerInputChannels(layerIndex);
layer.outputChannels = m_mlpDesc->GetLayerOutputChannels(layerIndex);
layer.weightView = appendView(layer.inputChannels * layer.outputChannels);
layer.scaleView = appendView(layer.outputChannels * sizeof(float));
layer.biasView = appendView(layer.outputChannels * sizeof(float));
}
json::MLP* mlpFP8 = nullptr;
if (m_networkHasFP8Weights)
{
mlpFP8 = &document.mlpVersions.emplace_back(m_allocator);
mlpFP8->activation = json::ActivationType::HGELUClamp;
mlpFP8->weightLayout = json::MatrixLayout::RowMajor;
mlpFP8->weightType = json::MlpDataType::FloatE4M3;
mlpFP8->scaleBiasType = json::MlpDataType::Float16;
// Fill out the MLP layers - FP8
// The MLP versions need to be in separate loops to keep view offsets consistent with the actual writing order below
for (int layerIndex = 0; layerIndex < NTC_MLP_LAYERS; ++layerIndex)
{
json::MLPLayer& layer = mlpFP8->layers.emplace_back(m_allocator);
layer.inputChannels = m_mlpDesc->GetLayerInputChannels(layerIndex);
layer.outputChannels = m_mlpDesc->GetLayerOutputChannels(layerIndex);
layer.weightView = appendView(layer.inputChannels * layer.outputChannels);
if (layerIndex == NTC_MLP_LAYERS - 1)
{
// Output layer has int8 weights and fp32 scale+bias
layer.scaleView = appendView(layer.outputChannels * sizeof(float));
layer.biasView = appendView(layer.outputChannels * sizeof(float));
layer.weightType = json::MlpDataType::Int8;
layer.scaleBiasType = json::MlpDataType::Float32;
}
else
{
// Other layers have fp8 weights and fp16 bias
layer.biasView = appendView(layer.outputChannels * sizeof(half));
}
}
}
// Fill out the textures
for (const auto& info : m_textureInfos)
{
json::Texture& texture = document.textures.emplace_back(m_allocator);
texture.name = info->GetNameString();
texture.firstChannel = info->GetFirstChannel();
texture.numChannels = info->GetNumChannels();
texture.channelFormat = info->GetChannelFormat();
if (info->GetRgbColorSpace() != ColorSpace::Linear)
texture.rgbColorSpace = info->GetRgbColorSpace();
if (info->GetAlphaColorSpace() != ColorSpace::Linear)
texture.alphaColorSpace = info->GetAlphaColorSpace();
if (info->GetBlockCompressedFormat() != BlockCompressedFormat::None)
texture.bcFormat = info->GetBlockCompressedFormat();
if (info->GetBlockCompressionQuality() != BlockCompressionMaxQuality)
texture.bcQuality = info->GetBlockCompressionQuality();
if (info->HasBlockCompressionAccelerationData())
{
size_t bcDataSize = 0;
info->GetBlockCompressionModeHistogram(nullptr, &bcDataSize);
texture.bcAccelerationDataView = appendView(bcDataSize);
}
}
// Fill out the channels
for (int channelIndex = 0; channelIndex < m_desc.channels; ++channelIndex)
{
json::Channel& channel = document.channels.emplace_back(m_allocator);
channel.scale = m_channelInfos[channelIndex].optimalToLinearScale;
channel.bias = m_channelInfos[channelIndex].optimalToLinearBias;
if (m_channelColorSpaces[channelIndex] != ColorSpace::Linear)
channel.colorSpace = m_channelColorSpaces[channelIndex];
}
// Fill out the latent image descriptors
for (int neuralLod = 0; neuralLod < m_featureGrid.GetNumMipLevels(); ++neuralLod)
{
LatentImageDesc const& src = m_latentImages[neuralLod];
json::LatentImage& image = document.latents.emplace_back(m_allocator);
image.highResWidth = src.highResWidth;
image.highResHeight = src.highResHeight;
image.lowResWidth = src.lowResWidth;
image.lowResHeight = src.lowResHeight;
image.highResBitsPerPixel = m_latentShape.highResFeatures * m_latentShape.highResQuantBits;
image.lowResBitsPerPixel = m_latentShape.lowResFeatures * m_latentShape.lowResQuantBits;
image.highResView = appendView(m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::HighRes, neuralLod));
image.lowResView = appendView(m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::LowRes, neuralLod));
}
// Fill out the color MIP descriptors
for (int mipLevel = 0; mipLevel < m_desc.mips; ++mipLevel)
{
json::ColorMip& mip = document.colorMips.emplace_back(m_allocator);
mip.width = std::max(m_desc.width >> mipLevel, 1);
mip.height = std::max(m_desc.height >> mipLevel, 1);
mip.latentMip = m_colorMips[mipLevel].neuralLod;
mip.positionLod = m_colorMips[mipLevel].positionLod;
mip.positionScale = m_colorMips[mipLevel].positionScale;
}
// Serialize the document into a JSON string
String jsonString(m_allocator);
String errorMessage(m_allocator);
if (!json::SerializeDocument(document, jsonString, errorMessage))
{
// Serialization failed - that should never happen if the saving code is correct.
SetUnformattedErrorMessage(errorMessage.c_str());
return Status::InternalError;
}
// Write the container header
json::FileHeader header;
header.jsonChunkOffset = sizeof(json::FileHeader);
header.jsonChunkSize = jsonString.size() + 1;
header.binaryChunkOffset = RoundUp4(header.jsonChunkOffset + header.jsonChunkSize);
header.binaryChunkSize = binaryChunkSize;
if (!outputStream->Write(&header, sizeof(header)))
return Status::IOError;
if (!outputStream->Write(jsonString.c_str(), jsonString.size() + 1))
return Status::IOError;
if (!PadStreamTo4Bytes(outputStream))
return Status::IOError;
auto validateOffset = [&document, &header, &outputStream](uint32_t view) {
uint64_t expectedOffset = document.views[view].offset + header.binaryChunkOffset;
uint64_t actualOffset = outputStream->Tell();
assert(actualOffset == expectedOffset);
};
// Write the MLP data
auto writeMlpData = [this, &outputStream, &validateOffset]
(json::MLP const& mlp, size_t dataOffset, bool useFP8)
{
// See the comment block in the beginning of this file for the weight layouts
size_t mlpWeightsOffset = dataOffset;
size_t mlpScaleOffset = dataOffset + m_mlpDesc->GetWeightCount();
size_t mlpBiasOffset = useFP8
? mlpScaleOffset
: mlpScaleOffset + m_mlpDesc->GetLayerOutputCount() * sizeof(float);
for (int layerIndex = 0; layerIndex < NTC_MLP_LAYERS; ++layerIndex)
{
json::MLPLayer const& layer = mlp.layers[layerIndex];
validateOffset(layer.weightView);
size_t const layerWeightsSize = layer.inputChannels * layer.outputChannels;
if (!outputStream->Write(m_lowPrecMlpData.HostPtr() + mlpWeightsOffset, layerWeightsSize))
return Status::IOError;
if (!PadStreamTo4Bytes(outputStream))
return Status::IOError;
mlpWeightsOffset += layerWeightsSize;
bool const outputLayer = layerIndex == NTC_MLP_LAYERS - 1;
size_t scaleBiasElemSize = (useFP8 && !outputLayer) ? sizeof(half) : sizeof(float);
size_t const scaleOrBiasSize = layer.outputChannels * scaleBiasElemSize;
if (useFP8 && outputLayer)
{
mlpScaleOffset = mlpBiasOffset;
mlpBiasOffset += scaleOrBiasSize;
}
if (layer.scaleView.has_value())
{
validateOffset(*layer.scaleView);
if (!outputStream->Write(m_lowPrecMlpData.HostPtr() + mlpScaleOffset, scaleOrBiasSize))
return Status::IOError;
mlpScaleOffset += scaleOrBiasSize;
}
validateOffset(layer.biasView);
if (!outputStream->Write(m_lowPrecMlpData.HostPtr() + mlpBiasOffset, scaleOrBiasSize))
return Status::IOError;
mlpBiasOffset += scaleOrBiasSize;
}
return Status::Ok;
};
Status status = writeMlpData(mlpInt8, 0, false);
if (status != Status::Ok)
return status;
if (mlpFP8)
{
status = writeMlpData(*mlpFP8, m_mlpDataSizeInt8, true);
if (status != Status::Ok)
return status;
}
// Write the texture BC data
for (int textureIndex = 0; textureIndex < int(m_textureInfos.size()); ++textureIndex)
{
auto const& info = m_textureInfos[textureIndex];
json::Texture const& texture = document.textures[textureIndex];
void const* bcData = nullptr;
size_t bcDataSize = 0;
info->GetBlockCompressionModeHistogram(&bcData, &bcDataSize);
if (bcDataSize != 0)
{
assert(texture.bcAccelerationDataView.has_value());
validateOffset(*texture.bcAccelerationDataView);
if (!outputStream->Write(bcData, bcDataSize))
return Status::IOError;
if (!PadStreamTo4Bytes(outputStream))
return Status::IOError;
}
}
// Write the latents data
for (int neuralLod = 0; neuralLod < m_featureGrid.GetNumMipLevels(); ++neuralLod)
{
json::LatentImage const& image = document.latents[neuralLod];
validateOffset(image.highResView);
if (!outputStream->Write(
m_featureGrid.GetEncodedLatentsHostPtr(FeatureGrid::Grid::HighRes, neuralLod),
m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::HighRes, neuralLod)))
return Status::IOError;
validateOffset(image.lowResView);
if (!outputStream->Write(
m_featureGrid.GetEncodedLatentsHostPtr(FeatureGrid::Grid::LowRes, neuralLod),
m_featureGrid.GetQuantizedLatentsSize(FeatureGrid::Grid::LowRes, neuralLod)))
return Status::IOError;
}
// Verify that we've written no more than the number of bytes predicted by GetOutputStreamSize
uint64_t expectedSize = GetOutputStreamSize();
uint64_t actualSize = outputStream->Tell();
if (actualSize > expectedSize)
{
SetErrorMessage("SaveToStream produced a stream with %" PRIu64 " bytes, while GetOutputStreamSize "
"predicted no more than %" PRIu64 " bytes.", actualSize, expectedSize);
return Status::InternalError;
}
ClearErrorMessage();
return Status::Ok;
}
Status TextureSet::LoadFromStream(IStream* stream)
{
if (!stream)
{
SetErrorMessage("inputStream is NULL.");
return Status::InvalidArgument;
}
json::Document document(m_allocator);
uint64_t binaryChunkOffset, binaryChunkSize;
Status status = LoadFileHeadersFromStream(m_allocator, stream, document, binaryChunkOffset, binaryChunkSize);
if (status != Status::Ok)
return status;
TextureSetDesc desc;
LatentShape latentShape;
status = TextureSetMetadata::DeserializeTextureSetDesc(document, desc, latentShape);
if (status != Status::Ok)
return status;
if (desc != m_desc)
{
SetErrorMessage("Incompatible texture set in the file - dimensions do not match.");
return Status::FileIncompatible;
}
return LoadFromStreamPostHeader(document, binaryChunkOffset, binaryChunkSize, stream, latentShape);
}
Status TextureSet::SaveToMemory(void *pData, size_t* pSize)
{
if (!pSize)
{
SetErrorMessage("pSize is NULL");
return Status::InvalidArgument;
}
MemoryStreamWrapper stream(m_context);
Status status = m_context->OpenMemory(pData, *pSize, stream.ptr());
if (status != Status::Ok)
return status;
status = SaveToStream(stream);
if (status != Status::Ok)
return status;
*pSize = size_t(stream->Tell());
return Status::Ok;
}
Status TextureSet::LoadFromMemory(void const *pData, size_t size)
{
MemoryStreamWrapper stream(m_context);
Status status = m_context->OpenReadOnlyMemory(pData, size, stream.ptr());
if (status != Status::Ok)
return status;
return LoadFromStream(stream);
}
Status TextureSet::SaveToFile(char const *fileName)
{
FileStreamWrapper stream(m_context);
Status status = m_context->OpenFile(fileName, true, stream.ptr());
if (status != Status::Ok)
return status;
return SaveToStream(stream);
}
Status TextureSet::LoadFromFile(char const *fileName)
{
FileStreamWrapper stream(m_context);
Status status = m_context->OpenFile(fileName, false, stream.ptr());
if (status != Status::Ok)
return status;
return LoadFromStream(stream);
}
Status TextureSet::WriteChannels(WriteChannelsParameters const& params)
{
if (!params.pData)
{
SetErrorMessage("pData is NULL.");
return Status::InvalidArgument;
}
const size_t sizeToCopy = size_t(params.height) * params.rowPitch;
Status status = ValidateReadWriteChannelsArgs(params.mipLevel, params.firstChannel, params.numChannels,
params.width, params.height, params.pixelStride, params.rowPitch, sizeToCopy, params.channelFormat);
if (status != Status::Ok)
return status;
// Make sure that the user doesn't accidentally overwrite some texture data while training is in progress.
// That wouldn't affect the training process, which may be unexpected.
if (m_networkState != TextureSetNetworkState::Empty &&
m_networkState != TextureSetNetworkState::Complete)
{
SetErrorMessage("Invalid network state (%s) for WriteChannels, must be Empty or Complete.",
NetworkStateToString(m_networkState));
return Status::InvalidState;
}
CudaDeviceGuard cudaGuard(m_context);
if (!cudaGuard.Success())
return Status::CudaError;
if (params.addressSpace == AddressSpace::Host)
{
cudaError_t err = cudaMemcpy(m_textureStaging.DevicePtr(), params.pData, sizeToCopy, cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
SetCudaErrorMessage("cudaMemcpy", err);
return Status::CudaError;