{"record":{"id":"bf5766834128b53f","repo":"keras-team/keras","slug":"cannot-adapt-layer-self-name-after-setting-a-s","errorCode":null,"errorMessage":"Cannot adapt layer '{self.name}' after setting a static vocabulary via `vocabulary` argument or `set_vocabulary()` method.","messagePattern":"Cannot adapt layer '(.+?)' after setting a static vocabulary via `vocabulary` argument or `set_vocabulary\\(\\)` method\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/layers/preprocessing/index_lookup.py","lineNumber":685,"sourceCode":"            or tf.is_tensor(data)\n        ):\n            progbar = Progbar(target=steps, unit_name=\"step\")\n            for i, batch in enumerate(data):\n                if steps is not None and i >= steps:\n                    break\n                self.update_state(batch)\n                progbar.update(i + 1)\n            progbar.update(steps if steps is not None else i + 1, finalize=True)\n        else:\n            data = tf_utils.ensure_tensor(data, dtype=self.vocabulary_dtype)\n            if data.shape.rank == 1:\n                data = tf.expand_dims(data, -1)\n            self.update_state(data)\n        self.finalize_state()\n\n    def update_state(self, data):\n        if self._has_input_vocabulary:\n            raise ValueError(\n                f\"Cannot adapt layer '{self.name}' after setting a static \"\n                \"vocabulary via `vocabulary` argument or \"\n                \"`set_vocabulary()` method.\"\n            )\n\n        data = tf_utils.ensure_tensor(data, dtype=self.vocabulary_dtype)\n        if data.shape.rank == 0:\n            data = tf.expand_dims(data, 0)\n        if data.shape.rank == 1:\n            # Expand dims on axis 0 for tf-idf. A 1-d tensor\n            # is a single document.\n            data = tf.expand_dims(data, 0)\n\n        tokens, counts = self._num_tokens(data)\n        self.token_counts.insert(\n            tokens, counts + self.token_counts.lookup(tokens)\n        )\n","sourceCodeStart":667,"sourceCodeEnd":703,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/layers/preprocessing/index_lookup.py#L667-L703","documentation":"Keras preprocessing layers that support adapt() cannot be adapted after a static vocabulary has been set. update_state(), which adapt() drives, raises this when _has_input_vocabulary is true, because adapting would silently discard or conflict with the vocabulary you supplied explicitly.","triggerScenarios":"Creating a layer with a vocabulary argument (e.g. TextVectorization(vocabulary=my_list)) or calling set_vocabulary(), then later calling layer.adapt(data); also re-adapting a layer restored from a saved model that had a vocabulary.","commonSituations":"Fine-tuning pipelines that load a pretrained vectorizer and try to adapt on new domain data; notebooks that experiment with both static vocab and adapt on the same layer instance.","solutions":["Create a fresh layer without the vocabulary argument and adapt that instead","Compute the union of old and new vocabulary yourself and call set_vocabulary() with the merged list","If the layer came from a loaded model, instantiate a new TextVectorization/IndexLookup before adapting"],"exampleFix":"// before\nlayer = keras.layers.TextVectorization(vocabulary=vocab)\nlayer.adapt(new_data)\n// after\nlayer = keras.layers.TextVectorization(max_tokens=...)\nlayer.adapt(new_data)","handlingStrategy":"validation","validationCode":"if getattr(layer, '_has_input_vocabulary', False):\n    cfg = layer.get_config(); cfg.pop('vocabulary', None)\n    layer = type(layer)(**cfg)\nlayer.adapt(data)","typeGuard":null,"tryCatchPattern":"try:\n    layer.adapt(data)\nexcept ValueError as e:\n    if 'static vocabulary' in str(e):\n        cfg = layer.get_config(); cfg.pop('vocabulary', None)\n        layer = type(layer)(**cfg)\n        layer.adapt(data)\n    else:\n        raise","preventionTips":["Decide up front: static vocabulary XOR adapt, never both","Treat vocabularies in loaded models as static"],"tags":["keras","adapt","vocabulary","state-error"],"backgroundTag":"immutable-state-modification","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}