File size: 14,478 Bytes
38fb1f6 | 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 | /*
* SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TRT_SAMPLE_DEVICE_H
#define TRT_SAMPLE_DEVICE_H
#include <cassert>
#include <cuda.h>
#include <cuda_runtime.h>
#include <iostream>
#include <thread>
#include "common.h"
#include "sampleUtils.h"
namespace sample
{
class TrtCudaEvent;
namespace
{
void cudaSleep(void* sleep)
{
std::this_thread::sleep_for(std::chrono::duration<float, std::milli>(*static_cast<float*>(sleep)));
}
} // namespace
//!
//! \class TrtCudaStream
//! \brief Managed CUDA stream
//!
class TrtCudaStream
{
public:
TrtCudaStream()
{
CHECK(cudaStreamCreate(&mStream));
}
TrtCudaStream(const TrtCudaStream&) = delete;
TrtCudaStream& operator=(const TrtCudaStream&) = delete;
TrtCudaStream(TrtCudaStream&&) = delete;
TrtCudaStream& operator=(TrtCudaStream&&) = delete;
~TrtCudaStream()
{
CHECK(cudaStreamDestroy(mStream));
}
cudaStream_t get() const
{
return mStream;
}
void synchronize()
{
CHECK(cudaStreamSynchronize(mStream));
}
void wait(TrtCudaEvent& event);
void sleep(float* ms)
{
CHECK(cudaLaunchHostFunc(mStream, cudaSleep, ms));
}
private:
cudaStream_t mStream{};
};
//!
//! \class TrtCudaEvent
//! \brief Managed CUDA event
//!
class TrtCudaEvent
{
public:
explicit TrtCudaEvent(bool blocking = true)
{
const uint32_t flags = blocking ? cudaEventBlockingSync : cudaEventDefault;
CHECK(cudaEventCreateWithFlags(&mEvent, flags));
}
TrtCudaEvent(const TrtCudaEvent&) = delete;
TrtCudaEvent& operator=(const TrtCudaEvent&) = delete;
TrtCudaEvent(TrtCudaEvent&&) = delete;
TrtCudaEvent& operator=(TrtCudaEvent&&) = delete;
~TrtCudaEvent()
{
CHECK(cudaEventDestroy(mEvent));
}
cudaEvent_t get() const
{
return mEvent;
}
void record(const TrtCudaStream& stream)
{
CHECK(cudaEventRecord(mEvent, stream.get()));
}
void synchronize()
{
CHECK(cudaEventSynchronize(mEvent));
}
// Returns time elapsed time in milliseconds
float operator-(const TrtCudaEvent& e) const
{
float time{0};
CHECK(cudaEventElapsedTime(&time, e.get(), get()));
return time;
}
private:
cudaEvent_t mEvent{};
};
inline void TrtCudaStream::wait(TrtCudaEvent& event)
{
CHECK(cudaStreamWaitEvent(mStream, event.get(), 0));
}
//!
//! \class TrtCudaGraph
//! \brief Managed CUDA graph
//!
class TrtCudaGraph
{
public:
explicit TrtCudaGraph() = default;
TrtCudaGraph(const TrtCudaGraph&) = delete;
TrtCudaGraph& operator=(const TrtCudaGraph&) = delete;
TrtCudaGraph(TrtCudaGraph&&) = delete;
TrtCudaGraph& operator=(TrtCudaGraph&&) = delete;
~TrtCudaGraph()
{
if (mGraphExec)
{
cudaGraphExecDestroy(mGraphExec);
}
}
void beginCapture(TrtCudaStream& stream)
{
CHECK(cudaStreamBeginCapture(stream.get(), cudaStreamCaptureModeThreadLocal));
}
bool launch(TrtCudaStream& stream)
{
return cudaGraphLaunch(mGraphExec, stream.get()) == cudaSuccess;
}
void endCapture(TrtCudaStream& stream)
{
CHECK(cudaStreamEndCapture(stream.get(), &mGraph));
CHECK(cudaGraphInstantiate(&mGraphExec, mGraph, nullptr, nullptr, 0));
CHECK(cudaGraphDestroy(mGraph));
}
void endCaptureOnError(TrtCudaStream& stream)
{
// There are two possibilities why stream capture would fail:
// (1) stream is in cudaErrorStreamCaptureInvalidated state.
// (2) TRT reports a failure.
// In case (1), the returning mGraph should be nullptr.
// In case (2), the returning mGraph is not nullptr, but it should not be used.
const auto ret = cudaStreamEndCapture(stream.get(), &mGraph);
if (ret == cudaErrorStreamCaptureInvalidated)
{
assert(mGraph == nullptr);
}
else
{
CHECK(ret);
assert(mGraph != nullptr);
CHECK(cudaGraphDestroy(mGraph));
mGraph = nullptr;
}
// Clean up any CUDA error.
cudaGetLastError();
sample::gLogWarning << "The CUDA graph capture on the stream has failed." << std::endl;
}
private:
cudaGraph_t mGraph{};
cudaGraphExec_t mGraphExec{};
};
//!
//! \class TrtCudaBuffer
//! \brief Managed buffer for host and device
//!
template <typename A, typename D>
class TrtCudaBuffer
{
public:
TrtCudaBuffer() = default;
TrtCudaBuffer(const TrtCudaBuffer&) = delete;
TrtCudaBuffer& operator=(const TrtCudaBuffer&) = delete;
TrtCudaBuffer(TrtCudaBuffer&& rhs)
{
reset(rhs.mPtr, rhs.mSize);
rhs.mPtr = nullptr;
rhs.mSize = 0;
}
TrtCudaBuffer& operator=(TrtCudaBuffer&& rhs)
{
if (this != &rhs)
{
reset(rhs.mPtr, rhs.mSize);
rhs.mPtr = nullptr;
rhs.mSize = 0;
}
return *this;
}
~TrtCudaBuffer()
{
reset();
}
TrtCudaBuffer(size_t size)
{
A()(&mPtr, size);
mSize = size;
}
void allocate(size_t size)
{
reset();
A()(&mPtr, size);
mSize = size;
}
void reset(void* ptr = nullptr, size_t size = 0)
{
if (mPtr)
{
D()(mPtr);
}
mPtr = ptr;
mSize = size;
}
void* get() const
{
return mPtr;
}
size_t getSize() const
{
return mSize;
}
private:
void* mPtr{nullptr};
size_t mSize{0};
};
struct DeviceAllocator
{
void operator()(void** ptr, size_t size)
{
CHECK(cudaMalloc(ptr, size));
}
};
struct DeviceDeallocator
{
void operator()(void* ptr)
{
CHECK(cudaFree(ptr));
}
};
struct ManagedAllocator
{
void operator()(void** ptr, size_t size)
{
CHECK(cudaMallocManaged(ptr, size));
}
};
struct HostAllocator
{
//! Attempts to allocate size bytes on host, pointing *ptr to the start.
//! First attempts to allocate pinned memory using cudaMallocHost(ptr, size), failing that, warns to gLogWarning and
//! falls back to ::operator new(size) to allocate pageable memory. If that still fails, an exception may be thrown.
void operator()(void** ptr, size_t size)
{
// Try allocating pinned host memory.
cudaError_t ret = cudaMallocHost(ptr, size);
// If we cannot allocate pinned host memory, allocate pageable host memory instead and print a warning.
if (ret != cudaSuccess)
{
// Clean up the last cuda error.
(void) cudaGetLastError();
sample::gLogWarning << "cudaMallocHost() call with ptr=" << ptr << " and size=" << size
<< " returns a cuda error: " << cudaGetErrorString(ret) << std::endl;
sample::gLogWarning << "Allocate pageable host memory instead of pinned host memory. H2D and D2H copy "
"latencies may become longer."
<< std::endl;
*ptr = ::operator new(size);
// Make sure there is no remaining cuda error at this point.
CHECK(cudaGetLastError());
}
}
};
struct HostDeallocator
{
//! Attempts to deallocate the host memory allocated by HostAllocator.
//! It first checks if ptr is a pinned or pageable host memory. If pinned, call cudaFreeHost() to free it. If
//! pageable, call ::operator delete() to free it. If ptr is neither of them, an error is printed and the program
//! exits.
void operator()(void* ptr)
{
// Check if the host memory pointer is pinned or pageable.
cudaPointerAttributes attrs;
CHECK(cudaPointerGetAttributes(&attrs, ptr));
// If pinned, call cudaFreeHost() to deallocate it.
if (attrs.type == cudaMemoryTypeHost)
{
CHECK(cudaFreeHost(ptr));
}
// If pageable, delete it directly.
else if (attrs.type == cudaMemoryTypeUnregistered)
{
::operator delete(ptr);
}
// The host memory pointer should not be of any other types.
else
{
sample::gLogError << "Unexpected cuda memory type:" << static_cast<int32_t>(attrs.type) << std::endl;
exit(EXIT_FAILURE);
}
}
};
using TrtDeviceBuffer = TrtCudaBuffer<DeviceAllocator, DeviceDeallocator>;
using TrtManagedBuffer = TrtCudaBuffer<ManagedAllocator, DeviceDeallocator>;
using TrtHostBuffer = TrtCudaBuffer<HostAllocator, HostDeallocator>;
//!
//! \class MirroredBuffer
//! \brief Coupled host and device buffers
//!
class IMirroredBuffer
{
public:
//!
//! Allocate memory for the mirrored buffer give the size
//! of the allocation.
//!
virtual void allocate(size_t size) = 0;
//!
//! Get the pointer to the device side buffer.
//!
//! \return pointer to device memory or nullptr if uninitialized.
//!
virtual void* getDeviceBuffer() const = 0;
//!
//! Get the pointer to the host side buffer.
//!
//! \return pointer to host memory or nullptr if uninitialized.
//!
virtual void* getHostBuffer() const = 0;
//!
//! Copy the memory from host to device.
//!
virtual void hostToDevice(TrtCudaStream& stream) = 0;
//!
//! Copy the memory from device to host.
//!
virtual void deviceToHost(TrtCudaStream& stream) = 0;
//!
//! Interface to get the size of the memory
//!
//! \return the size of memory allocated.
//!
virtual size_t getSize() const = 0;
//!
//! Virtual destructor declaraion
//!
virtual ~IMirroredBuffer() = default;
}; // class IMirroredBuffer
//!
//! Class to have a separate memory buffer for discrete device and host allocations.
//!
class DiscreteMirroredBuffer : public IMirroredBuffer
{
public:
void allocate(size_t size) override
{
mSize = size;
mHostBuffer.allocate(size);
mDeviceBuffer.allocate(size);
}
void* getDeviceBuffer() const override
{
return mDeviceBuffer.get();
}
void* getHostBuffer() const override
{
return mHostBuffer.get();
}
void hostToDevice(TrtCudaStream& stream) override
{
CHECK(cudaMemcpyAsync(mDeviceBuffer.get(), mHostBuffer.get(), mSize, cudaMemcpyHostToDevice, stream.get()));
}
void deviceToHost(TrtCudaStream& stream) override
{
CHECK(cudaMemcpyAsync(mHostBuffer.get(), mDeviceBuffer.get(), mSize, cudaMemcpyDeviceToHost, stream.get()));
}
size_t getSize() const override
{
return mSize;
}
private:
size_t mSize{0};
TrtHostBuffer mHostBuffer;
TrtDeviceBuffer mDeviceBuffer;
}; // class DiscreteMirroredBuffer
//!
//! Class to have a unified memory buffer for embedded devices.
//!
class UnifiedMirroredBuffer : public IMirroredBuffer
{
public:
void allocate(size_t size) override
{
mSize = size;
mBuffer.allocate(size);
}
void* getDeviceBuffer() const override
{
return mBuffer.get();
}
void* getHostBuffer() const override
{
return mBuffer.get();
}
void hostToDevice(TrtCudaStream& stream) override
{
// Does nothing since we are using unified memory.
}
void deviceToHost(TrtCudaStream& stream) override
{
// Does nothing since we are using unified memory.
}
size_t getSize() const override
{
return mSize;
}
private:
size_t mSize{0};
TrtManagedBuffer mBuffer;
}; // class UnifiedMirroredBuffer
//!
//! Class to allocate memory for outputs with data-dependent shapes. The sizes of those are unknown so pre-allocation is
//! not possible.
//!
class OutputAllocator : public nvinfer1::IOutputAllocator
{
public:
//! Construct, using buffer as the backing storage:
explicit OutputAllocator(std::unique_ptr<IMirroredBuffer> buffer)
: mBuffer{std::move(buffer)}
{
ASSERT(mBuffer);
}
~OutputAllocator() override = default;
void* reallocateOutput(
char const* tensorName, void* currentMemory, uint64_t size, uint64_t alignment) noexcept override
{
// Some memory allocators return nullptr when allocating zero bytes, but TensorRT requires a non-null ptr
// even for empty tensors, so allocate a dummy byte.
size = std::max(size, static_cast<uint64_t>(1));
if (size > mSize)
{
mBuffer->allocate(roundUp(size, alignment));
mSize = size;
}
return mBuffer->getDeviceBuffer();
}
//! IMirroredBuffer does not implement Async allocation, hence this is just a wrap around
void* reallocateOutputAsync(char const* tensorName, void* currentMemory, uint64_t size, uint64_t alignment,
cudaStream_t /*stream*/) noexcept override
{
return reallocateOutput(tensorName, currentMemory, size, alignment);
}
void notifyShape(char const* tensorName, nvinfer1::Dims const& dims) noexcept override
{
mFinalDims = dims;
}
IMirroredBuffer* getBuffer()
{
return mBuffer.get();
}
nvinfer1::Dims getFinalDims()
{
return mFinalDims;
}
private:
std::unique_ptr<IMirroredBuffer> mBuffer;
uint64_t mSize{};
nvinfer1::Dims mFinalDims;
};
//! Set the GPU to run the inference on.
void setCudaDevice(int32_t device, std::ostream& os);
//! Get the CUDA version of the current CUDA driver.
int32_t getCudaDriverVersion();
//! Get the CUDA version of the current CUDA runtime.
int32_t getCudaRuntimeVersion();
} // namespace sample
#endif // TRT_SAMPLE_DEVICE_H
|