| 166 | } |
| 167 | |
| 168 | bool test_gpu_float16(nvrhi::IDevice* device) |
| 169 | { |
| 170 | nvrhi::CommandListHandle commandList = device->createCommandList(); |
| 171 | |
| 172 | constexpr size_t count = 65536; |
| 173 | std::vector<float> f32(count); |
| 174 | std::vector<float16_t> f16(count); |
| 175 | |
| 176 | std::mt19937 rng(1); |
| 177 | std::uniform_real_distribution dist(-26.0, 18.0); // These are base-2 logarithms for the input numbers |
| 178 | std::uniform_int_distribution signDist(0, 1); |
| 179 | for (size_t i = 0; i < count; ++i) |
| 180 | { |
| 181 | double rnd = dist(rng); |
| 182 | int signRnd = signDist(rng); |
| 183 | double value = pow(2.0, rnd) * (signRnd ? -1.0 : 1.0); |
| 184 | f32[i] = float(value); |
| 185 | f16[i] = Float32ToFloat16(f32[i]); |
| 186 | } |
| 187 | |
| 188 | auto bufferDesc = nvrhi::BufferDesc() |
| 189 | .setByteSize(count * sizeof(float)) |
| 190 | .setDebugName("Input Buffer") |
| 191 | .setCanHaveRawViews(true) |
| 192 | .enableAutomaticStateTracking(nvrhi::ResourceStates::CopyDest); |
| 193 | nvrhi::BufferHandle f32buf = device->createBuffer(bufferDesc); |
| 194 | |
| 195 | bufferDesc |
| 196 | .setByteSize(count * sizeof(float16_t)) |
| 197 | .setDebugName("Output Buffer") |
| 198 | .setCanHaveUAVs(true); |
| 199 | nvrhi::BufferHandle f16buf = device->createBuffer(bufferDesc); |
| 200 | |
| 201 | bufferDesc |
| 202 | .setDebugName("Readback Buffer") |
| 203 | .setCanHaveUAVs(false) |
| 204 | .setCpuAccess(nvrhi::CpuAccessMode::Read); |
| 205 | nvrhi::BufferHandle readbackBuf = device->createBuffer(bufferDesc); |
| 206 | |
| 207 | commandList->open(); |
| 208 | commandList->writeBuffer(f32buf, f32.data(), count * sizeof(float)); |
| 209 | |
| 210 | nvrhi::coopvec::ConvertMatrixLayoutDesc convertDesc{}; |
| 211 | convertDesc.numRows = 1; |
| 212 | convertDesc.numColumns = count; |
| 213 | convertDesc.src.buffer = f32buf; |
| 214 | convertDesc.src.layout = nvrhi::coopvec::MatrixLayout::RowMajor; |
| 215 | convertDesc.src.stride = count * sizeof(float); |
| 216 | convertDesc.src.size = convertDesc.src.stride; |
| 217 | convertDesc.src.type = nvrhi::coopvec::DataType::Float32; |
| 218 | convertDesc.dst.buffer = f16buf; |
| 219 | convertDesc.dst.layout = nvrhi::coopvec::MatrixLayout::RowMajor; |
| 220 | convertDesc.dst.stride = count * sizeof(float16_t); |
| 221 | convertDesc.dst.size = convertDesc.dst.stride; |
| 222 | convertDesc.dst.type = nvrhi::coopvec::DataType::Float16; |
| 223 | commandList->convertCoopVecMatrices(&convertDesc, 1); |
| 224 | |
| 225 | commandList->copyBuffer(readbackBuf, 0, f16buf, 0, count * sizeof(float16_t)); |
no test coverage detected