• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include <fuzzer/FuzzedDataProvider.h>
16 
17 #include <cstdint>
18 #include <cstdlib>
19 
20 #include "tensorflow/core/framework/bfloat16.h"
21 #include "tensorflow/core/platform/test.h"
22 
23 // This is a fuzzer for tensorflow::FloatToBFloat16 and
24 // tensorflow::BFloat16ToFloat.
25 
26 namespace {
27 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)28 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
29   FuzzedDataProvider fuzzed_data(data, size);
30 
31   const int array_size = 100;
32 
33   float float_originals[array_size];
34   for (int i = 0; i < array_size; ++i) {
35     float_originals[i] = fuzzed_data.ConsumeFloatingPointInRange(1.0f, 1000.0f);
36   }
37   tensorflow::bfloat16 bfloats[array_size];
38   float floats_converted[array_size];
39 
40   tensorflow::FloatToBFloat16(float_originals, bfloats, array_size);
41   tensorflow::BFloat16ToFloat(bfloats, floats_converted, array_size);
42 
43   for (int i = 0; i < array_size; ++i) {
44     // The relative error should be less than 1/(2^7) since bfloat16
45     // has 7 bits mantissa.
46     // Copied this logic from bfloat16_test.cc
47     assert(fabs(floats_converted[i] - float_originals[i]) / float_originals[i] <
48            1.0 / 128);
49   }
50 
51   return 0;
52 }
53 
54 }  // namespace
55