Skip to content

Add support for GEMM e2e Test For CUDA backend on F16 input - #10842

Merged
manishucsd merged 5 commits into
iree-org:mainfrom
manishucsd:fp16_e2e_gemm_tests
Nov 9, 2022
Merged

manishucsd merged 5 commits into
iree-org:mainfrom
manishucsd:fp16_e2e_gemm_tests

Conversation

@manishucsd

@manishucsd manishucsd commented Oct 18, 2022 •

Copy link
Copy Markdown
Contributor

This pull request adds support for testing e2e GEMM on a CUDA backend for F16 input and F16 accumulation.

  • Functional testing of F16 GEMMs requires setting the right tolerance value to ensure correctness checks.
  • Tolerance-based testing is fragile and finding tolerances is hard.
  • Instead we fill the buffers as small integers centered at zero and test for equivalence.

This pull requests adds e2e_matmul_direct_f16_gpu_large_LLVMGPUMatmulTensorCore_cuda_cuda more e2e GEMM test to CUDA backend. We have not total 4 e2e GEMM tests on CUDA backend.

manigupta@manigupta-gpu-a100 ~/cpu_machine_workspace/repos/iree/iree_tree_1/iree-build-debug $ ctest -j96 -R e2e_matmul.*cuda

1/4 Test #41: iree/tests/e2e/matmul/e2e_matmul_direct_f32_gpu_large_LLVMGPUMatmulTensorCore_cuda_cuda ...   Passed    2.83 sec
2/4 Test #42: iree/tests/e2e/matmul/e2e_matmul_direct_f16_gpu_large_LLVMGPUMatmulTensorCore_cuda_cuda ...   Passed    3.09 sec
3/4 Test #40: iree/tests/e2e/matmul/e2e_matmul_direct_f32_gpu_large_LLVMGPUMatmulSimt_cuda_cuda .........   Passed    3.38 sec
4/4 Test #43: iree/tests/e2e/matmul/e2e_matmul_direct_f32_large_split_k_cuda_cuda .......................   Passed    4.43 sec

Comment thread tools/iree-e2e-matmul-test.c Outdated
for (iree_hal_dim_t k = 0; k < k_size; ++k) {
float lhs_value = iree_math_f16_to_f32(lhs_data[k + m * k_size]);
float rhs_value = iree_math_f16_to_f32(rhs_data[n + k * n_size]);
acc += lhs_value * rhs_value;

@bjacob bjacob Oct 19, 2022 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This reference matmul implementation is really a f32 += f16 * f16 matmul, not a f16 += f16 * f16, since acc has type float. I believe that in order to make it exactly f16 += f16 * f16, you would have to do something like this: first have a helper function to round a float to the nearest f16,

float round_to_nearest_f16_representable(float x) {
return iree_math_f16_to_f32(iree_math_f32_to_f16(x));
}

then insert that around both the multiplication and the addition in acc += lhs_value * rhs_value.... is that correct? (Or only after the addition if we want to implement a fused-mul-add reference impl here).

Side note: the reason why this isn't caught by the test despite the test requiring bit-for-bit exactness is that the test input values are special enough that all intermediate values here are exactly f16-representable anyway. I don't think this is sufficient reason to reconsider that, just worth noting.

Side side note: this is also the reason why we haven't needed to worry about whether the reference implementation is fused or unfused mul-add.

Or OK, we can plausibly argue here that we don't need to worry about any of this at all, because this reference implementation is meant to be used only in the context of such special test values, but then this deserves at least a comment.

Maybe the impact on test latency could be allowed to factor into the decision here.

@manishucsd manishucsd Oct 20, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bjacob , Thanks for the comment and catching this. Yes, you are right, this is accumulating in f32. For the case we are trying to verify, i.e. f16 += f16 * f16 we want the following:

acc = round_to_nearest_f16_representable (
                              round_to_nearest_f16_representable(
                                  (iree_math_f16_to_f32(lhs_data[k + m * k_size]) * 
                                   iree_math_f16_to_f32(rhs_data[n + k * n_size]))
                               ) // round multiply result to the nearest half
                           + acc
      ); // round add results to the nearest half

Consider there is a half_t datatype and conversion operators to half and to float. Then to do f16 multiply_add we will below expression:

Do we have similar implementations of half and bfloat16 types that we can use in iree?

It could help handle these concerns by overloading multiply and add operators for the respective data types. For example half_t operator*(half_t const& lhs, half_t const& rhs)

Side note: the reason why this isn't caught by the test despite the test requiring bit-for-bit exactness is that the test input values are special enough that all intermediate values here are exactly f16-representable anyway. I don't think this is sufficient reason to reconsider that, just worth noting.

Yes, I agree this worth noting and there are trade-offs of testing f16 arithmetic using tolerance on real inputs vs. bit-exactness on small integers.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have similar implementations of half and bfloat16 types that we can use in iree?

Good question, i don't know! @benvanik , @antiagainst might.

It could help handle these concerns by overloading multiply and add operators for the respective data types. For example half_t operator*(half_t const& lhs, half_t const& rhs)

Noooooooooooo :-D explicitness is good here. The overriding concern here is to keep this code easy to read in the sense of proving that it's correct, not just easy to glance over casually --- operator overloading would help the latter, not the former.

Yes, I agree this worth noting and there are trade-offs of testing f16 arithmetic using tolerance on real inputs vs. bit-exactness on small integers.

So I was serious in the last part of my comment above,

Or OK, we can plausibly argue here that we don't need to worry about any of this at all, because this reference implementation is meant to be used only in the context of such special test values, but then this deserves at least a comment.

That is, seriously, it's OK to explicitly make this reference matmul code specific to the special flavor of test values that we use here, and take advantage of that to not need f16 arithmetic at all in the reference code. I'm OK either way, up to you.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just had a conversation with @manishucsd . Here's the summary of the thinking we've arrived at.

We need to keep consistency between the test code, including its reference matmul implementation, and the test input values.

Choose one route between A and B:

A. If we have integral test input values allowing us to require bit-exactness, then it makes sense to have only one reference matmul implementation, multiplying integer matrices. We still nead to load matrix data from the test matrices in various element types, but we can cast that to int and feed that to a single shared reference matmul.

B. If we have more general test input values causing floating-point rounding to occur, then more factors come into the picture. We were so far papering over them by using a fuzzy comparison, but this PR switches (at least for f16, but I do believe this is a good change to make for all types) to exact comparisons, so we are not papering over anything anymore and we need reference code to be bit-exact with the actual device code. Now, besides the data type (f16 vs f32) device code will also differ in at least fused-vs-unfused multiply-add, so we would need at least 2x more reference code paths for that. And that's not even starting to look into details of device-specific rounding modes!

The point is that if we keep separate reference code paths as in B. then we need test coverage ensuring that the distinctions justifying these separate code paths, are actually correctly handled, in particular we need more than integral test values. This circles back to the specific issue noted at the start of this thread, the f16 reference code was actually accumulating in f32 and the test didn't notice due to the integral test values.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @bjacob for summarizing this. I have made the change to fill the buffers for floating point inputs with small integers, create a reference matmul which takes buffers as void*, and casts the values to int32_t. There are various cast on reads.

@manishucsd manishucsd Oct 22, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On C++ struct for half_t datatype and explicitness of conversion. Please review the pseudo code below:

Given a half_t implementation with conversions from F32->F16 and F16->F32. Also operator for matrix-multiply as below:

/// half.h
struct half_t {
/// half_t bits stored in 16-bit uint16_t
uint16_t storage;

/// Explicit conversion ctor
explicit half_t(float x);

/// F32->F16 conversion
operator float() const;
};

/// Multiplication on half_f numbers.
half_t operator*(half_t const& lhs, half_t const& rhs) {
#if HW_FP16_MUL_SUPPORTED
  // hardware support intrinsic call here
#else
  return half_t(float(lhs) * float(rhs));
#endif
}

/// Output stream operator 
inline
std::ostream & operator<<(std::ostream &out, half_t const &x) {
  return out << float(x);
}

The application/user code using the above half_t type:

#include <half_h>
...
half_t opA(1.0f);
half_t opB(2.0f);
half_t opC;

// Multiplication on half_t datatypes
opC = opA * opB;

// Print half results
std::cout << opC

I think using structured half_t type will make handling F16 datatype in the application more graceful and the operations on a typed c++ langugage will make sure the programmer know that multiply is happening on half_t types.

Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
Comment thread runtime/src/iree/tooling/trace_replay.c Outdated
for (uint8_t* data = span.data; data < data_end; data += element_byte_count) {
int value_in_uint8_range = iree_trace_replay_pseudorandom_uint8(&state);
int value = value_in_uint8_range + (is_unsigned ? 0 : -128);
double value = iree_trace_replay_pseudorandom_double(&state);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't feel entirely good about routing all element types through double. I feel that it would be nice to only use floating point at all (resp. double) when element_type is a floating-point type (resp. is double). Reasons:

  • Floating point will always be potentially weird, in terms of potentially having unexpected hardware floating-point environment/state interfere with results. When element_type is integral, such weirdness would be particularly unexpected.
  • On some targets, floating-point is very slow (e.g. when it's emulated in software). We care about e2e tests running not much slower than necessary there.
  • Even on targets that have fast float, double may still be slow.

Comment thread runtime/src/iree/vm/value.h Outdated
IREE_VM_VALUE_TYPE_F32 = 6,
// double.
IREE_VM_VALUE_TYPE_F64 = 6,
IREE_VM_VALUE_TYPE_F64 = 7,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check with @benvanik if it's OK to shift existing enum values --- these are never serialized, right?

Comment thread runtime/src/iree/vm/value.h Resolved
Comment thread tools/iree-e2e-matmul-test.c Resolved

// Rounds of 32-bit C `float` value to nearest 16-bit value and returns
// 32-bit `float`
static inline float iree_math_round_to_nearest_f16(const float f32_value) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a TODO about the possibility of someday writing a faster impl of this function (it's called literally as many times as there are scalar (add or mul) ops in the reference matmuls, so it'll likely be quite significant on profiles, and e2e matmul tests latency are never far below the threshold where we feel compelled to do something about them, in fact we have repeatedly trimmed them in the past to keep their latency in check).

@manishucsd manishucsd Oct 21, 2022 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I didn't feel good writing the above function and calling the conversions. half_t data type implementation in c++ with well defined conversion operator() could handle this graceful on a CPU and also GPU.

There is a fast implementation of half_t data type which uses fast conversion (F32->F16) implementation supported for:

I champion using this implementation of half data type until it becomes available in c++ standard.

@manishucsd
manishucsd force-pushed the fp16_e2e_gemm_tests branch 7 times, most recently from 53d20e4 to 4017042 Compare October 22, 2022 06:18
@manishucsd
manishucsd force-pushed the fp16_e2e_gemm_tests branch 5 times, most recently from 4046911 to 924b4e5 Compare November 2, 2022 14:56
Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
Comment thread runtime/src/iree/vm/value.h Resolved
Comment thread tools/iree-e2e-matmul-test.c Resolved
Comment thread tools/iree-e2e-matmul-test.c Resolved
Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
@manishucsd
manishucsd force-pushed the fp16_e2e_gemm_tests branch 2 times, most recently from 7241a39 to dbd1d4c Compare November 2, 2022 17:27

@benvanik benvanik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes to the e2e matmul test don't look correct - it seems to always be doing i32*i32 matmuls, converting float<->int with default C rounding, etc. I think there may have been too much of an effort to generalize the code at a bit too high of a cost. I think you will need to use macros-as-templates for the generic implementation that templated on types to ensure that the types don't get messed up/performance remains reasonable. KISS - reference code and tests are intended to be easy to diagnose/debug/modify and deeply polymorphic code is usually the opposite (though still sometimes useful).

Comment thread tools/iree-e2e-matmul-test.c Resolved
((int32_t*)data)[index] = value;
return;
} else if (result_type == IREE_HAL_ELEMENT_TYPE_FLOAT_16) {
((uint16_t*)data)[index] = iree_math_f32_to_f16((float)value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this correct? it's doing a float<-> int conversion, so it'll only be able to represent ints

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks correct to me: uint16_t is the (preexisting) storage type of our dummy f16's. See the return type of iree_math_f32_to_f16.

Comment thread tools/iree-e2e-matmul-test.c Resolved
@benvanik

benvanik commented Nov 2, 2022

Copy link
Copy Markdown
Collaborator

(sorry if some of these things have been discussed in prior comments - I hadn't been following this PR and am just looking at what the latest commits show - but the vm value changes will have to be dropped and the e2e matmul test will need its own copy of those types if you go the generic route - but I strongly suggest reworking that to something simpler)

Comment thread runtime/src/iree/tooling/trace_replay.c Resolved
((int32_t*)data)[index] = value;
return;
} else if (result_type == IREE_HAL_ELEMENT_TYPE_FLOAT_16) {
((uint16_t*)data)[index] = iree_math_f32_to_f16((float)value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks correct to me: uint16_t is the (preexisting) storage type of our dummy f16's. See the return type of iree_math_f32_to_f16.

Comment thread tools/iree-e2e-matmul-test.c Resolved
Comment thread tools/iree-e2e-matmul-test.c Resolved
@manishucsd
manishucsd merged commit 0a6cdf0 into iree-org:main Nov 9, 2022
manishucsd pushed a commit that referenced this pull request Jan 23, 2023
…atrix] (#11817)

Adds native Tensor Core (F16) support for NVIDIA GPUs. Specifically,
adds support to target
`mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16` and `ldmatrix`
instructions on NVIDIA A100 GPUs. For now, these instructions are not
enabled by default and requires using
(`--iree-codegen-llvmgpu-use-mma-sync=true`).

IREE runs row-row matmul and the native Tensor Core support requires
`ldmatrix` for operandA and `ldmatrix.trans` for operandB.
`ldmatrix.trans` transposes the data while loading to use Tensor Core
`mma*row.col*` instruction.

There are LLVM/MLIR upstream pathes and previous IREE PRs that enable
targeting native Tensor Core F16 support.

A few LLVM/MLIR upstream patches:
- [[mlir][NVGPU] Adding Support for cp_async_zfill via Inline
Asm](https://reviews.llvm.org/D132269)
- [[mlir][NVGPU] Handle Native mma.sync sizes and ldmatrix(x4) for
matrixB](https://reviews.llvm.org/D135749)
- [[mlir][NVGPU] Fix affine maps computing indices for LdMatrixOp
srcMemref](https://reviews.llvm.org/D138978)
- [[mlir][NVGPU] Fix NVGPU Bazel
Layering](https://reviews.llvm.org/D141982)


Previous IREE PRs:
- [Support GEMM Pipelining *without* Epilogue
Peeling](#10388)
- [Add support for GEMM e2e Test For CUDA backend on F16
input](#10842)
qedawkins pushed a commit to qedawkins/iree that referenced this pull request Apr 2, 2023
…atrix] (iree-org#11817)

Adds native Tensor Core (F16) support for NVIDIA GPUs. Specifically,
adds support to target
`mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16` and `ldmatrix`
instructions on NVIDIA A100 GPUs. For now, these instructions are not
enabled by default and requires using
(`--iree-codegen-llvmgpu-use-mma-sync=true`).

IREE runs row-row matmul and the native Tensor Core support requires
`ldmatrix` for operandA and `ldmatrix.trans` for operandB.
`ldmatrix.trans` transposes the data while loading to use Tensor Core
`mma*row.col*` instruction.

There are LLVM/MLIR upstream pathes and previous IREE PRs that enable
targeting native Tensor Core F16 support.

A few LLVM/MLIR upstream patches:
- [[mlir][NVGPU] Adding Support for cp_async_zfill via Inline
Asm](https://reviews.llvm.org/D132269)
- [[mlir][NVGPU] Handle Native mma.sync sizes and ldmatrix(x4) for
matrixB](https://reviews.llvm.org/D135749)
- [[mlir][NVGPU] Fix affine maps computing indices for LdMatrixOp
srcMemref](https://reviews.llvm.org/D138978)
- [[mlir][NVGPU] Fix NVGPU Bazel
Layering](https://reviews.llvm.org/D141982)


Previous IREE PRs:
- [Support GEMM Pipelining *without* Epilogue
Peeling](iree-org#10388)
- [Add support for GEMM e2e Test For CUDA backend on F16
input](iree-org#10842)
jpienaar pushed a commit that referenced this pull request May 1, 2023
…atrix] (#11817)

Adds native Tensor Core (F16) support for NVIDIA GPUs. Specifically,
adds support to target
`mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16` and `ldmatrix`
instructions on NVIDIA A100 GPUs. For now, these instructions are not
enabled by default and requires using
(`--iree-codegen-llvmgpu-use-mma-sync=true`).

IREE runs row-row matmul and the native Tensor Core support requires
`ldmatrix` for operandA and `ldmatrix.trans` for operandB.
`ldmatrix.trans` transposes the data while loading to use Tensor Core
`mma*row.col*` instruction.

There are LLVM/MLIR upstream pathes and previous IREE PRs that enable
targeting native Tensor Core F16 support.

A few LLVM/MLIR upstream patches:
- [[mlir][NVGPU] Adding Support for cp_async_zfill via Inline
Asm](https://reviews.llvm.org/D132269)
- [[mlir][NVGPU] Handle Native mma.sync sizes and ldmatrix(x4) for
matrixB](https://reviews.llvm.org/D135749)
- [[mlir][NVGPU] Fix affine maps computing indices for LdMatrixOp
srcMemref](https://reviews.llvm.org/D138978)
- [[mlir][NVGPU] Fix NVGPU Bazel
Layering](https://reviews.llvm.org/D141982)


Previous IREE PRs:
- [Support GEMM Pipelining *without* Epilogue
Peeling](#10388)
- [Add support for GEMM e2e Test For CUDA backend on F16
input](#10842)
rengolin pushed a commit to plaidml/iree that referenced this pull request May 2, 2023
…atrix] (iree-org#11817)

Adds native Tensor Core (F16) support for NVIDIA GPUs. Specifically,
adds support to target
`mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16` and `ldmatrix`
instructions on NVIDIA A100 GPUs. For now, these instructions are not
enabled by default and requires using
(`--iree-codegen-llvmgpu-use-mma-sync=true`).

IREE runs row-row matmul and the native Tensor Core support requires
`ldmatrix` for operandA and `ldmatrix.trans` for operandB.
`ldmatrix.trans` transposes the data while loading to use Tensor Core
`mma*row.col*` instruction.

There are LLVM/MLIR upstream pathes and previous IREE PRs that enable
targeting native Tensor Core F16 support.

A few LLVM/MLIR upstream patches:
- [[mlir][NVGPU] Adding Support for cp_async_zfill via Inline
Asm](https://reviews.llvm.org/D132269)
- [[mlir][NVGPU] Handle Native mma.sync sizes and ldmatrix(x4) for
matrixB](https://reviews.llvm.org/D135749)
- [[mlir][NVGPU] Fix affine maps computing indices for LdMatrixOp
srcMemref](https://reviews.llvm.org/D138978)
- [[mlir][NVGPU] Fix NVGPU Bazel
Layering](https://reviews.llvm.org/D141982)


Previous IREE PRs:
- [Support GEMM Pipelining *without* Epilogue
Peeling](iree-org#10388)
- [Add support for GEMM e2e Test For CUDA backend on F16
input](iree-org#10842)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants