Skip to content

Enable mcsolve with jax.grad#2499

Merged
Ericgig merged 2 commits into
qutip:dev.majorfrom
rochisha0:mcsolve
Aug 12, 2024
Merged

Enable mcsolve with jax.grad#2499
Ericgig merged 2 commits into
qutip:dev.majorfrom
rochisha0:mcsolve

Conversation

@rochisha0

Copy link
Copy Markdown
Contributor

Description
As it is already possible to run mcsolve with gpus. The next step in the process to make mcsolve work with grad.

With the changes, I can get

`import qutip_jax as qjax
import qutip as qt
import jax
import jax.numpy as jnp
from functools import partial
qjax.use_jax_backend()

# Define time-dependent functions
@partial(jax.jit, static_argnames=("omega",))
def H_1_coeff(t, omega):
    return 2.0 * jnp.pi * 0.25 * jnp.cos(2.0 * omega * t)

# Hamiltonian components
N = 100
with qt.CoreOptions(default_dtype="jaxdia"):
    a = qt.tensor(qt.qeye(2), qt.destroy(N))
    sm = qt.tensor(qt.destroy(2), qt.qeye(N))
    
H_0 = 2.0 * jnp.pi * a.dag() * a + 2.0 * jnp.pi * sm.dag() * sm
H_1_op = sm * a.dag() + sm.dag() * a
H = [H_0, [H_1_op, qt.coefficient(H_1_coeff, args={"omega": 1.0})]]

# Initial state
state = qt.tensor(qt.fock(2, 0, dtype="jax"), qt.fock(N, 8, dtype="jax"))

# Collapse operators and observables
c_ops = [jnp.sqrt(0.1) * a]
e_ops = [a.dag() * a, sm.dag() * sm]

# Time list
tlist = jnp.linspace(0.0, 100, 2)

# Define the function for which we want to compute the gradient
def f(omega):
    H[1][1] = qt.coefficient(H_1_coeff, args={"omega": omega})
    result = qt.mcsolve(H, state, tlist, c_ops, e_ops, ntraj=10, options={"method": "diffrax"})
    # Return the expectation value of the number operator at tlist[1]
    return result.expect[0][1].real

# Compute the gradient
gradient = jax.grad(f)(1.0)

print("Gradient:", gradient)
`

@coveralls

coveralls commented Jul 23, 2024

Copy link
Copy Markdown

Coverage Status

coverage: 85.123% (-0.008%) from 85.131%
when pulling 13a44af on rochisha0:mcsolve
into 234f26b on qutip:dev.major.

@rochisha0 rochisha0 marked this pull request as ready for review August 6, 2024 16:14
@rochisha0

Copy link
Copy Markdown
Contributor Author

I think this is up for review for grad

@Ericgig Ericgig merged commit b0ec492 into qutip:dev.major Aug 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants