MemoryError but I have enough memory

Hello! I am having problems managing memory. To provide some context, I am using a neural network with the new ML library on an OpenMV H7 board. It works well when I use it with the “mobilenet detection” example provided by the IDE. I embedded my network into the firmware and have been cleaning up variables so it can be used in a real application that I have been developing. Today, I realized that even though I have more memory than needed, I still keep getting this memory allocation error. I would appreciate any help you can provide. Here is a part of the code I am using and the error output.

def InferenceAI(blobList, img):
    labels=[]
    objectsDetected=[]
    gc.collect()
    print("Free memory: {} bytes".format(gc.mem_free()))
    print("Used memory: {} bytes".format(gc.mem_alloc()))
    net = ml.Model("detection_custom") ## Error line

Free memory: 273264 bytes
Used memory: 19872 bytes

Traceback (most recent call last):
File “”, line 604, in
File “”, line 433, in InferenceAI
File “ml/model.py”, line 14, in init
MemoryError: memory allocation failed, allocating 239091 bytes

239091 bytes are needed but I have 273264 free to use

This is just one of many allocations that are needed. The model object, its state, the ops resolver and tensor arena are all dynamically allocated. By the time you get to this allocation that free memory you saw before is either less than what’s needed or too fragmented to provide a single 239K block.

Got it, is there any way to see the capacity of each allocation in the memory or is it not possible?

A few smaller allocations of 100s of bytes, and about 4K for the ops resolver.

Hi! I solved this problem by seeing how the memory behaved in each part of the code with the following functions:

    print("Free memory: {} bytes".format(gc.mem_free()))
    print("Used memory: {} bytes".format(gc.mem_alloc()))
    print("******* Mem info = " + str( micropython.mem_info(1)))

With this I was able to see how much memory and how it was fragmented. By using the following functions in various parts of my code I was able to clean up unused variables and simplify memory usage.

gc.collect()
gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())

Nice day :slight_smile: