\brief Runs inference for this sample \details This function is the main execution function of the sample. It runs inference for using a random image from the MNIST dataset as an input.
| 375 | //! It runs inference for using a random image from the MNIST dataset as an input. |
| 376 | //! |
| 377 | bool SampleDynamicReshape::infer() |
| 378 | { |
| 379 | // Load a random PGM file into a host buffer, then copy to device. |
| 380 | std::random_device rd{}; |
| 381 | std::default_random_engine generator{rd()}; |
| 382 | std::uniform_int_distribution<int> digitDistribution{0, 9}; |
| 383 | int digit = digitDistribution(generator); |
| 384 | |
| 385 | Dims inputDims = loadPGMFile(locateFile(std::to_string(digit) + ".pgm", mParams.dataDirs)); |
| 386 | mInput.deviceBuffer.resize(inputDims); |
| 387 | CHECK(cudaMemcpy( |
| 388 | mInput.deviceBuffer.data(), mInput.hostBuffer.data(), mInput.hostBuffer.nbBytes(), cudaMemcpyHostToDevice)); |
| 389 | |
| 390 | // Set the input size for the preprocessor |
| 391 | CHECK_RETURN_W_MSG(mPreprocessorContext->setBindingDimensions(0, inputDims), false, "Invalid binding dimensions."); |
| 392 | |
| 393 | // We can only run inference once all dynamic input shapes have been specified. |
| 394 | if (!mPreprocessorContext->allInputDimensionsSpecified()) |
| 395 | { |
| 396 | return false; |
| 397 | } |
| 398 | |
| 399 | // Run the preprocessor to resize the input to the correct shape |
| 400 | std::vector<void*> preprocessorBindings = {mInput.deviceBuffer.data(), mPredictionInput.data()}; |
| 401 | // For engines using full dims, we can use executeV2, which does not include a separate batch size parameter. |
| 402 | bool status = mPreprocessorContext->executeV2(preprocessorBindings.data()); |
| 403 | if (!status) |
| 404 | { |
| 405 | return false; |
| 406 | } |
| 407 | |
| 408 | // Next, run the model to generate a prediction. |
| 409 | std::vector<void*> predicitonBindings = {mPredictionInput.data(), mOutput.deviceBuffer.data()}; |
| 410 | status = mPredictionContext->executeV2(predicitonBindings.data()); |
| 411 | if (!status) |
| 412 | { |
| 413 | return false; |
| 414 | } |
| 415 | |
| 416 | // Copy the outputs back to the host and verify the output. |
| 417 | CHECK(cudaMemcpy(mOutput.hostBuffer.data(), mOutput.deviceBuffer.data(), mOutput.deviceBuffer.nbBytes(), |
| 418 | cudaMemcpyDeviceToHost)); |
| 419 | return validateOutput(digit); |
| 420 | } |
| 421 | |
| 422 | //! |
| 423 | //! \brief Loads a PGM file into mInput and returns the dimensions of the loaded image. |
no test coverage detected