-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContext.cpp
1322 lines (1105 loc) · 50.7 KB
/
Context.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 "AdaptiveCompressionSession.h"
#include "Context.h"
#include "CoopVecWeightConverter.h"
#include "CudaDeviceGuard.h"
#include "Errors.h"
#include "GraphicsResources.h"
#include "JsonFileFormat.h"
#include "MathUtils.h"
#include "Shaders.h"
#include "Stream.h"
#include "TextureMetadata.h"
#include "TextureSetMetadata.h"
#if NTC_WITH_CUDA
#include "Regression.h"
#include "SharedTexture.h"
#include "TextureSet.h"
#endif
#include <cinttypes>
#include <cassert>
#include <cmath>
#include <cstring>
#include <libntc/shaders/DecompressConstants.h>
#include <libntc/shaders/BlockCompressConstants.h>
#include <libntc/shaders/ImageDifferenceConstants.h>
namespace ntc
{
Context::Context(ContextParameters const& params)
: m_allocator(params.pAllocator)
, m_cudaDevice(params.cudaDevice)
{
if (params.graphicsApi != GraphicsAPI::None)
{
m_graphicsResources = new (m_allocator->Allocate(sizeof(GraphicsResources))) GraphicsResources(params);
}
}
Context::~Context()
{
if (m_graphicsResources)
{
m_graphicsResources->~GraphicsResources();
m_allocator->Deallocate(m_graphicsResources, sizeof(GraphicsResources));
m_graphicsResources = nullptr;
}
}
Status Context::OpenFile(const char* fileName, bool write, IStream** pOutStream) const
{
if (!fileName)
{
SetErrorMessage("fileName is NULL.");
return Status::InvalidArgument;
}
if (!pOutStream)
{
SetErrorMessage("pOutStream is NULL.");
return Status::InvalidArgument;
}
FILE* file = fopen(fileName, write ? "wb" : "rb");
if (!file)
{
SetErrorMessage("Cannot open file '%s': %s.", fileName, strerror(errno));
return Status::FileUnavailable;
}
*pOutStream = new(m_allocator->Allocate(sizeof(FileStream)))FileStream(file);
return Status::Ok;
}
void Context::CloseFile(IStream* stream) const
{
if (!stream)
return;
stream->~IStream();
m_allocator->Deallocate(stream, sizeof(FileStream));
}
Status Context::OpenMemory(void* pData, size_t size, IStream** pOutStream) const
{
if (!pData)
{
SetErrorMessage("pData is NULL.");
return Status::InvalidArgument;
}
if (size == 0)
{
SetErrorMessage("size is 0.");
return Status::InvalidArgument;
}
if (!pOutStream)
{
SetErrorMessage("pOutStream is NULL.");
return Status::InvalidArgument;
}
*pOutStream = new(m_allocator->Allocate(sizeof(MemoryStream)))MemoryStream(
static_cast<uint8_t*>(pData), size, false);
return Status::Ok;
}
Status Context::OpenReadOnlyMemory(void const* pData, size_t size, IStream** pOutStream) const
{
if (!pData)
{
SetErrorMessage("pData is NULL.");
return Status::InvalidArgument;
}
if (size == 0)
{
SetErrorMessage("size is 0.");
return Status::InvalidArgument;
}
if (!pOutStream)
{
SetErrorMessage("pOutStream is NULL.");
return Status::InvalidArgument;
}
*pOutStream = new(m_allocator->Allocate(sizeof(MemoryStream)))MemoryStream(
const_cast<uint8_t*>(static_cast<uint8_t const*>(pData)), size, true);
return Status::Ok;
}
void Context::CloseMemory(IStream* stream) const
{
if (!stream)
return;
stream->~IStream();
m_allocator->Deallocate(stream, sizeof(MemoryStream));
}
Status Context::CreateTextureSet(const TextureSetDesc& desc,
const TextureSetFeatures& features, ITextureSet** pOutTextureSet) const
{
#if NTC_WITH_CUDA
if (!pOutTextureSet)
{
SetErrorMessage("pOutTextureSet is NULL.");
return Status::InvalidArgument;
}
if (!IsCudaAvailable())
{
SetErrorMessage("Cannot create a TextureSet object when no suitable CUDA device is available.");
return Status::CudaUnavailable;
}
CudaDeviceGuard cudaGuard(this);
if (!cudaGuard.Success())
return Status::CudaError;
Status status = TextureSetMetadata::ValidateTextureSetDesc(desc);
if (status != Status::Ok)
return status;
TextureSet* textureSet = new(m_allocator->Allocate(sizeof(TextureSet)))
TextureSet(m_allocator, this, desc);
status = textureSet->Initialize(features);
if (status != Status::Ok)
{
DestroyTextureSet(textureSet);
return status;
}
*pOutTextureSet = textureSet;
ClearErrorMessage();
return Status::Ok;
#else
SetErrorMessage("Cannot create TextureSet objects when LibNTC was compiled without CUDA support.");
return Status::CudaUnavailable;
#endif
}
void Context::DestroyTextureSet(ITextureSet* textureSet) const
{
#if NTC_WITH_CUDA
if (!textureSet)
return;
CudaDeviceGuard cudaGuard(this);
if (!cudaGuard.Success())
return;
TextureSet* implementation = dynamic_cast<TextureSet*>(textureSet);
textureSet->~ITextureSet();
m_allocator->Deallocate(implementation, sizeof(TextureSet));
#endif
}
Status Context::CreateTextureSetMetadataFromStream(IStream* inputStream, ITextureSetMetadata** pOutMetadata) const
{
if (!pOutMetadata)
{
SetErrorMessage("pOutMetadata is NULL.");
return Status::InvalidArgument;
}
if (!inputStream)
{
SetErrorMessage("inputStream is NULL.");
return Status::InvalidArgument;
}
json::Document document(m_allocator);
uint64_t binaryChunkOffset, binaryChunkSize;
Status status = TextureSetMetadata::LoadFileHeadersFromStream(m_allocator, inputStream, 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;
TextureSetMetadata* textureSetMetadata = new(m_allocator->Allocate(sizeof(TextureSetMetadata)))
TextureSetMetadata(m_allocator, desc, latentShape);
status = textureSetMetadata->LoadMetadataFromStream(document, binaryChunkOffset, binaryChunkSize,
latentShape, inputStream);
if (status == Status::Ok)
{
status = textureSetMetadata->LoadWeightsFromStream(document, inputStream, m_graphicsResources);
}
if (status != Status::Ok)
{
DestroyTextureSetMetadata(textureSetMetadata);
return status;
}
ClearErrorMessage();
*pOutMetadata = textureSetMetadata;
return Status::Ok;
}
void Context::DestroyTextureSetMetadata(ITextureSetMetadata* textureSetMetadata) const
{
if (!textureSetMetadata)
return;
TextureSetMetadata* implementation = dynamic_cast<TextureSetMetadata*>(textureSetMetadata);
textureSetMetadata->~ITextureSetMetadata();
m_allocator->Deallocate(implementation, sizeof(TextureSetMetadata));
}
Status Context::CreateCompressedTextureSetFromStream(IStream* inputStream,
const TextureSetFeatures& features, ITextureSet** pOutTextureSet) const
{
#if NTC_WITH_CUDA
if (!pOutTextureSet)
{
SetErrorMessage("pOutTextureSet is NULL.");
return Status::InvalidArgument;
}
if (!inputStream)
{
SetErrorMessage("inputStream is NULL.");
return Status::InvalidArgument;
}
if (!IsCudaAvailable())
{
SetErrorMessage("Cannot create a TextureSet object when no suitable CUDA device is available.");
return Status::CudaUnavailable;
}
CudaDeviceGuard cudaGuard(this);
if (!cudaGuard.Success())
return Status::CudaError;
json::Document document(m_allocator);
uint64_t binaryChunkOffset, binaryChunkSize;
Status status = TextureSetMetadata::LoadFileHeadersFromStream(m_allocator, inputStream, 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;
TextureSet* textureSet = nullptr;
status = CreateTextureSet(desc, features, (ITextureSet**)&textureSet);
if (status != Status::Ok)
return status;
status = textureSet->LoadFromStreamPostHeader(document, binaryChunkOffset, binaryChunkSize, inputStream, latentShape);
if (status != Status::Ok)
{
DestroyTextureSet(textureSet);
return status;
}
*pOutTextureSet = textureSet;
ClearErrorMessage();
return Status::Ok;
#else
SetErrorMessage("Cannot create TextureSet objects when LibNTC was compiled without CUDA support.");
return Status::CudaUnavailable;
#endif
}
Status Context::CreateCompressedTextureSetFromMemory(void const* pData, size_t size,
const TextureSetFeatures& features, ITextureSet** pOutTextureSet) const
{
MemoryStreamWrapper stream(this);
Status status = OpenReadOnlyMemory(pData, size, stream.ptr());
if (status != Status::Ok)
return status;
return CreateCompressedTextureSetFromStream(stream, features, pOutTextureSet);
}
Status Context::CreateCompressedTextureSetFromFile(char const* fileName,
const TextureSetFeatures& features, ITextureSet** pOutTextureSet) const
{
FileStreamWrapper stream(this);
Status status = OpenFile(fileName, false, stream.ptr());
if (status != Status::Ok)
return status;
return CreateCompressedTextureSetFromStream(stream, features, pOutTextureSet);
}
Status Context::RegisterSharedTexture(const SharedTextureDesc& desc, ISharedTexture** pOutTexture) const
{
#if NTC_WITH_CUDA
if (!pOutTexture)
{
SetErrorMessage("pOutTexture is NULL.");
return Status::InvalidArgument;
}
if (!IsCudaAvailable())
{
SetErrorMessage("Cannot create a SharedTexture object when no suitable CUDA device is available.");
return Status::CudaUnavailable;
}
CudaDeviceGuard cudaGuard(this);
if (!cudaGuard.Success())
return Status::CudaError;
SharedTexture* sharedTexture = new(m_allocator->Allocate(sizeof(SharedTexture))) SharedTexture(desc);
Status status = sharedTexture->Initialize();
if (status != Status::Ok)
{
ReleaseSharedTexture(sharedTexture);
return status;
}
*pOutTexture = sharedTexture;
ClearErrorMessage();
return Status::Ok;
#else
SetErrorMessage("Cannot create SharedTexture objects when LibNTC was compiled without CUDA support.");
return Status::CudaUnavailable;
#endif
}
void Context::ReleaseSharedTexture(ISharedTexture* texture) const
{
#if NTC_WITH_CUDA
if (!texture)
return;
CudaDeviceGuard cudaGuard(this);
if (!cudaGuard.Success())
return;
texture->~ISharedTexture();
m_allocator->Deallocate(texture, sizeof(SharedTexture));
#endif
}
Status Context::CreateAdaptiveCompressionSession(IAdaptiveCompressionSession** pOutSession) const
{
if (!pOutSession)
{
SetErrorMessage("pOutSession is NULL");
return Status::InvalidArgument;
}
*pOutSession = new (m_allocator->Allocate(sizeof(AdaptiveCompressionSession))) AdaptiveCompressionSession();
ClearErrorMessage();
return Status::Ok;
}
void Context::DestroyAdaptiveCompressionSession(IAdaptiveCompressionSession *session) const
{
if (!session)
return;
m_allocator->Deallocate(session, sizeof(AdaptiveCompressionSession));
}
Status Context::MakeDecompressionComputePass(MakeDecompressionComputePassParameters const& params, ComputePassDesc* pOutComputePass) const
{
if (!pOutComputePass)
{
SetErrorMessage("pOutComputePass is NULL");
return Status::InvalidArgument;
}
if (!m_graphicsResources)
{
SetErrorMessage("The context was initialized with graphicsApi == None");
return Status::InvalidArgument;
}
if (!params.pOutputTextures && params.numOutputTextures != 0)
{
SetErrorMessage("pOutputTextures is NULL while numOutputTextures (%d) is nonzero", params.numOutputTextures);
return Status::InvalidArgument;
}
if (params.numOutputTextures > DECOMPRESS_CS_MAX_OUTPUTS)
{
SetErrorMessage("numOutputTextures (%d) is too large, must be %d or less", params.numOutputTextures, DECOMPRESS_CS_MAX_OUTPUTS);
return Status::InvalidArgument;
}
// Validate the output textures
for (int textureIndex = 0; textureIndex < params.numOutputTextures; ++textureIndex)
{
OutputTextureDesc const& desc = params.pOutputTextures[textureIndex];
if (desc.firstChannel < 0 || desc.numChannels <= 0 || desc.numChannels > 4 ||
desc.firstChannel + desc.numChannels >= NTC_MLP_OUTPUT_CHANNELS)
{
SetErrorMessage("pOutputTextures[%d] has invalid channel configuration: firstChannel = %d, numChannels = %d",
textureIndex, desc.firstChannel, desc.numChannels);
return Status::InvalidArgument;
}
if (desc.descriptorIndex < 0)
{
SetErrorMessage("pOutputTextures[%d] has invalid descriptorOffset (%d)",
textureIndex, desc.descriptorIndex);
return Status::InvalidArgument;
}
}
TextureSetMetadata* textureSetMetadata = dynamic_cast<TextureSetMetadata*>(params.textureSetMetadata);
if (!textureSetMetadata)
{
SetErrorMessage("textureSetMetadata is NULL or points at a wrong object type");
return Status::InvalidArgument;
}
TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
LatentShape const& latentShape = textureSetMetadata->GetLatentShape();
MlpDesc const* mlpDesc = textureSetMetadata->GetMlpDesc();
if (!mlpDesc)
{
SetErrorMessage("The texture set metadata doesn't have MLP information.");
return Status::InvalidArgument;
}
if (params.mipLevel < 0 || params.mipLevel >= textureSetDesc.mips)
{
SetErrorMessage("mipLevel (%d) must be between 0 and %d.", params.mipLevel, textureSetDesc.mips - 1);
return Status::OutOfRange;
}
// Pre-compute some parameters needed to pick the right shader
int const mipWidth = std::max(textureSetDesc.width >> params.mipLevel, 1);
int const mipHeight = std::max(textureSetDesc.height >> params.mipLevel, 1);
int const neuralLod = textureSetMetadata->ColorMipToNeuralLod(params.mipLevel);
LatentImageDesc const* latentImage = textureSetMetadata->GetLatentImageDesc(neuralLod);
if (!latentImage)
{
// This shouldn't happen with all the validation above, but let's be sure
SetErrorMessage("latentImage is NULL");
return Status::InternalError;
}
// The preload code only works when the resolution of high-res latents is <= the resolution of color pixels,
// otherwise there's not enough shared memory allocated to store all the latents.
bool const preloadLatents = latentImage->highResWidth <= mipWidth && latentImage->highResHeight <= mipHeight;
// Use the weight vectors from the texture set as support flags - if coopvec int8 or fp8 is not supported
// or disabled, the vector is empty. If there are no fp8 weights provided for example, the vector is also empty.
bool const legacyInt8 = !textureSetMetadata->GetInferenceWeightVector(InferenceWeightType::GenericInt8)->empty();
bool const coopVecInt8 = !textureSetMetadata->GetInferenceWeightVector(InferenceWeightType::CoopVecInt8)->empty();
bool const coopVecFP8 = params.enableFP8 && !textureSetMetadata->GetInferenceWeightVector(InferenceWeightType::CoopVecFP8)->empty();
bool const useCoopVec = coopVecInt8 || coopVecFP8;
// Select the shader version based on which math modes are supported and enabled.
InferenceMath mathVersion;
InferenceWeightType weightType;
if (coopVecFP8)
{
mathVersion = InferenceMath::CoopVecFP8;
weightType = InferenceWeightType::CoopVecFP8;
}
else if (coopVecInt8)
{
mathVersion = InferenceMath::CoopVecInt8;
weightType = InferenceWeightType::CoopVecInt8;
}
else if (legacyInt8)
{
if (m_graphicsResources->IsDP4aSupported() && m_graphicsResources->IsFloat16Supported())
mathVersion = InferenceMath::DP4aWithFloat16;
else if (m_graphicsResources->IsDP4aSupported())
mathVersion = InferenceMath::DP4aNoFloat16;
else
mathVersion = InferenceMath::Legacy;
weightType = InferenceWeightType::GenericInt8;
}
else
{
SetErrorMessage("No weights for the supported inference modes found in the texture set");
return Status::Unsupported;
}
pOutComputePass->computeShader = nullptr;
pOutComputePass->computeShaderSize = 0;
#if NTC_WITH_PREBUILT_SHADERS
switch (m_graphicsResources->GetGraphicsApi())
{
case GraphicsAPI::D3D12:
#if NTC_WITH_DX12
GetDecompressDxilShaderBytecode(mlpDesc, mathVersion, preloadLatents,
&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
case GraphicsAPI::Vulkan:
#if NTC_WITH_VULKAN
GetDecompressSpirvShaderBytecode(mlpDesc, mathVersion, preloadLatents,
&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
default:
// Shouldn't happen - None is handled above and invalid values are handled at context initialization
return Status::InvalidArgument;
}
#endif
Rect srcRect { 0, 0, mipWidth, mipHeight };
if (params.pSrcRect)
{
int const left = params.pSrcRect->left;
int const top = params.pSrcRect->top;
int const width = params.pSrcRect->width;
int const height = params.pSrcRect->height;
int const right = left + width;
int const bottom = top + height;
if (left < 0 || top < 0 || width <= 0 || height <= 0 || right > mipWidth || bottom > mipHeight)
{
SetErrorMessage("Invalid rectangle specified. For mip %d, left (%d) and top (%d) must be >= 0; "
"width (%d) and height (%d) must be > 0; (left + width) (%d) must be <= %d; "
"(top + height) must be <= %d.",
params.mipLevel, left, top, width, height, right, bottom, mipHeight);
return Status::OutOfRange;
}
srcRect = *params.pSrcRect;
}
Point dstOffset { srcRect.left, srcRect.top };
if (params.pDstOffset)
{
dstOffset = *params.pDstOffset;
}
// Get the stream range for this mip level
StreamRange requiredRange;
Status status = textureSetMetadata->GetStreamRangeForLatents(params.mipLevel, 1, requiredRange);
if (status != Status::Ok)
return status;
StreamRange latentStreamRange = params.latentStreamRange;
// Convert the "entire stream" range into the actual stream size
if (latentStreamRange.size + 1 == 0)
{
latentStreamRange.size = std::max(textureSetMetadata->GetSourceStreamSize(), latentStreamRange.offset)
- latentStreamRange.offset;
}
// Validate that the provided stream range contains the required range
if (requiredRange.offset < latentStreamRange.offset ||
requiredRange.offset + requiredRange.size > latentStreamRange.offset + latentStreamRange.size)
{
SetErrorMessage("Decompression of mip level %d requires input stream range %" PRId64 "-%" PRId64", "
"which is not contained in the provided range %" PRId64 "-%" PRId64 ".",
params.mipLevel,
requiredRange.offset, requiredRange.offset + requiredRange.size,
latentStreamRange.offset, latentStreamRange.offset + latentStreamRange.size);
return Status::OutOfRange;
}
NtcDecompressConstants& constants = reinterpret_cast<NtcDecompressConstants&>(pOutComputePass->constantBufferData);
static_assert(sizeof(NtcDecompressConstants) <= sizeof(ComputePassDesc::constantBufferData),
"NtcDecompressConstants don't fit into constantBufferData. Increase MaxComputePassConstantSize.");
pOutComputePass->constantBufferSize = sizeof(NtcDecompressConstants);
// Fill the constant buffer using that latent buffer offset
textureSetMetadata->FillDecompressionConstants(constants, weightType, params.mipLevel, srcRect, dstOffset,
params.pOutputTextures, params.numOutputTextures, params.firstOutputDescriptorIndex, latentStreamRange.offset);
int const gridWidth = constants.srcRight - constants.gridLeft;
int const gridHeight = constants.srcBottom - constants.gridTop;
pOutComputePass->weightBufferData = textureSetMetadata->GetInferenceWeightVector(weightType)->data();
pOutComputePass->weightBufferSize = textureSetMetadata->GetInferenceWeightVector(weightType)->size();
pOutComputePass->dispatchWidth = (gridWidth + DECOMPRESS_CS_BLOCK_WIDTH - 1) / DECOMPRESS_CS_BLOCK_WIDTH;
pOutComputePass->dispatchHeight = (gridHeight + DECOMPRESS_CS_BLOCK_HEIGHT - 1) / DECOMPRESS_CS_BLOCK_HEIGHT;
if (!pOutComputePass->computeShader)
{
SetErrorMessage("The requested shader binary is unavailable.");
return Status::ShaderUnavailable;
}
return Status::Ok;
}
Status Context::MakeBlockCompressionComputePass(MakeBlockCompressionComputePassParameters const& params,
ComputePassDesc* pOutComputePass) const
{
if (!pOutComputePass)
{
SetErrorMessage("pOutComputePass is NULL");
return Status::InvalidArgument;
}
if (!m_graphicsResources)
{
SetErrorMessage("The context was initialized with graphicsApi == None");
return Status::InvalidArgument;
}
if (params.srcRect.left < 0 || params.srcRect.top < 0 || params.srcRect.width <= 0 || params.srcRect.height <= 0)
{
SetErrorMessage("srcRect.left (%d) and srcRect.top (%d) must be >= 0; srcRect.width (%d) and "
"srcRect.height (%d) must be > 0",
params.srcRect.left, params.srcRect.top, params.srcRect.width, params.srcRect.height);
return Status::OutOfRange;
}
if (params.dstOffsetInBlocks.x < 0 || params.dstOffsetInBlocks.y < 0)
{
SetErrorMessage("dstOffsetInBlocks.x (%d) and dstOffsetInBlocks.y (%d) must be >= 0",
params.dstOffsetInBlocks.x, params.dstOffsetInBlocks.y);
return Status::OutOfRange;
}
if (params.dstFormat < BlockCompressedFormat::BC1 || params.dstFormat > BlockCompressedFormat::BC7)
{
SetErrorMessage("dstFormat (%s) has invalid value", BlockCompressedFormatToString(params.dstFormat));
return Status::OutOfRange;
}
pOutComputePass->computeShader = nullptr;
pOutComputePass->computeShaderSize = 0;
#if NTC_WITH_PREBUILT_SHADERS
switch (m_graphicsResources->GetGraphicsApi())
{
case GraphicsAPI::D3D12:
#if NTC_WITH_DX12
GetBlockCompressDxilShaderBytecode(params.dstFormat, params.writeAccelerationData,
&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
case GraphicsAPI::Vulkan:
#if NTC_WITH_VULKAN
GetBlockCompressSpirvShaderBytecode(params.dstFormat, params.writeAccelerationData,
&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
default:
// Shouldn't happen - None is handled above and invalid values are handled at context initialization
return Status::InvalidArgument;
}
#endif
NtcBlockCompressConstants& constants = reinterpret_cast<NtcBlockCompressConstants&>(pOutComputePass->constantBufferData);
static_assert(sizeof(NtcBlockCompressConstants) <= sizeof(ComputePassDesc::constantBufferData),
"NtcBlockCompressConstants don't fit into constantBufferData. Increase MaxComputePassConstantSize.");
pOutComputePass->constantBufferSize = sizeof(NtcBlockCompressConstants);
constants.srcLeft = params.srcRect.left;
constants.srcTop = params.srcRect.top;
constants.dstOffsetX = params.dstOffsetInBlocks.x;
constants.dstOffsetY = params.dstOffsetInBlocks.y;
constants.widthInBlocks = (params.srcRect.width + 3) / 4;
constants.heightInBlocks = (params.srcRect.height + 3) / 4;
constants.alphaThreshold = params.alphaThreshold;
memset(constants.allowedModes, 0xff, sizeof(constants.allowedModes));
if (params.texture && params.dstFormat == BlockCompressedFormat::BC7 && !params.writeAccelerationData)
{
static_cast<TextureMetadata const*>(params.texture)->GetAllowedBCModes(constants.allowedModes,
sizeof(constants.allowedModes), params.quality);
}
pOutComputePass->dispatchWidth = (constants.widthInBlocks + BLOCK_COMPRESS_CS_ST_GROUP_WIDTH - 1)
/ BLOCK_COMPRESS_CS_ST_GROUP_WIDTH;
pOutComputePass->dispatchHeight = (constants.heightInBlocks + BLOCK_COMPRESS_CS_ST_GROUP_HEIGHT - 1)
/ BLOCK_COMPRESS_CS_ST_GROUP_HEIGHT;
if (!pOutComputePass->computeShader)
{
SetErrorMessage("The requested shader binary is unavailable.");
return Status::ShaderUnavailable;
}
return Status::Ok;
}
Status Context::MakeImageDifferenceComputePass(MakeImageDifferenceComputePassParameters const& params,
ComputePassDesc* pOutComputePass) const
{
if (!pOutComputePass)
{
SetErrorMessage("pOutComputePass is NULL");
return Status::InvalidArgument;
}
if (!m_graphicsResources)
{
SetErrorMessage("The context was initialized with graphicsApi == None");
return Status::InvalidArgument;
}
if (params.extent.left < 0 || params.extent.top < 0)
{
SetErrorMessage("Left (%d) and top (%d) must be non-negative", params.extent.left, params.extent.top);
return Status::OutOfRange;
}
if (params.extent.width <= 0 || params.extent.height <= 0)
{
SetErrorMessage("Width (%d) and height (%d) must be positive", params.extent.width, params.extent.height);
return Status::OutOfRange;
}
if ((params.outputOffset & 3) != 0)
{
SetErrorMessage("outputOffset (%d) must be aligned to 4 bytes", params.outputOffset);
return Status::OutOfRange;
}
pOutComputePass->computeShader = nullptr;
pOutComputePass->computeShaderSize = 0;
#if NTC_WITH_PREBUILT_SHADERS
switch (m_graphicsResources->GetGraphicsApi())
{
case GraphicsAPI::D3D12:
#if NTC_WITH_DX12
GetImageDifferenceDxilShaderBytecode(&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
case GraphicsAPI::Vulkan:
#if NTC_WITH_VULKAN
GetImageDifferenceSpirvShaderBytecode(&pOutComputePass->computeShader, &pOutComputePass->computeShaderSize);
#endif
break;
default:
// Shouldn't happen - None is handled above and invalid values are handled at context initialization
return Status::InvalidArgument;
}
#endif
NtcImageDifferenceConstants& constants = reinterpret_cast<NtcImageDifferenceConstants&>(pOutComputePass->constantBufferData);
static_assert(sizeof(NtcImageDifferenceConstants) <= sizeof(ComputePassDesc::constantBufferData),
"NtcImageDifferenceConstants don't fit into constantBufferData. Increase MaxComputePassConstantSize.");
pOutComputePass->constantBufferSize = sizeof(NtcImageDifferenceConstants);
constants.left = params.extent.left;
constants.top = params.extent.top;
constants.width = params.extent.width;
constants.height = params.extent.height;
constants.alphaThreshold = params.alphaThreshold;
constants.useAlphaThreshold = params.useAlphaThreshold ? 1 : 0;
constants.useMSLE = params.useMSLE ? 1 : 0;
constants.outputOffset = params.outputOffset;
pOutComputePass->dispatchWidth = (params.extent.width + IMAGE_DIFFERENCE_CS_PIXELS_PER_BLOCK_X - 1)
/ IMAGE_DIFFERENCE_CS_PIXELS_PER_BLOCK_X;
pOutComputePass->dispatchHeight = (params.extent.height + IMAGE_DIFFERENCE_CS_PIXELS_PER_BLOCK_Y - 1)
/ IMAGE_DIFFERENCE_CS_PIXELS_PER_BLOCK_Y;
if (!pOutComputePass->computeShader)
{
SetErrorMessage("The requested shader binary is unavailable.");
return Status::ShaderUnavailable;
}
return Status::Ok;
}
Status Context::MakeInferenceData(ITextureSetMetadata* _textureSetMetadata, StreamRange latentStreamRange,
InferenceWeightType weightType, InferenceData* pOutInferenceData) const
{
if (!pOutInferenceData)
{
SetErrorMessage("pOutInferenceData is NULL");
return Status::InvalidArgument;
}
TextureSetMetadata* textureSetMetadata = dynamic_cast<TextureSetMetadata*>(_textureSetMetadata);
if (!textureSetMetadata)
{
SetErrorMessage("textureSetMetadata is NULL or points at a wrong object type");
return Status::InvalidArgument;
}
switch(weightType)
{
case InferenceWeightType::GenericInt8:
case InferenceWeightType::CoopVecInt8:
case InferenceWeightType::GenericFP8:
case InferenceWeightType::CoopVecFP8:
break;
default:
SetErrorMessage("Unsupported weightType (%s)", InferenceWeightTypeToString(weightType));
}
if (!textureSetMetadata->IsInferenceWeightTypeSupported(weightType))
{
SetErrorMessage("The texture set does not provide %s weights", InferenceWeightTypeToString(weightType));
return Status::Unsupported;
}
memset(pOutInferenceData, 0, sizeof(InferenceData));
TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
LatentShape const& latentShape = textureSetMetadata->GetLatentShape();
TextureSetMetadata::FillLatentEncodingConstants(pOutInferenceData->constants.highResEncoding,
latentShape.highResFeatures, latentShape.highResQuantBits, weightType);
TextureSetMetadata::FillLatentEncodingConstants(pOutInferenceData->constants.lowResEncoding,
latentShape.lowResFeatures, latentShape.lowResQuantBits, weightType);
for (int neuralLod = 0; neuralLod < textureSetMetadata->GetNumLatentImages(); ++neuralLod)
{
assert(neuralLod < NTC_MAX_NEURAL_MIPS);
textureSetMetadata->FillNeuralMipConstants(
pOutInferenceData->constants.highResNeuralMips[neuralLod],
pOutInferenceData->constants.lowResNeuralMips[neuralLod],
neuralLod, latentStreamRange.offset);
}
for (int mipLevel = 0; mipLevel < textureSetDesc.mips; ++mipLevel)
{
assert(mipLevel < NTC_MAX_MIPS);
textureSetMetadata->FillColorMipConstants(pOutInferenceData->constants.colorMips[mipLevel], mipLevel);
}
pOutInferenceData->constants.imageWidth = textureSetDesc.width;
pOutInferenceData->constants.imageHeight = textureSetDesc.height;
pOutInferenceData->constants.imageMips = textureSetDesc.mips;
textureSetMetadata->GetWeightOffsets(weightType, pOutInferenceData->constants.networkWeightOffsets,
pOutInferenceData->constants.networkScaleBiasOffset);
pOutInferenceData->constants.validChannelMask = textureSetMetadata->GetValidChannelMask();
pOutInferenceData->constants.channelColorSpaces = textureSetMetadata->GetPackedColorSpaces();
return Status::Ok;
}
Status Context::MakePartialInferenceData(ITextureSetMetadata* _textureSetMetadata, IStream* inputStream,
int firstMipLevel, int numMipLevels, Rect firstMipSlice, InferenceWeightType weightType,
InferenceData* pOutInferenceData, void* pOutLatentData, size_t* pInOutLatentSize) const
{
if (!pInOutLatentSize)
{
SetErrorMessage("pInOutLatentSize is NULL");
return Status::InvalidArgument;
}
if (!pOutInferenceData && pOutLatentData)
{
SetErrorMessage("pOutInferenceData is NULL");
return Status::InvalidArgument;
}
TextureSetMetadata* textureSetMetadata = dynamic_cast<TextureSetMetadata*>(_textureSetMetadata);
if (!textureSetMetadata)
{
SetErrorMessage("textureSetMetadata is NULL or points at a wrong object type");
return Status::InvalidArgument;
}
switch(weightType)
{
case InferenceWeightType::GenericInt8:
case InferenceWeightType::CoopVecInt8:
case InferenceWeightType::GenericFP8:
case InferenceWeightType::CoopVecFP8:
break;
default:
SetErrorMessage("Unsupported weightType (%s)", InferenceWeightTypeToString(weightType));
return Status::InvalidArgument;
}
if (!textureSetMetadata->IsInferenceWeightTypeSupported(weightType))
{
SetErrorMessage("The texture set does not provide %s weights", InferenceWeightTypeToString(weightType));
return Status::Unsupported;
}
TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
LatentShape const& latentShape = textureSetMetadata->GetLatentShape();
if (firstMipLevel < 0 || numMipLevels <= 0 || firstMipLevel + numMipLevels > textureSetDesc.mips)
{
SetErrorMessage("firstMipLevel (%d) and numMipLevels (%d) must describe a valid range within 0-%d",
firstMipLevel, numMipLevels, textureSetDesc.mips - 1);
return Status::OutOfRange;
}
int colorMipWidth = std::max(textureSetDesc.width >> firstMipLevel, 1);
int colorMipHeight = std::max(textureSetDesc.height >> firstMipLevel, 1);
if (firstMipSlice.left < 0 || firstMipSlice.top < 0 || firstMipSlice.width <= 0 || firstMipSlice.height <= 0 ||
firstMipSlice.left + firstMipSlice.width > colorMipWidth ||
firstMipSlice.top + firstMipSlice.height > colorMipWidth)
{
SetErrorMessage("firstMipSlice (%dx%d starting at %d, %d) must be within the bounds of MIP %d (%dx%d)",
firstMipSlice.left + firstMipSlice.width, firstMipSlice.top + firstMipSlice.height,
firstMipSlice.left, firstMipSlice.top,
firstMipLevel, colorMipWidth, colorMipHeight);
return Status::OutOfRange;
}
int const highResBitsPerLatentPixel = latentShape.highResFeatures * latentShape.highResQuantBits;
int const lowResBitsPerLatentPixel = latentShape.lowResFeatures * latentShape.lowResQuantBits;
// Validate that the latent pixels occupy a multiple of 4 bits. That should always be true because we enforce
// that the number of latents is a multiple of 4 (see TextureSetMetadata::ValidateLatentShape)
assert((highResBitsPerLatentPixel & 3) == 0);
assert((lowResBitsPerLatentPixel & 3) == 0);
size_t const latentBufferSize = pOutLatentData ? *pInOutLatentSize : 0;
size_t totalLatentSize = 0;
NtcTextureSetConstants* constants = pOutInferenceData ? &pOutInferenceData->constants : nullptr;
if (constants)
{
memset(constants, 0, sizeof(NtcTextureSetConstants));
TextureSetMetadata::FillLatentEncodingConstants(constants->highResEncoding,
latentShape.highResFeatures, latentShape.highResQuantBits, weightType);
TextureSetMetadata::FillLatentEncodingConstants(constants->lowResEncoding,
latentShape.lowResFeatures, latentShape.lowResQuantBits, weightType);
textureSetMetadata->GetWeightOffsets(weightType, constants->networkWeightOffsets,
constants->networkScaleBiasOffset);
constants->imageWidth = textureSetDesc.width;
constants->imageHeight = textureSetDesc.height;