PySR icon indicating copy to clipboard operation
PySR copied to clipboard

[BUG]: Custom loss function not working in multiprocessing-mode

Open ibengtsson opened this issue 2 years ago • 9 comments

What happened?

I'm having issues running PySR in multiprocessing mode when I use a custom loss function. My loss function looks like:

function eval_loss(tree, dataset::Dataset{T, L}, options::Options, idx)::L where {T, L}

      # Extract data for the given indices
      x = idx === nothing ? dataset.X : view(dataset.X, :, idx)
      y = idx === nothing ? dataset.y : view(dataset.y, idx)

      derivative_with_respect_to = 1
      predicted, gradient, complete = eval_diff_tree_array(tree, x, options, derivative_with_respect_to)
      if !complete
          # encountered NaN/Inf, so return early
          return L(Inf)
      end
      # loss components
      positivity = sum(i -> gradient[i] > 0 ? L(0) : abs2(gradient[i]), eachindex(gradient))
      scatter_loss = sum(i -> abs(log((abs(predicted[i])+1e-20) / (abs(y[i])+1e-20))), eachindex(predicted, y))
      sign_loss = sum(i -> 10 * (sign(predicted[i]) - sign(y[i]))^2, eachindex(predicted, y))
      
      beta = L(1e-3)
      return (scatter_loss + sign_loss + beta*positivity) / length(y)
  end

It works fine when I run it in multithreading mode, but it crashes when trying to use multiprocessing. Grateful for help!

Version

1.0.0

Operating System

macOS

Package Manager

pip

Interface

Script (i.e., python my_script.py)

Relevant log output

Traceback (most recent call last):
  File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/run_sr.py", line 32, in <module>
    main()
  File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/run_sr.py", line 23, in main
    trainer.fit_expression()
  File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/../src/sr_training.py", line 243, in fit_expression
    self.model.fit(
  File "/Users/isakbe/Library/Caches/pypoetry/virtualenvs/il-sr-9TFUWRsR-py3.11/lib/python3.11/site-packages/pysr/sr.py", line 2240, in fit
    self._run(X, y, runtime_params, weights=weights, seed=seed, category=category)
  File "/Users/isakbe/Library/Caches/pypoetry/virtualenvs/il-sr-9TFUWRsR-py3.11/lib/python3.11/site-packages/pysr/sr.py", line 2028, in _run
    out = SymbolicRegression.equation_search(
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/isakbe/.julia/packages/PythonCall/Nr75f/src/JlWrap/any.jl", line 258, in __call__
    return self._jl_callmethod($(pyjl_methodnum(pyjlany_call)), args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
juliacall.JuliaError: On worker 2:
MethodError: no method matching eval_loss(::Node{Float32}, ::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, ::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5})

Closest candidates are:
  eval_loss(::Any, ::Dataset{T, L, AX} where AX<:AbstractMatrix{T}, ::Options, !Matched::Any) where {T, L}
   @ Main none:1
Stacktrace:
 [1] #9
   @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/macros.jl:83
 [2] #invokelatest#2
   @ ./essentials.jl:892 [inlined]
 [3] invokelatest
   @ ./essentials.jl:889
 [4] #107
   @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:283
 [5] run_work_thunk
   @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:70
 [6] run_work_thunk
   @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:79
 [7] #100
   @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:88
Stacktrace:
  [1] remotecall_fetch(f::Function, w::Distributed.Worker, args::Distributed.RRID; kwargs::@Kwargs{})
    @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:465
  [2] remotecall_fetch(f::Function, w::Distributed.Worker, args::Distributed.RRID)
    @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:454
  [3] remotecall_fetch
    @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:492 [inlined]
  [4] call_on_owner
    @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:565 [inlined]
  [5] fetch(r::Distributed.Future)
    @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:619
  [6] test_function_on_workers(example_inputs::Tuple{Node{Float32}, Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}}, op::Function, procs::Vector{Int64})
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:206
  [7] move_functions_to_workers(procs::Vector{Int64}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, dataset::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, verbosity::Int64)
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:180
  [8] configure_workers(; procs::Nothing, numprocs::Int64, addprocs_function::typeof(Distributed.addprocs), options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, project_path::String, file::String, exeflags::Cmd, verbosity::Int64, example_dataset::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, runtests::Bool)
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:349
  [9] _create_workers(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}, ropt::SymbolicRegression.SearchUtilsModule.RuntimeOptions{:multiprocessing, 1, true, SRLogger{TensorBoardLogger.TBLogger{String, IOStream}}}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5})
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:597
 [10] _equation_search(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}, ropt::SymbolicRegression.SearchUtilsModule.RuntimeOptions{:multiprocessing, 1, true, SRLogger{TensorBoardLogger.TBLogger{String, IOStream}}}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, saved_state::Nothing)
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:532
 [11] equation_search(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}; options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, saved_state::Nothing, runtime_options::Nothing, runtime_options_kws::@Kwargs{niterations::Int64, parallelism::String, numprocs::Int64, procs::Nothing, addprocs_function::Nothing, heap_size_hint_in_bytes::Nothing, runtests::Bool, return_state::Bool, run_id::String, verbosity::Int64, logger::SRLogger{TensorBoardLogger.TBLogger{String, IOStream}}, progress::Bool, v_dim_out::Val{1}})
    @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:525
 [12] equation_search
    @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:506 [inlined]
 [13] #equation_search#20
    @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:476 [inlined]
 [14] equation_search
    @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:422 [inlined]
 [15] #equation_search#21
    @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:499 [inlined]
 [16] pyjlany_call(self::typeof(equation_search), args_::Py, kwargs_::Py)
    @ PythonCall.JlWrap ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/any.jl:40
 [17] _pyjl_callmethod(f::Any, self_::Ptr{PythonCall.C.PyObject}, args_::Ptr{PythonCall.C.PyObject}, nargs::Int64)
    @ PythonCall.JlWrap ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/base.jl:73
 [18] _pyjl_callmethod(o::Ptr{PythonCall.C.PyObject}, args::Ptr{PythonCall.C.PyObject})
    @ PythonCall.JlWrap.Cjl ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/C.jl:63

