Benchmark (#2348) @tensorflow/micro Formatted column output Added CSV output resolves [b/297590035](https://issuetracker.google.com/297590035) bug=fixes #2347
diff --git a/tensorflow/lite/micro/micro_profiler.cc b/tensorflow/lite/micro/micro_profiler.cc index e7743aa..ebead51 100644 --- a/tensorflow/lite/micro/micro_profiler.cc +++ b/tensorflow/lite/micro/micro_profiler.cc
@@ -99,7 +99,7 @@ } MicroPrintf("%s, %d", each_tag_entry.tag, each_tag_entry.ticks); } - MicroPrintf("total number of ticks, %d", total_ticks); + MicroPrintf("\"total number of ticks\", %d", total_ticks); #endif }
diff --git a/tensorflow/lite/micro/tools/benchmarking/BUILD b/tensorflow/lite/micro/tools/benchmarking/BUILD index 9fda3ae..9984a84 100644 --- a/tensorflow/lite/micro/tools/benchmarking/BUILD +++ b/tensorflow/lite/micro/tools/benchmarking/BUILD
@@ -10,7 +10,6 @@ srcs = ["metrics.cc"], hdrs = ["metrics.h"], deps = [ - ":log_utils", "//tensorflow/lite/micro:micro_profiler", "//tensorflow/lite/micro:recording_allocators", "//tensorflow/lite/micro/arena_allocator:recording_simple_memory_allocator", @@ -18,19 +17,9 @@ ) cc_library( - name = "log_utils", - srcs = ["log_utils.cc"], - hdrs = ["log_utils.h"], - deps = [ - "//tensorflow/lite/micro:micro_log", - ], -) - -cc_library( name = "generic_benchmark_lib", srcs = ["generic_model_benchmark.cc"], deps = [ - ":log_utils", ":metrics", ":op_resolver", "//tensorflow/lite/c:c_api_types",
diff --git a/tensorflow/lite/micro/tools/benchmarking/Makefile.inc b/tensorflow/lite/micro/tools/benchmarking/Makefile.inc index 178d88b..6189be4 100644 --- a/tensorflow/lite/micro/tools/benchmarking/Makefile.inc +++ b/tensorflow/lite/micro/tools/benchmarking/Makefile.inc
@@ -2,12 +2,10 @@ GENERIC_BENCHMARK_SRCS := \ $(MICROLITE_BENCHMARK_ROOT_DIR)/generic_model_benchmark.cc \ -$(MICROLITE_BENCHMARK_ROOT_DIR)/log_utils.cc \ $(MICROLITE_BENCHMARK_ROOT_DIR)/metrics.cc GENERIC_BENCHMARK_HDRS := \ $(MICROLITE_BENCHMARK_ROOT_DIR)/op_resolver.h \ -$(MICROLITE_BENCHMARK_ROOT_DIR)/log_utils.h \ $(MICROLITE_BENCHMARK_ROOT_DIR)/metrics.h ifneq ($(TARGET),bluepill)
diff --git a/tensorflow/lite/micro/tools/benchmarking/generic_model_benchmark.cc b/tensorflow/lite/micro/tools/benchmarking/generic_model_benchmark.cc index 912b84a..1493e87 100644 --- a/tensorflow/lite/micro/tools/benchmarking/generic_model_benchmark.cc +++ b/tensorflow/lite/micro/tools/benchmarking/generic_model_benchmark.cc
@@ -17,6 +17,7 @@ #include <sys/stat.h> #include <sys/types.h> +#include <cstring> #include <memory> #include <random> @@ -29,7 +30,6 @@ #include "tensorflow/lite/micro/recording_micro_allocator.h" #include "tensorflow/lite/micro/recording_micro_interpreter.h" #include "tensorflow/lite/micro/system_setup.h" -#include "tensorflow/lite/micro/tools/benchmarking/log_utils.h" #include "tensorflow/lite/micro/tools/benchmarking/metrics.h" #include "tensorflow/lite/micro/tools/benchmarking/op_resolver.h" #include "tensorflow/lite/schema/schema_generated.h" @@ -53,9 +53,6 @@ // so randomness isn't really needed. constexpr uint32_t kRandomSeed = 0xFB; -// Which format should be used to output debug information. -constexpr PrettyPrintType kPrintType = PrettyPrintType::kTable; - constexpr size_t kTensorArenaSize = 3e6; constexpr int kNumResourceVariable = 100; constexpr size_t kModelSize = 2e6; @@ -101,7 +98,7 @@ return true; } -int Benchmark(const char* model_file_name) { +int Benchmark(const char* model_file_name, tflite::PrettyPrintType print_type) { Profiler profiler; alignas(16) static uint8_t tensor_arena[kTensorArenaSize]; alignas(16) static uint8_t model_file_content[kModelSize]; @@ -154,11 +151,35 @@ } } - LogAllocatorEvents(*allocator, kPrintType); + LogAllocatorEvents(*allocator, print_type); return 0; } } // namespace } // namespace tflite -int main(int argc, char** argv) { return tflite::Benchmark(argv[1]); } +void usage(const char* prog_name) { + MicroPrintf("usage: %s filename [--csv]", prog_name); +} + +int main(int argc, char** argv) { + // Which format should be used to output debug information. + tflite::PrettyPrintType print_type = tflite::PrettyPrintType::kTable; + + if (argc < 2 || argc > 3) { + usage(argv[0]); + return -1; + } + const char* model_filename = argv[1]; + + if (argc == 3) { + if (std::strcmp(argv[2], "--csv") == 0) { + print_type = tflite::PrettyPrintType::kCsv; + } else { + usage(argv[0]); + return -1; + } + } + + return tflite::Benchmark(model_filename, print_type); +}
diff --git a/tensorflow/lite/micro/tools/benchmarking/log_utils.cc b/tensorflow/lite/micro/tools/benchmarking/log_utils.cc deleted file mode 100644 index 808e465..0000000 --- a/tensorflow/lite/micro/tools/benchmarking/log_utils.cc +++ /dev/null
@@ -1,115 +0,0 @@ -/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. - -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. -==============================================================================*/ - -#include "tensorflow/lite/micro/tools/benchmarking/log_utils.h" - -#include <inttypes.h> -#include <stdio.h> -#include <stdlib.h> - -namespace tflite { - -int GetLongestStringLength(const char strings[][kMaxStringLength], - const int count) { - int max_length = 0; - - for (int i = 0; i < count; ++i) { - int size = strlen(strings[i]); - if (size > max_length) { - max_length = size; - } - } - - return max_length; -} - -void FillColumnPadding(char* string, const int size, const int max_size, - const int padding) { - FillString(string, max_size - size + padding, kMaxStringLength); -} - -void FillString(char* string, const int size, const int buffer_size, - const char value) { - if (buffer_size <= (static_cast<int>(strlen(string)))) { - for (int i = 0; i < buffer_size; ++i) { - string[i] = (i < size) ? value : 0; - } - } -} - -void MicroStrcat(char* output, const char* input, const int size) { - if (size < 0) { - strcat(output, input); // NOLINT: strcat required due to no dynamic memory. - } else { - strncat(output, input, size); - } -} - -void MicroStrcpy(char* output, const char* input) { - strcpy(output, input); // NOLINT: strcpy required due to no dynamic memory. -} - -void FormatIntegerDivide(char* output, const int64_t numerator, - const int64_t denominator, const int decimal_places) { - int64_t multiplier = 1; - for (int i = 0; i < decimal_places; ++i) { - multiplier *= 10; - } - - const int64_t total = numerator * multiplier / denominator; - const int whole = static_cast<int>(total / multiplier); - const int fractional = static_cast<int>(total % multiplier); - sprintf(output, "%d.%d", whole, fractional); // NOLINT: sprintf is required. -} - -void FormatAsPercentage(char* output, const int64_t numerator, - const int64_t denominator, const int decimal_places) { - FormatIntegerDivide(output, numerator * 100, denominator, decimal_places); -} - -void PrettyPrintTableHeader(PrettyPrintType type, const char* table_name) { - switch (type) { - case PrettyPrintType::kCsv: - MicroPrintf("[[ CSV ]]: %s", table_name); - break; - case PrettyPrintType::kTable: - MicroPrintf("[[ TABLE ]]: %s", table_name); - } -} - -template <> -void FormatNumber<int32_t>(char* output, int32_t value) { - sprintf(output, "%" PRId32, value); // NOLINT: sprintf required. -} - -template <> -void FormatNumber<size_t>(char* output, size_t value) { - sprintf(output, "%zu", value); // NOLINT: sprintf required. -} - -template <> -void FormatNumber<float>(char* output, float value) { - constexpr int64_t kDenominator = 1000; - FormatIntegerDivide(output, static_cast<int64_t>(value * kDenominator), - kDenominator, 3); -} - -template <> -void FormatNumber<double>(char* output, double value) { - constexpr int64_t kDenominator = 1000; - FormatIntegerDivide(output, static_cast<int64_t>(value * kDenominator), - kDenominator, 3); -} -} // namespace tflite
diff --git a/tensorflow/lite/micro/tools/benchmarking/log_utils.h b/tensorflow/lite/micro/tools/benchmarking/log_utils.h deleted file mode 100644 index ee73f48..0000000 --- a/tensorflow/lite/micro/tools/benchmarking/log_utils.h +++ /dev/null
@@ -1,273 +0,0 @@ -/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. - -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 TFLM_BENCHMARK_INTERNAL_LOG_UTILS_H_ -#define TFLM_BENCHMARK_INTERNAL_LOG_UTILS_H_ - -#include <algorithm> -#include <cstdarg> -#include <cstdint> -#include <cstring> - -#include "tensorflow/lite/micro/micro_log.h" - -namespace tflite { - -// The maxmimum length of a string. -static constexpr int kMaxStringLength = 32; - -// The maximum length of a table row, applies to the header as well. -static constexpr int kMaxRowLength = 100; - -// The default padding between columns in a table. -static constexpr int kDefaultColumnPadding = 4; - -// Defines how formatted data is printed to stdout. -enum class PrettyPrintType { - // Prints as a CSV file. - kCsv, - // Prints as a formatted table. - kTable, -}; - -// Returns the length of the longest string in an array. -// Args: -// - strings: An array of strings. -// - count: The number of strings in the array. -int GetLongestStringLength(const char strings[][kMaxStringLength], int count); - -// Adds padding between two columns in a table. -// ex) "hello" is being inserted into a column. The largest value in that column -// is 10, and there's a global padding of 4 spaces. Therefore, 9 spaces (10 -// - 5 + 4) are added as padding. -// Args: -// - string: The input padding string. -// - size: The size of the string that's being inserted into a column. -// - max_size: The size of the largest string in the column. -// - padding: The amount of padding to add to each column regardless of its -// size. -void FillColumnPadding(char* string, int size, int max_size, - int padding = kDefaultColumnPadding); - -// Fills a string with a specified value. -// Args: -// - string: The input string. This is filled in with the specified value. -// - size: The size of the string after being filled in. This must be less than -// the allocated space for the string. -// - buffer_size: The size of the string's buffer. -// - value: The value to insert into the string. Defaults to a space. -void FillString(char* string, int size, int buffer_size, char value = ' '); - -// Concatenates the input string onto the first. -// Args: -// - output: The destination string for where to append input. -// - input: The input string to concatenate. -// - size: The number of characters to concatenate from the first string. If -// negative, the whole input string will be concatenated. -void MicroStrcat(char* output, const char* input, int size = -1); - -// Copies the input string into the output. -void MicroStrcpy(char* output, const char* input); - -// Formats a division operation to have a specified number of decimal places. -// Args: -// - output: The output string to be formatted. -// - numerator: The numerator in the division operation. -// - denominator: The denominator in the division operation. -// - decimal places: The number of decimal places to print to. -void FormatIntegerDivide(char* output, int64_t numerator, int64_t denominator, - int decimal_places); - -// Formats a division operation as a percentage. -// Args: -// - output: The output string to be formatted. -// - numerator: The numerator in the division operation. -// - denominator: The denominator in the division operation. -// - decimal places: The number of decimal places to print to. -void FormatAsPercentage(char* output, int64_t numerator, int64_t denominator, - int decimal_places); - -void PrettyPrintTableHeader(PrettyPrintType type, const char* table_name); - -// Formats a number as a string. -// Args: -// - output: The location of where to write the formatted number. -// - value: The value to write to a string. -template <typename T> -void FormatNumber(char* output, T value); - -// Pretty prints a table to stdout. -// Note: kMaxRows and kColumns should describe the allocated size of the table, -// not the amount of data that is populated. It is required that all -// columns are filled out, but not all rows. -// -// ex) PrintTable<3, 25>(headers, data, 4); -// This will print a table with 3 columns and 4 rows. In this example, it -// is required that data is defined as char[3][25][kMaxStringLength] to -// properly print. -// -// op cycles cpu % -// ------------------------- -// foo | 1000 | 10 -// bar | 2500 | 25 -// baz | 1000 | 10 -// lorem | 2000 | 20 -// -// Args: -// - headers: A 1D array of strings containing the headers of the table. This -// must be equal in size to kColumns. -// - data: A 2D array of string data organized in [columns, rows]. As stated -// above, it is required that all columns are populated, but not all rows. -// - rows: The number of populated rows in `data`. -template <int kMaxRows, int kColumns> -void PrintTable(const char headers[kColumns][kMaxStringLength], - const char data[kColumns][kMaxRows][kMaxStringLength], - const int rows) { - // Get the maximum width for each column in the table. - int max_column_width[kColumns]; - for (int i = 0; i < kColumns; ++i) { - max_column_width[i] = std::max(GetLongestStringLength(data[i], rows), - static_cast<int>(strlen(headers[i]))); - } - - // Add padding between each item in the header so it can be printed on one - // line. - char header_spaces[kColumns][kMaxStringLength]; - for (int i = 0; i < kColumns; ++i) { - FillColumnPadding(header_spaces[i], strlen(headers[i]), max_column_width[i], - kDefaultColumnPadding + 2); - } - - // Print the header. - char header[kMaxRowLength]; - memset(header, 0, kMaxRowLength); - for (int i = 0; i < kColumns; ++i) { - MicroStrcat(header, headers[i]); - MicroStrcat(header, header_spaces[i]); - } - MicroPrintf("%s", header); - - // Print a separator to separate the header from the data. - char separator[kMaxRowLength]; - FillString(separator, strlen(header) - 1, kMaxRowLength, '-'); - MicroPrintf("%s", separator); - - for (int i = 0; i < rows; ++i) { - char spaces[kColumns][kMaxStringLength]; - for (int j = 0; j < kColumns; ++j) { - FillColumnPadding(spaces[j], strlen(data[j][i]), max_column_width[j]); - } - - char row[kMaxRowLength]; - memset(row, 0, kMaxRowLength); - - // Concatenate each column in a row with the format "[data][padding]| " - for (int j = 0; j < kColumns; ++j) { - MicroStrcat(row, data[j][i]); - MicroStrcat(row, spaces[j]); - MicroStrcat(row, "| "); - } - - MicroPrintf("%s", row); - } - - MicroPrintf(separator); - MicroPrintf(""); -} - -// Pretty prints a csv to stdout. -// Note: kMaxRows and kColumns should describe the allocated size of the table, -// not the amount of data that is populated. It is required that all -// columns are filled out, but not all rows. -// -// ex) -// op,cycles,%cpu -// foo,1000,10 -// bar,2500,25 -// baz,1000,10 -// -// Args: -// - headers: A 1D array of strings containing the headers of the table. This -// must be equal in size to kColumns. -// - data: A 2D array of string data organized in [columns, rows]. As stated -// above, it is required that all columns are populated, but not all rows. -// - rows: The number of populated rows in `data`. -template <int kMaxRows, int kColumns> -void PrintCsv(const char headers[kColumns][kMaxStringLength], - const char data[kColumns][kMaxRows][kMaxStringLength], - const int rows) { - char header[kMaxRowLength]; - memset(header, 0, kMaxRowLength); - for (int i = 0; i < kColumns; ++i) { - MicroStrcat(header, headers[i]); - if (i < kColumns - 1) { - MicroStrcat(header, ","); - } - } - - MicroPrintf("%s", header); - - char row[kMaxRowLength]; - for (int i = 0; i < rows; ++i) { - memset(row, 0, kMaxRowLength); - for (int j = 0; j < kColumns; ++j) { - MicroStrcat(row, data[j][i]); - if (j < kColumns - 1) { - MicroStrcat(row, ","); - } - } - - MicroPrintf("%s", row); - } - - MicroPrintf(""); // Serves as a new line. -} - -// Prints a 2D array of strings in a formatted manner along with a table name -// that includes the table type. -// -// Note: kMaxRows and kColumns should describe the allocated size of the table, -// not the amount of data that is populated. It is required that all -// columns are filled out, but not all rows. -// -// ex) PrettyPrint::kCsv will print a csv with a [[ CSV ]]: table_name header. -// -// Args: -// - headers: A 1D array of strings containing the headers of the table. This -// must be equal in size to kColumns. -// - data: A 2D array of string data organized in [columns, rows]. As stated -// above, it is required that all columns are populated, but not all rows. -// - rows: The number of populated rows in `data`. -// - type: The format type that should be used to pretty print. -// - table_name: The name of the table to be printed alongside the format type. -template <int kMaxRows, int kColumns> -void PrintFormattedData(const char headers[kColumns][kMaxStringLength], - const char data[kColumns][kMaxRows][kMaxStringLength], - const int rows, const PrettyPrintType type, - const char* table_name) { - PrettyPrintTableHeader(type, table_name); - switch (type) { - case PrettyPrintType::kCsv: - PrintCsv<kMaxRows, kColumns>(headers, data, rows); - break; - case PrettyPrintType::kTable: - PrintTable<kMaxRows, kColumns>(headers, data, rows); - break; - } -} - -} // namespace tflite - -#endif // TFLM_BENCHMARK_INTERNAL_LOG_UTILS_H_
diff --git a/tensorflow/lite/micro/tools/benchmarking/metrics.cc b/tensorflow/lite/micro/tools/benchmarking/metrics.cc index 115d879..3a4bf7e 100644 --- a/tensorflow/lite/micro/tools/benchmarking/metrics.cc +++ b/tensorflow/lite/micro/tools/benchmarking/metrics.cc
@@ -15,44 +15,70 @@ #include "tensorflow/lite/micro/tools/benchmarking/metrics.h" -#include <sys/types.h> - #include <cstddef> +#include <cstring> +#include <iterator> +#include <type_traits> +#include <utility> -#include "tensorflow/lite/micro/tools/benchmarking/log_utils.h" +#include "tensorflow/lite/kernels/internal/compatibility.h" +#include "tensorflow/lite/micro/micro_log.h" namespace tflite { -void LogArenaAllocations( +namespace { + +struct LogArenaRecord { + const char* title; + int allocations; + float percentage; +}; + +struct LogAllocationRecord { + const char* title; + int type; + int used_bytes; + int requested_bytes; + int count; + float percentage; +}; + +constexpr int kArenaRows = 3; +constexpr int kArenaColumns = 3; + +constexpr int kAllocationTypes = 7; +constexpr int kAllocationColumns = 6; + +constexpr int kMaxBufSize = 100; + +LogArenaRecord GetLogArenaRecord( const tflite::RecordingSingleArenaBufferAllocator* allocator, - const PrettyPrintType type) { - constexpr int kArenaRows = 3; - constexpr int kArenaCols = 3; + int row_index) { + TFLITE_DCHECK(row_index < kArenaRows); const size_t total_bytes = allocator->GetUsedBytes(); + const size_t allocations[] = {total_bytes, + allocator->GetNonPersistentUsedBytes(), + allocator->GetPersistentUsedBytes()}; + static_assert(std::extent<decltype(allocations)>::value == kArenaRows, + "kArenaRows mismatch"); + const char* titles[] = {"Total", "NonPersistent", "Persistent"}; + static_assert(std::extent<decltype(titles)>::value == kArenaRows, + "kArenaRows mismatch"); - size_t allocations[kArenaRows] = {total_bytes, - allocator->GetNonPersistentUsedBytes(), - allocator->GetPersistentUsedBytes()}; - char titles[kArenaRows][kMaxStringLength] = {"Total", "Head", "Tail"}; - char headers[kArenaRows][kMaxStringLength] = {"Arena", "Bytes", "% Arena"}; + LogArenaRecord record = {}; + record.title = titles[row_index]; + record.allocations = allocations[row_index]; + record.percentage = record.allocations * 100.0f / total_bytes; - char data[kArenaCols][kArenaRows][kMaxStringLength]; - for (int i = 0; i < kArenaRows; ++i) { - MicroStrcpy(data[0][i], titles[i]); - FormatNumber<int32_t>(data[1][i], allocations[i]); - FormatAsPercentage(data[2][i], static_cast<int64_t>(allocations[i]), - static_cast<int64_t>(total_bytes), 2); - } - - PrintFormattedData<kArenaRows, kArenaCols>(headers, data, kArenaRows, type, - "Arena"); + return record; } -void LogAllocations(const tflite::RecordingMicroAllocator& allocator, - const PrettyPrintType type) { - constexpr int kAllocationTypes = 7; - tflite::RecordedAllocationType types[kAllocationTypes] = { +LogAllocationRecord GetLogAllocationRecord( + const tflite::RecordingMicroAllocator& allocator, int row_index) { + TFLITE_DCHECK(row_index < kAllocationTypes); + + const tflite::RecordedAllocationType types[] = { tflite::RecordedAllocationType::kTfLiteEvalTensorData, tflite::RecordedAllocationType::kPersistentTfLiteTensorData, tflite::RecordedAllocationType::kPersistentTfLiteTensorQuantizationData, @@ -60,38 +86,227 @@ tflite::RecordedAllocationType::kTfLiteTensorVariableBufferData, tflite::RecordedAllocationType::kNodeAndRegistrationArray, tflite::RecordedAllocationType::kOpData}; - - char titles[kAllocationTypes][kMaxStringLength] = { - "Eval tensor data", - "Persistent tensor data", - "Persistent quantization data", - "Persistent buffer data", - "Tensor variable buffer data", - "Node and registration array", - "Operation data"}; - - constexpr int kColumns = 6; - const char headers[kColumns][kMaxStringLength] = { - "Allocation", "Id", "Used", "Requested", "Count", "% Memory"}; - + static_assert(std::extent<decltype(types)>::value == kAllocationTypes, + "kAllocationTypes mismatch"); + const char* titles[] = {"Eval tensor data", + "Persistent tensor data", + "Persistent quantization data", + "Persistent buffer data", + "Tensor variable buffer data", + "Node and registration array", + "Operation data"}; + static_assert(std::extent<decltype(titles)>::value == kAllocationTypes, + "kAllocationTypes mismatch"); const size_t total_bytes = allocator.GetSimpleMemoryAllocator()->GetUsedBytes(); + tflite::RecordedAllocation allocation = + allocator.GetRecordedAllocation(types[row_index]); - char data[kColumns][kAllocationTypes][kMaxStringLength]; - for (int i = 0; i < kAllocationTypes; ++i) { - tflite::RecordedAllocation allocation = - allocator.GetRecordedAllocation(types[i]); - MicroStrcpy(data[0][i], titles[i]); - FormatNumber<int32_t>(data[1][i], static_cast<int>(types[i])); - FormatNumber<int32_t>(data[2][i], allocation.used_bytes); - FormatNumber<int32_t>(data[3][i], allocation.requested_bytes); - FormatNumber<int32_t>(data[4][i], allocation.count); - FormatAsPercentage(data[5][i], static_cast<int64_t>(allocation.used_bytes), - static_cast<int64_t>(total_bytes), 2); + LogAllocationRecord record = {}; + record.title = titles[row_index]; + record.type = static_cast<int>(types[row_index]); + record.used_bytes = allocation.used_bytes; + record.requested_bytes = allocation.requested_bytes; + record.count = allocation.count; + record.percentage = allocation.used_bytes * 100.0f / total_bytes; + + return record; +} + +template <int kColumns> +void UpdateColumnWidths(int (&widths)[kColumns], const char* s[kColumns]) { + for (int i = 0; i < kColumns; i++) { + widths[i] = std::max(widths[i], static_cast<int>(std::strlen(s[i]))); + } +} + +void UpdateColumnWidths(int (&widths)[kArenaColumns], + const LogArenaRecord& record) { + char buf[kMaxBufSize]; + int count; + + count = MicroSnprintf(buf, kMaxBufSize, "%s", record.title); + widths[0] = std::max(widths[0], count); + count = MicroSnprintf(buf, kMaxBufSize, "%d", record.allocations); + widths[1] = std::max(widths[1], count); + count = MicroSnprintf(buf, kMaxBufSize, "%.2f", + static_cast<double>(record.percentage)); + widths[2] = std::max(widths[2], count); +} + +void UpdateColumnWidths(int (&widths)[kAllocationColumns], + const LogAllocationRecord& record) { + char buf[kMaxBufSize]; + int count; + + count = MicroSnprintf(buf, kMaxBufSize, "%s", record.title); + widths[0] = std::max(widths[0], count); + count = MicroSnprintf(buf, kMaxBufSize, "%d", record.type); + widths[1] = std::max(widths[1], count); + count = MicroSnprintf(buf, kMaxBufSize, "%d", record.used_bytes); + widths[2] = std::max(widths[2], count); + count = MicroSnprintf(buf, kMaxBufSize, "%d", record.requested_bytes); + widths[3] = std::max(widths[3], count); + count = MicroSnprintf(buf, kMaxBufSize, "%d", record.count); + widths[4] = std::max(widths[4], count); + count = MicroSnprintf(buf, kMaxBufSize, "%.2f", + static_cast<double>(record.percentage)); + widths[5] = std::max(widths[5], count); +} + +using BufferDatum = std::tuple<char*, char*>; + +template <typename T> +BufferDatum AddTableColumnValue(const BufferDatum& buffer, const char* format, + int column_width, T value, + const char* separator = nullptr) { + char* p; + char* p_end; + std::tie(p, p_end) = buffer; + int count = MicroSnprintf(p, p_end - p, format, column_width, value); + p += count; + if (separator != nullptr && p < p_end) { + count = MicroSnprintf(p, p_end - p, separator); + p += count; } - PrintFormattedData<kAllocationTypes, kColumns>( - headers, data, kAllocationTypes, type, "Allocations"); + if (p > p_end) { + p = p_end; + } + + return std::make_tuple(p, p_end); +} + +} // namespace + +void LogArenaAllocations( + const tflite::RecordingSingleArenaBufferAllocator* allocator, + const PrettyPrintType type) { + const char* headers[] = {"Arena", "Bytes", "%% Arena"}; + static_assert(std::extent<decltype(headers)>::value == kArenaColumns, + "kArenaColumns mismatch"); + char buffer[kMaxBufSize]; + BufferDatum buffer_datum = + std::make_tuple(std::begin(buffer), std::end(buffer)); + int column_widths[kArenaColumns] = {}; + + const char* output_type; + const char* string_format; + if (type == PrettyPrintType::kCsv) { + output_type = "CSV"; + string_format = "\"%*s\""; + } else { + output_type = "Table"; + string_format = "%*s"; + + UpdateColumnWidths<kArenaColumns>(column_widths, headers); + for (int i = 0; i < kArenaRows; i++) { + LogArenaRecord record = GetLogArenaRecord(allocator, i); + UpdateColumnWidths(column_widths, record); + } + } + + MicroPrintf("[[ %s ]]: Arena", output_type); + + for (int i = 0; i < kArenaColumns; i++) { + // create header + const char* separator = nullptr; + if (i != kArenaColumns - 1) { + // separator for all but last column value + if (type == PrettyPrintType::kCsv) { + separator = ","; + } else { + separator = " "; + } + } + buffer_datum = AddTableColumnValue(buffer_datum, string_format, + column_widths[i], headers[i], separator); + } + MicroPrintf(buffer); + + for (int i = 0; i < kArenaRows; ++i) { + // create rows + const char* separator = (type == PrettyPrintType::kCsv) ? "," : " | "; + buffer_datum = std::make_tuple(std::begin(buffer), std::end(buffer)); + LogArenaRecord record = GetLogArenaRecord(allocator, i); + buffer_datum = AddTableColumnValue( + buffer_datum, string_format, column_widths[0], record.title, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*d", column_widths[1], + record.allocations, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*.2f", column_widths[2], + static_cast<double>(record.percentage)); + MicroPrintf(buffer); + } + + MicroPrintf(""); // output newline +} + +void LogAllocations(const tflite::RecordingMicroAllocator& allocator, + const PrettyPrintType type) { + const char* headers[] = {"Allocation", "Id", "Used", + "Requested", "Count", "%% Memory"}; + static_assert(std::extent<decltype(headers)>::value == kAllocationColumns, + "kAllocationColumns mismatch"); + char buffer[kMaxBufSize]; + BufferDatum buffer_datum = + std::make_tuple(std::begin(buffer), std::end(buffer)); + int column_widths[kAllocationColumns] = {}; + + const char* output_type; + const char* string_format; + if (type == PrettyPrintType::kCsv) { + output_type = "CSV"; + string_format = "\"%*s\""; + } else { + output_type = "Table"; + string_format = "%*s"; + + UpdateColumnWidths<kAllocationColumns>(column_widths, headers); + for (int i = 0; i < kAllocationTypes; i++) { + LogAllocationRecord record = GetLogAllocationRecord(allocator, i); + UpdateColumnWidths(column_widths, record); + } + } + + MicroPrintf("[[ %s ]]: Allocations", output_type); + + for (int i = 0; i < kAllocationColumns; i++) { + // create header + const char* separator = nullptr; + if (i != kAllocationColumns - 1) { + // separator for all but last column value + if (type == PrettyPrintType::kCsv) { + separator = ","; + } else { + separator = " "; + } + } + buffer_datum = AddTableColumnValue(buffer_datum, string_format, + column_widths[i], headers[i], separator); + } + MicroPrintf(buffer); + + for (int i = 0; i < kAllocationTypes; ++i) { + // create rows + const char* separator = (type == PrettyPrintType::kCsv) ? "," : " | "; + buffer_datum = std::make_tuple(std::begin(buffer), std::end(buffer)); + LogAllocationRecord record = GetLogAllocationRecord(allocator, i); + buffer_datum = AddTableColumnValue( + buffer_datum, string_format, column_widths[0], record.title, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*d", column_widths[1], + record.type, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*d", column_widths[2], + record.used_bytes, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*d", column_widths[3], + record.requested_bytes, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*d", column_widths[4], + record.count, separator); + buffer_datum = AddTableColumnValue(buffer_datum, "%*.2f", column_widths[5], + static_cast<double>(record.percentage)); + MicroPrintf(buffer); + } + + MicroPrintf(""); // output newline } void LogAllocatorEvents(const tflite::RecordingMicroAllocator& allocator, @@ -99,4 +314,5 @@ LogArenaAllocations(allocator.GetSimpleMemoryAllocator(), type); LogAllocations(allocator, type); } + } // namespace tflite
diff --git a/tensorflow/lite/micro/tools/benchmarking/metrics.h b/tensorflow/lite/micro/tools/benchmarking/metrics.h index 5c0c880..996cde1 100644 --- a/tensorflow/lite/micro/tools/benchmarking/metrics.h +++ b/tensorflow/lite/micro/tools/benchmarking/metrics.h
@@ -16,17 +16,19 @@ #ifndef TFLM_BENCHMARK_INTERNAL_METRICS_H_ #define TFLM_BENCHMARK_INTERNAL_METRICS_H_ -#include <stdio.h> - -#include <cmath> -#include <cstdint> - #include "tensorflow/lite/micro/micro_profiler.h" #include "tensorflow/lite/micro/recording_micro_allocator.h" -#include "tensorflow/lite/micro/tools/benchmarking/log_utils.h" namespace tflite { +// Defines how formatted data is printed to stdout. +enum class PrettyPrintType { + // Prints as a CSV file. + kCsv, + // Prints as a formatted table. + kTable, +}; + // Logs the allocation events. Prints out two tables, one for the arena // allocations, and one for each type of TFLM allocation type. // Args: