cvxpygen icon indicating copy to clipboard operation
cvxpygen copied to clipboard

Replace `pickle` with `dill` for serialization

Open langestefan opened this issue 5 months ago • 0 comments

This replaces the python pickle module with the more robust dill (see dill), which is used by many projects that require serialization.

This will fix the serialization part of issue #72 and prevent more serialization issues in the future.

Models of this form will no longer fail to serialize:

import cvxpy as cp
import numpy as np
from cvxpygen import cpg
import dill as pickle

# setup model
m, n = 3, 2
x = cp.Variable(n, name="x")
A = cp.Parameter((m, n), name="A", sparsity=((0, 0, 1), (0, 1, 1)))
b = cp.Parameter(m, name="b")
d = cp.Parameter(m, name="d")
bd = cp.CallbackParam(
    shape=(m,), callback=lambda: d.value * b.value, name="bd"
)
problem = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - bd)), [x >= 0])

# set values for parameters
np.random.seed(0)
A.value = np.zeros((m, n))
A.value[0, 0] = np.random.randn()
A.value[0, 1] = np.random.randn()
A.value[1, 1] = np.random.randn()
b.value = np.random.randn(m)
d.value = np.random.randn(m)

# solve
problem.solve()
obj = problem.value
print("Objective value:", obj)

# code gen
cpg.generate_code(problem, code_dir="nonneg_LS", solver="SCS")

from nonneg_LS.cpg_solver import cpg_solve

with open('nonneg_LS/problem.pickle', 'rb') as f:
    prob = pickle.load(f)

prob.register_solve('CPG', cpg_solve)

obj = prob.solve(method='CPG')
print("Objective value:", obj)

langestefan avatar Jul 13 '25 17:07 langestefan