Hi, I'm currently building a tool for an EU research project and I came across a bug with name_scope_stack.

I'm getting two different errors when calling predict or when calling load_model,

...
.../.venv/lib/python3.12/site-packages/keras/src/backend/common/name_scope.py", line 61, in __exit__
    name_scope_stack.pop()
    ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'pop'

or

 .../.venv/lib/python3.12/site-packages/keras/src/backend/common/name_scope.py", line 61, in __exit__
    name_scope_stack.pop()
IndexError: pop from empty list

If I manually add a guard clause to handle the case of name_scope_stack being None or name_scope_stack being empty, my code executes fine. Any chance you could add those guards, so we can move forward with our project?

Thanks in advance.

Comment From: Abhinavexists

Hi @JimiC

What i understood is that the __exit__() implementation in the name_scope.py always assume that global_state.get_global_attribute("name_scope_stack") always returns a valid list (i.e. list is always non-empty)

when keras run multiple thread it can lead to thread_local global state being unset leading to none

i suggest a simple fix which just checks if name_scope_stack is empty or dosen't exist

Comment From: JimiC

Hi @JimiC

What i understood is that the __exit__() implementation in the name_scope.py always assume that global_state.get_global_attribute("name_scope_stack") always returns a valid list (i.e. list is always non-empty)

when keras run multiple thread it can lead to thread_local global state being unset leading to none

i suggest a simple fix which just checks if name_scope_stack is empty or dosen't exist

You are right. This happens on a Streamlit app that's multi threaded.

Comment From: Abhinavexists

@JimiC I have made a minimal change that now handled this issue, hope this works for you.

Let's wait for maintainer review till then

Comment From: JimiC

@Abhinavexists I reviewed the change. It's exactly what I have done manually. 👍