Extra Info

No response

ibengtsson avatar Dec 02 '24 12:12 ibengtsson

Hm. What happens if you give it a different name? Like my_eval_loss?

MilesCranmer avatar Dec 02 '24 12:12 MilesCranmer

Same issue if I change the name to my_eval_loss unfortunately.

ibengtsson avatar Dec 02 '24 12:12 ibengtsson

Does it work with batching=false and no idx argument?

Can you also try modifying the signature like

function eval_loss(tree, dataset::Dataset{T, L}, options::Options, idx=nothing)::L where {T, L}

Note the idx=nothing.

The specific error complains there is no method for ::Node, ::Dataset, ::Options, which is true here. But I'm confused that it worked in normal multithreading mode but not on workers.

MilesCranmer avatar Dec 02 '24 12:12 MilesCranmer

Also can you share the error traceback when you name it my_eval_loss?

MilesCranmer avatar Dec 02 '24 12:12 MilesCranmer

So it seems that setting idx=nothing works! It also works when you set batching=False and don't use a idx argument.

For completeness, here's my output for naming the function my_eval_loss.

Output
Traceback (most recent call last): File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/run_sr.py", line 32, in main() File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/run_sr.py", line 23, in main trainer.fit_expression() File "/Users/isakbe/Dev/modelling/il-sr/il_sr/scripts/../src/sr_training.py", line 245, in fit_expression self.model.fit( File "/Users/isakbe/Library/Caches/pypoetry/virtualenvs/il-sr-9TFUWRsR-py3.11/lib/python3.11/site-packages/pysr/sr.py", line 2240, in fit self._run(X, y, runtime_params, weights=weights, seed=seed, category=category) File "/Users/isakbe/Library/Caches/pypoetry/virtualenvs/il-sr-9TFUWRsR-py3.11/lib/python3.11/site-packages/pysr/sr.py", line 2028, in _run out = SymbolicRegression.equation_search( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/isakbe/.julia/packages/PythonCall/Nr75f/src/JlWrap/any.jl", line 258, in __call__ return self._jl_callmethod($(pyjl_methodnum(pyjlany_call)), args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ juliacall.JuliaError: On worker 2: MethodError: no method matching my_eval_loss(::Node{Float32}, ::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, ::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5})

Closest candidates are: my_eval_loss(::Any, ::Dataset{T, L, AX} where AX<:AbstractMatrix{T}, ::Options, !Matched::Any) where {T, L} @ Main none:1

Stacktrace: [1] #9 @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/macros.jl:83 [2] #invokelatest#2 @ ./essentials.jl:892 [inlined] [3] invokelatest @ ./essentials.jl:889 [4] #107 @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:283 [5] run_work_thunk @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:70 [6] run_work_thunk @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:79 [7] #100 @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/process_messages.jl:88 Stacktrace: [1] remotecall_fetch(f::Function, w::Distributed.Worker, args::Distributed.RRID; kwargs::@Kwargs{}) @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:465 [2] remotecall_fetch(f::Function, w::Distributed.Worker, args::Distributed.RRID) @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:454 [3] remotecall_fetch @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:492 [inlined] [4] call_on_owner @ /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:565 [inlined] [5] fetch(r::Distributed.Future) @ Distributed /opt/homebrew/Cellar/julia/1.10.4/share/julia/stdlib/v1.10/Distributed/src/remotecall.jl:619 [6] test_function_on_workers(example_inputs::Tuple{Node{Float32}, Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}}, op::Function, procs::Vector{Int64}) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:206 [7] move_functions_to_workers(procs::Vector{Int64}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, dataset::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, verbosity::Int64) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:180 [8] configure_workers(; procs::Nothing, numprocs::Int64, addprocs_function::typeof(Distributed.addprocs), options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, project_path::String, file::String, exeflags::Cmd, verbosity::Int64, example_dataset::Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}, runtests::Bool) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/Configure.jl:349 [9] create_workers(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}, ropt::SymbolicRegression.SearchUtilsModule.RuntimeOptions{:multiprocessing, 1, true, Nothing}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:597 [10] equation_search(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}, ropt::SymbolicRegression.SearchUtilsModule.RuntimeOptions{:multiprocessing, 1, true, Nothing}, options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, saved_state::Nothing) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:532 [11] equation_search(datasets::Vector{Dataset{Float32, Float32, Matrix{Float32}, Vector{Float32}, Nothing, @NamedTuple{}, Nothing, Nothing, Nothing, Nothing}}; options::Options{SymbolicRegression.CoreModule.OptionsStructModule.ComplexityMapping{Int64, Int64}, DynamicExpressions.OperatorEnumModule.OperatorEnum, Node, Expression, @NamedTuple{}, MutationWeights, false, true, nothing, Nothing, 5}, saved_state::Nothing, runtime_options::Nothing, runtime_options_kws::@Kwargs{niterations::Int64, parallelism::String, numprocs::Int64, procs::Nothing, addprocs_function::Nothing, heap_size_hint_in_bytes::Nothing, runtests::Bool, return_state::Bool, run_id::String, verbosity::Int64, logger::Nothing, progress::Bool, v_dim_out::Val{1}}) @ SymbolicRegression ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:525 [12] equation_search @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:506 [inlined] [13] #equation_search#20 @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:476 [inlined] [14] equation_search @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:422 [inlined] [15] #equation_search#21 @ ~/.julia/packages/SymbolicRegression/44X04/src/SymbolicRegression.jl:499 [inlined] [16] pyjlany_call(self::typeof(equation_search), args::Py, kwargs::Py) @ PythonCall.JlWrap ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/any.jl:40 [17] pyjl_callmethod(f::Any, self::Ptr{PythonCall.C.PyObject}, args_::Ptr{PythonCall.C.PyObject}, nargs::Int64) @ PythonCall.JlWrap ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/base.jl:73 [18] _pyjl_callmethod(o::Ptr{PythonCall.C.PyObject}, args::Ptr{PythonCall.C.PyObject}) @ PythonCall.JlWrap.Cjl ~/.julia/packages/PythonCall/Nr75f/src/JlWrap/C.jl:63

Thank you so much for the quick help!

ibengtsson avatar Dec 02 '24 13:12 ibengtsson

Cool! Thanks. And just to check, what happens in multithreading mode when you use the original function string, but rename it to my_eval_loss?

I think it's some unfortunate combination of it being a real error (not setting idx=nothing in a custom loss function) but multithreading mode it was colliding with the internal function of the same name (also eval_loss). Which is why it only seemed to hit this error in multiprocessing only.

I guess on my side I should add an error check for the function name not being equal to eval_loss, and also helpful error messages if idx is not given a default of nothing.

MilesCranmer avatar Dec 02 '24 13:12 MilesCranmer

Btw, do you remember if there was any documentation which incorrectly suggested idx) instead of idx=nothing) in a custom loss function? I want to update that too.

MilesCranmer avatar Dec 02 '24 13:12 MilesCranmer

If I rename the function string and use multithreading it actually works too. Not really sure why...

Hmm, regarding documentation I'm not sure! I have limited experience with Julia so I pieced together quite many different discussion replies to make it (sort of...) work. I think it comes down to me not really knowing Julia and that the documentation only shows how to write a custom loss function for the case of no batching!

ibengtsson avatar Dec 02 '24 13:12 ibengtsson

Cool. Thanks for helping get more debug info for this!

MilesCranmer avatar Dec 02 '24 13:12 MilesCranmer