0

I am using pytorch-minimize library (that can be downloaded via pip install pytorch-minimize), and the following code (which is a simplification of my code) raises an error: "my_callback() takes 1 positional argument but 2 were given"

from torchmin import minimize_constr
import torch
import torch.nn as nn

eps0 = torch.rand((2,3))

def my_callback(xi):
    print("hello world!")
    

res = minimize_constr(
    lambda x : nn.L1Loss()(x.sum(),  x.sum()),
    eps0, 
    max_iter=100,
    callback = my_callback,
    disp=1
)

eps = res.x

So, I debugged it and found that it calls scipy which, in turn, raises the same error for the following simple code:

from scipy.optimize import minimize
import numpy as np

def my_callback(xi):
    print("hello world!")

x0_np = np.random.rand(3)
result = minimize(
        lambda x : x.sum(), x0_np, method='trust-constr', callback = my_callback
    )

Note that both snippets of codes work perfectly when removing the callback optional argument. Also, when removing the method optional argument in the last snippet of code, we also get a perfectly working code.

I think that this is a bit similar, but I can't figure out what should I do.

Dudi Frid
  • 152
  • 7
  • 1
    According to `minimize` docs the callback signature is supposed to be `callback(xk, OptimizeResult state) -> bool` https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html – hpaulj Oct 21 '22 at 08:47
  • @hpaulj Thank you so much, I used different examples in the web which apparently indeed require different signature – Dudi Frid Oct 21 '22 at 09:08
  • You could define `def my_callback(*args):` to accept any number of arguments, and then do a `print(args)` to see what they are. In the long run you need to read the official docs, and not just depend on tutorial examples. – hpaulj Oct 21 '22 at 14:53

0 Answers0