{"record":{"id":"bf591dd24c6145c2","repo":"tensorflow/models","slug":"user-should-set-optimizer-attribute-to-model-insid","errorCode":null,"errorMessage":"User should set optimizer attribute to model inside `model_fn`.","messagePattern":"User should set optimizer attribute to model inside `model_fn`\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"official/legacy/bert/model_training_utils.py","lineNumber":271,"sourceCode":"          ' optimization for the distributed system.')\n\n  if eval_input_fn and eval_steps is None:\n    raise ValueError(\n        '`eval_step` is required when `eval_input_fn ` is not none.')\n  if metric_fn and not callable(metric_fn):\n    raise ValueError(\n        'if `metric_fn` is specified, metric_fn must be a callable.')\n\n  total_training_steps = steps_per_epoch * epochs  # pyrefly: ignore[unsupported-operation]\n  train_iterator = _get_input_iterator(train_input_fn, strategy)\n  eval_loss_metric = tf_keras.metrics.Mean('training_loss', dtype=tf.float32)\n\n  with distribute_utils.get_strategy_scope(strategy):\n    # To correctly place the model weights on accelerators,\n    # model and optimizer should be created in scope.\n    model, sub_model = model_fn()  # pyrefly: ignore[not-callable]\n    if not hasattr(model, 'optimizer'):\n      raise ValueError('User should set optimizer attribute to model '\n                       'inside `model_fn`.')\n    if sub_model_export_name and sub_model is None:\n      raise ValueError('sub_model_export_name is specified as %s, but '\n                       'sub_model is None.' % sub_model_export_name)\n\n    callback_list = tf_keras.callbacks.CallbackList(\n        callbacks=custom_callbacks, model=model)\n\n    optimizer = model.optimizer\n\n    if init_checkpoint:\n      logging.info(\n          'Checkpoint file %s found and restoring from '\n          'initial checkpoint for core model.', init_checkpoint)\n      checkpoint = tf.train.Checkpoint(model=sub_model, encoder=sub_model)\n      checkpoint.read(init_checkpoint).assert_existing_objects_matched()\n      logging.info('Loading from checkpoint file completed')\n","sourceCodeStart":253,"sourceCodeEnd":289,"githubUrl":"https://github.com/tensorflow/models/blob/e006f5f0d534913e49c1f1dae87364039fa607e2/official/legacy/bert/model_training_utils.py#L253-L289","documentation":"Error \"User should set optimizer attribute to model inside `model_fn`.\" thrown in tensorflow/models.","triggerScenarios":"Thrown at official/legacy/bert/model_training_utils.py:271 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"e006f5f0d534913e49c1f1dae87364039fa607e2","analyzedAt":"2026-08-24T14:09:15.576Z","schemaVersion":2},"datasetVersion":"2026-08-24T17:17:21.512Z"}