Welcome back.
In this video we're going to create the load model file function under the init block.
Start with private function load model file.
Taking into the parameters a model file name of type string and returning map byte buffer.
Let me explain what is the signature of this function?
Mapped byte buffer is a memory mapped file containing the model file.
Here we need to start with val file descriptor context dot assets dot open folder and we specify the
model file name parameter.
This appends the model file from apps folder, returning an asset file descriptor containing file metadata.
Then we need to create the input stream from the file descriptor.
This provides access to read the files raw bytes so val input stream file descriptor.
Create input stream.
The third step is to get file channel from the input stream val file channel equals to input stream
dot channel.
File channel provides memory mapped capabilities to access the files data.
Then we need to create and get file position information.
Start with val start offset equals to file descriptor dot start offset and val declared length file
descriptor dot declare length the start offset position where the actual file data begins, which is
usually zero, and the declared length total size of the file in bytes.
I want from you to write those notes down, because they are very important and help you to, uh, to
memorize what we've done before.
So offset from the beginning and declared length length of the file in the bytes.
The fifth step is memory mapping.
We use memory mapping for efficient loading file isn't fully loaded into heap memory.
Fast access.
Direct memory access to file content.
Low memory usage only needed portions are loaded on demand.
Ideal for large files.
Perfect for machine learning models that can be several memory consuming without memory mapping.
It's inefficient.
This would load entire file into memory, which is less efficient, so we use memory mapping for efficient
loading, fast access, low memory usage, and ideal for large files.
So here returning the map buffer using return file channel dot map.
And here we use the file channel Alt Plus enter to import file channel map mode read only and parameter
number two start offset parameter number three declared length okay.
So this is the memory mapping.
We use it for efficient loading, fast access, low memory usage and idle for large files.
Without it, it will load directly all the file, all the resources, all files into memory.
And this is inefficient.
So here we are creating map byte buffer that directly reference the file data in memory using this approach.
As I showed you here in this video, providing the most efficient way to load TensorFlow Lite models
on Android, minimizing memory usage while ensuring fast model access during inference.