#23761·keras

Layer.__delattr__ does not untrack sub-layers

Author: laxmareddypCreated Sep 25, 2026Updated Sep 28, 2026
Labelstype:BugGemma

Describe the bug del layer.attr untracks the attribute when it is a Variable, but not when it is a Layer. The deleted sub-layer's weights stay in weights, trainable_weights and count_params(). Reassigning the attribute (layer.attr = None) leaves it tracked too.

To Reproduce

python
import keras

inputs = keras.Input((4,))
model = keras.Model(inputs, keras.layers.Dense(4)(inputs))
print(len(model.weights), model.count_params())  # 2 20

model.extra_var = keras.Variable(keras.ops.zeros((2,)))
del model.extra_var
print(len(model.weights))  # 2  -> Variable untracked

helper = keras.layers.Dense(3)
helper.build((None, 4))
model.helper = helper
del model.helper
print(len(model.weights), model.count_params())  # 4 35 -> Layer still tracked

Same result on an unbuilt subclassed layer (keras.layers.Dense(4): 0 weights, 2 after the del).

Fails on: tensorflow ❌, jax ❌, torch ❌. Keras 3.15.0 and master (3.16.0, 58db6d6).

Expected behavior After del model.helper, the helper's weights are no longer part of model.weights / count_params(), the same as for a deleted Variable.

Additional context Layer.__delattr__ only has a Variable branch (self._untrack_variable(obj)), so a Layer falls through to object.__delattr__ and stays in _layers. Tracker.untrack() already supports removing it.

Found in KerasHub: Gemma4CausalLM.generate(assistant_model=...) attaches the assistant model for the duration of the call, and it stays attached afterwards (keras-team/keras-hub#3123). KerasHub will work around it with _tracker.untrack() until this is fixed.

One design question before a PR: Tracker stores objects, not attribute names. If the same layer is also held by another attribute or a list (self.a = L; self.b = L), del self.a should probably not untrack L. Deleting a Variable has the same issue today. Should __delattr__ untrack a layer only when no other tracked reference to it remains, or unconditionally, as it does for variables?