Change model's attribute during training

I’d like to change my model’s attribute during training.
In order to that, now I’m calling my model as global variable.

For example:

trainer = create_supervised_trainer(~)

def change_attribute(engine):
    global model
    model.my_attribute = new_attribute

Is there more clear way using trainer?
I investigated trainer.__dict__ and trainer.state.__dict__, but there’s no attributes that keeps model.


Trainer defined as

trainer = create_supervised_trainer(~)

is just a configured Engine. Engine, by default, does not store any info on model, optimizer, loss etc.
This can be done if needed like that:

trainer = ...
# trainer.state is not None in recent nightly releases: 0.4.0.dev202005XX
trainer.state.model = model
trainer.state.optimizer = optimizer
# otherwise, in stable v0.3.0, you need to set attributes in a handler attached to `Events.STARTED`

def change_attribute(engine):
    trainer.state.model.my_attribute = new_attribute

About using Engine, see .
About State, please, see the documentation on it : and

A good practice is to use State also as a storage of user data created in update or handler functions. For example, we would like to save new_attribute in the state:

def user_handler_function(engine): 
    engine.state.new_attribute = 12345


1 Like