EMI-Group / evox

Distributed GPU-Accelerated Framework for Evolutionary Computation. Comprehensive Library of Evolutionary Algorithms & Benchmark Problems.
BSD 3-Clause "New" or "Revised" License
211 stars 37 forks source link

KeyError: "State has no attribute 'topk_fitness'.This may be due to a mismatch between the state and the module. If you're trying to fit the state to a submodule, please use the `use_state` wrapper." #154

Open zha59 opened 14 hours ago

zha59 commented 14 hours ago

Hello,

I got an error trying to run the sample file, but I don't know how to proceed further, please give some suggestions. The code is below( python: 3.9; evox: 0.9.0):

algorithm = algorithms.PSO(
    lb=jnp.full(shape=(2,), fill_value=-32),
    ub=jnp.full(shape=(2,), fill_value=32),
    pop_size=100,
)
problem = problems.numerical.Ackley()
monitor = monitors.EvalMonitor()
workflow = workflows.StdWorkflow(
    algorithm,
    problem,
    monitors=[monitor],)

key = jax.random.PRNGKey(42)
state = workflow.init(key)
for i in range(100):
    state = workflow.step(state)

print(monitor.get_best_fitness())
print(monitor.get_best_solution())

Error:Traceback (most recent call last): File "f:\Desktop\Task1\GPU_test\main.py", line 22, in print(monitor.get_best_fitness()) TypeError: get_best_fitness() missing 1 required positional argument: 'state'

When I try to pass in the argument “state”, I get a new error: File "D:\soft\miniconda3\envs\py39\lib\site-packages\evox\monitors\eval_monitor.py", line 149, in get_best_fitness return self.opt_direction * state.topk_fitness[..., 0], state File "D:\soft\miniconda3\envs\py39\lib\site-packages\evox\core\state.py", line 241, in getattr raise KeyError( KeyError: "State has no attribute 'topk_fitness'.This may be due to a mismatch between the state and the module. If you're trying to fit the state to a submodule, please use the use_state wrapper."

Thank you for your attention.

BillHuang2001 commented 12 hours ago

The code you’re using is written for an older version of Evox. In version 0.9.0, we made several updates to the API. For compatibility with v0.9.0, the code should be updated as follows:

best_fitness, state = use_state(monitor.get_best_fitness)(state)
best_solution, state = use_state(monitor.get_best_solution)(state)
print(f"Best fitness so far: {best_fitness}")
print(f"Best solution so far: {best_solution}")

Details about use_state can be found in the Quick Start Guide. In brief, as of v0.9.0, the monitor (nested within the workflow) also maintains a state, which is why use_state is required.

Apologies for any confusion. Some examples in the documentation may still reference the previous API version. We will try to fix them ASAP.

zha59 commented 11 hours ago

Thanks