Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: model compression draft for review #2767

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions tensorflow/lite/micro/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ tflm_cc_library(
],
)

tflm_cc_library(
name = "compression",
hdrs = [
"compression.h",
],
deps = [
"//tensorflow/lite/c:common",
],
)

tflm_cc_library(
# TODO(b/187093492): Rename to micro_interpreter.
name = "micro_framework",
Expand Down Expand Up @@ -62,10 +72,14 @@ tflm_cc_library(
"micro_context.h",
],
deps = [
":compression",
":micro_common",
":micro_graph",
":micro_log",
":micro_profiler",
"//tensorflow/lite:type_to_tflitetype",
"//tensorflow/lite/c:common",
"//tensorflow/lite/micro/kernels:decompress",
],
)

Expand Down Expand Up @@ -135,6 +149,7 @@ tflm_cc_library(
":memory_helpers",
":micro_allocator",
":micro_common",
":micro_context",
":micro_graph",
":micro_log",
":micro_profiler",
Expand Down Expand Up @@ -162,6 +177,7 @@ tflm_cc_library(
tflm_cc_library(
name = "micro_allocator",
srcs = [
"compression.h",
"micro_allocation_info.cc",
"micro_allocator.cc",
],
Expand All @@ -170,6 +186,7 @@ tflm_cc_library(
"micro_allocator.h",
],
deps = [
":compression",
":flatbuffer_utils",
":memory_helpers",
":micro_arena_constants",
Expand All @@ -182,6 +199,7 @@ tflm_cc_library(
"//tensorflow/lite/micro/arena_allocator:non_persistent_arena_buffer_allocator",
"//tensorflow/lite/micro/arena_allocator:persistent_arena_buffer_allocator",
"//tensorflow/lite/micro/arena_allocator:simple_memory_allocator",
"//tensorflow/lite/micro/compression:metadata_saved",
"//tensorflow/lite/micro/memory_planner:greedy_memory_planner",
"//tensorflow/lite/micro/memory_planner:linear_memory_planner",
"//tensorflow/lite/micro/memory_planner:micro_memory_planner",
Expand Down Expand Up @@ -235,7 +253,9 @@ tflm_cc_library(
"test_helpers.h",
],
deps = [
":compression",
":memory_helpers",
":micro_log",
":micro_utils",
":op_resolvers",
"//tensorflow/lite:type_to_tflitetype",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,6 @@ class NonPersistentArenaBufferAllocator : public INonPersistentBufferAllocator {
// takes in account any temporary allocations.
size_t GetAvailableMemory(size_t alignment) const override;

TF_LITE_REMOVE_VIRTUAL_DELETE

private:
// The memory arena that this allocator manages.
uint8_t* const buffer_head_;
Expand All @@ -97,6 +95,8 @@ class NonPersistentArenaBufferAllocator : public INonPersistentBufferAllocator {
// Count of outstanding temp buffers.
int temp_buffer_count_ = 0;
bool resizable_buffer_allocated_ = false;

TF_LITE_REMOVE_VIRTUAL_DELETE
};

} // namespace tflite
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ class PersistentArenaBufferAllocator : public IPersistentBufferAllocator {
// Returns the size of all persistent allocations in bytes.
size_t GetPersistentUsedBytes() const override;

TF_LITE_REMOVE_VIRTUAL_DELETE
private:
// The memory arena that this allocator manages.
uint8_t* const buffer_head_;
Expand All @@ -51,6 +50,8 @@ class PersistentArenaBufferAllocator : public IPersistentBufferAllocator {
// So in essence, the allocated region grows from the bottom and emulates
// SingleArenaBufferAllocator's persistent part.
uint8_t* tail_temp_;

TF_LITE_REMOVE_VIRTUAL_DELETE
};

} // namespace tflite
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ class SingleArenaBufferAllocator : public INonPersistentBufferAllocator,
// account any temporary allocations.
size_t GetUsedBytes() const;

TF_LITE_REMOVE_VIRTUAL_DELETE

protected:
// Returns a pointer to the current end of the head buffer.
uint8_t* head() const;
Expand All @@ -137,6 +135,8 @@ class SingleArenaBufferAllocator : public INonPersistentBufferAllocator,
intptr_t temp_buffer_ptr_check_sum_ = 0;
// Count of outstanding temp buffers.
int temp_buffer_count_ = 0;

TF_LITE_REMOVE_VIRTUAL_DELETE
};

} // namespace tflite
Expand Down
68 changes: 68 additions & 0 deletions tensorflow/lite/micro/compression.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* Copyright 2024 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 TENSORFLOW_LITE_MICRO_MICRO_COMPRESSION_H_
#define TENSORFLOW_LITE_MICRO_MICRO_COMPRESSION_H_

#ifdef USE_TFLM_COMPRESSION

#include "tensorflow/lite/c/common.h"

namespace tflite {

//
// Compressed tensors
//

static constexpr const char* kCompressionMetadataString =
"COMPRESSION_METADATA";

enum class CompressionScheme : uint8_t {
kBinQuant,
};

struct LookupTableData {
static constexpr size_t kMaxBitWidth = 7;
static constexpr size_t kMaxValueTableChannelStride = 128;

const void* value_table; // Pointer into FlatBuffer Values.
uint8_t value_table_channel_stride; // elements per channel
uint8_t compressed_bit_width : 3; // 1 to 7 bits
bool is_per_channel_quantized : 1; // tensor is per-channel quantized
bool use_alternate_axis : 1; // shape default channel:
// 0 = first, 1 = last
uint8_t reserved : 3;
};

union CompressionData {
LookupTableData* lut_data;
};

struct CompressionTensorData {
CompressionScheme scheme;
CompressionData data;
};

struct CompressedTensorList {
// Sparsely populated array with the same number of elements as there are
// tensors in the Subgraph. An alternative would include a tensor index in
// the struct for each and walk the list on look up. This could be slow.
const CompressionTensorData** tensors;
};

} // namespace tflite

#endif // USE_TFLM_COMPRESSION
#endif // TENSORFLOW_LITE_MICRO_MICRO_COMPRESSION_H_
27 changes: 27 additions & 0 deletions tensorflow/lite/micro/compression/model_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,37 @@ def __init__(self, operator, index, subgraph):
def opcode(self) -> tflite.OperatorCodeT:
return self.subgraph.model.operatorCodes[self.operator.opcodeIndex]

@property
def builtin_opcode(self) -> int:
result: int = self.opcode.deprecatedBuiltinCode
if result == tflite.BuiltinOperator.PLACEHOLDER_FOR_GREATER_OP_CODES:
result = self.opcode.builtinCode
return result

@property
def inputs(self):
return _IndirectIterator(self.operator.inputs, self.subgraph.tensors)

@property
def outputs(self):
return _IndirectIterator(self.operator.outputs, self.subgraph.tensors)

@property
def inputs_indices(self):
return self.operator.inputs

@property
def outputs_indices(self):
return self.operator.outputs

@property
def builtin_options_type(self) -> int:
return self.operator.builtinOptionsType

@property
def builtin_options(self):
return self.operator.builtinOptions


_NP_DTYPES = {
tflite.TensorType.FLOAT16: np.dtype("<f2"),
Expand Down
114 changes: 71 additions & 43 deletions tensorflow/lite/micro/docs/compression.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,15 +234,48 @@ Only the following methods are required to implement decompression within kernel

* `MicroContext::AllocateDecompressionScratchBuffer` ([micro_context.h](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/micro_context.h)):
Allocates a scratch memory buffer within the `MicroInterpreter` to hold the
decompressed tensor data.
decompressed tensor data. The returned scratch memory handle must be retained
(typically through kernel `OpData`) for use during the kernel inference operation.
* `MicroContext::GetTensorCompressionData` ([micro_context.h](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/micro_context.h)):
Retrieves compressed tensor information (see [compression.h](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/compression.h)).
* `tflite::micro::GetTensorData` ([kernel_util.h](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/kernels/kernel_util.h)):
The four argument version of this method will automatically decompress the
tensor data into the supplied scratch memory buffer.
The four parameter version of this method will automatically decompress the
tensor data into the supplied scratch memory buffer. The lifetime of a scratch
buffer is the same as the lifetime of the current kernel operator being processed.
Each call to the four parameter version of this method will always result in a
decompression operation being performed, if the tensor supplied is compressed.

Please see the [TRANSPOSE_CONV](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/kernels/transpose_conv.cc)
reference kernel code for an example of how tensor decompression is implemented.
reference kernel code for an example of how to implement tensor decompression
within a kernel.

### Alternate Decompression Memory

Alternate decompression memory regions allow the use of specialized memory
available to the processor, to be used as the target of a tensor decompression
operation. Such memory is typically mapped by the application through a linker
script. The application would then use a C++ attribute of the form:
```
__attribute__((section(".your-specialized-memory")))
```
to link one or more application symbols to the specialized memory region.

Only a single API is required to use alternate decompression memory regions in
an application:
* `MicroInterpreter::SetDecompressionMemory` ([micro_interpreter.h](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/micro_interpreter.h)):
Specify the address and size of each alternate decompression
memory region. This method must be called before the application calls
`MicroInterpreter::AllocateTensors`. The lifetime of the method parameter must
equal the lifetime of the `MicroInterpreter` instance. The memory regions
specified by the method parameter must not overlap, and each region is considered
to be non-contiguous with all other regions.

Specifying alternate decompression memory will cause `MicroContext::AllocateDecompressionScratchBuffer`
and `tflite::micro::GetTensorData` (the four parameter version)
to automatically attempt to allocate memory for the decompression destination
buffer from available memory in one of the alternate memory regions. If no
alternate memory region of sufficient size is available, a scratch buffer will
be allocated within the `MicroInterpreter` arena.

# How to Compress a Model

Expand All @@ -253,61 +286,56 @@ a tensor to just four values among the tensor elements, a fixed-width of two bit
can be used for each element. This would result in nearly a four-fold decrease
in the size of an INT8 tensor.

Tensors to compress are specified with the `--tensors="#, #, ...#"` flag.
Per-channel quantized tensors using an alternate quantization axis (such as the
filter tensor supplied to DEPTHWISE_CONV) must use the `--alt_axis_tensors=` flag.

First, align your binned model:
Tensors to compress are specified with a `YAML` file. For example, if tensors
5, 10, 11, 22 of subgraph 0 of the model are to be compressed, the contents of
the file would be as follows:
```
bazel run --cache_test_results=no --test_output=all -s tensorflow/lite/micro/tools:tflite_flatbuffer_align -- binned_model.tflite binned_and_aligned.tflite
tensors:

- subgraph: 0
tensor: 5
compression:
- lut:
index_bitwidth: 4

- subgraph: 0
tensor: 10
compression:
- lut:
index_bitwidth: 4

- subgraph: 0
tensor: 11
compression:
- lut:
index_bitwidth: 2

- subgraph: 0
tensor: 22
compression:
- lut:
index_bitwidth: 2
```
Note that each tensor can have a different bit width (1 through 7 bits).

Next, compress the model, supplying as arguments the target tensors:
Once the `YAML` specification is ready, compress the model using the following:
```
bazel run --cache_test_results=no --test_output=all -s tensorflow/lite/micro/compression:compress -- binned_and_aligned.tflite compressed.tflite --tensors="1, 2, 7, 10, 3, 5"
bazel run -s tensorflow/lite/micro/compression:compress -- --input=binned.tflite --output=compressed.tflite --spec=spec.yaml
```

Then align the model:
```
bazel run --cache_test_results=no --test_output=all -s tensorflow/lite/micro/tools:tflite_flatbuffer_align -- compressed.tflite compressed_and_aligned.tflite
bazel run -s tensorflow/lite/micro/tools:tflite_flatbuffer_align -- compressed.tflite compressed_and_aligned.tflite
```

# The Generic Benchmark Application

The Generic Benchmark Application can be used to see the size of the model, the
amount of arena memory used, and the size of the interpreter data structures
including those involved with tensor conpression.

including those involved with tensor compression.
The benchmark also reports total inference time, as well as time taken for
tensor decompression. Timing data may be either wall-clock time or processor
cycle time. The type of timing data is dependent on the underlying platform
and/or simulator used. In some cases, no timing data is available.

The benchmark output includes a CRC32 of the output tensor(s) for comparison
within the same platform on which the benchmark is run.
tensor decompression.

For additional information on the Generic Benchmark Application, please refer to
this [document](https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/tools/benchmarking/README.md).

## How to Run the Generic Benchmark Application

The Generic Benchmark Application can only be built using `make`.

### Without Compression

HIFI3 example:
```
make -f ${TENSORFLOW_ROOT}tensorflow/lite/micro/tools/make/Makefile BUILD_TYPE=default run_tflm_benchmark -j$(nproc) GENERIC_BENCHMARK_MODEL_PATH=binned_and_aligned.tflite TARGET=xtensa TARGET_ARCH=hifi3 OPTIMIZED_KERNEL_DIR=xtensa XTENSA_CORE=HIFI_190304_swupgrade
```

The model path can be an abolute path, or relative to your local TFLM repository.

### With Compression

HIFI5 example:
```
make -f ${TENSORFLOW_ROOT}tensorflow/lite/micro/tools/make/Makefile BUILD_TYPE=default run_tflm_benchmark -j$(nproc) GENERIC_BENCHMARK_MODEL_PATH=compressed_and_aligned.tflite TARGET=xtensa TARGET_ARCH=hifi5 OPTIMIZED_KERNEL_DIR=xtensa XTENSA_CORE=PRD_H5_RDO_07_01_2022 USE_TFLM_COMPRESSION=1
```

The model path can be an abolute path, or relative to your local TFLM repository.

Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ namespace {
// Arena size is a guesstimate, followed by use of
// MicroInterpreter::arena_used_bytes() on both the AudioPreprocessor and
// MicroSpeech models and using the larger of the two results.
constexpr size_t kArenaSize = 28584; // xtensa p6
constexpr size_t kArenaSize = 30 * 1024;
alignas(16) uint8_t g_arena[kArenaSize];

using Features = int8_t[kFeatureCount][kFeatureSize];
Expand Down
Loading
Loading