Hello! If applicable, put your complete code example down below. Make sure that your code:
- is 100% self-contained — someone can copy-paste exactly what is here and run it to
reproduce the behaviour you are observing - includes comments
Hi, I am trying to implement the code StateLearning.ipynb available at (quantum-learning/notebooks/StateLearning.ipynb at master · XanaduAI/quantum-learning · GitHub
) using Jupyter notebook and Tensorflow 2. However, it does not create an unevaluated tensor as is required for optimization using Adam. When I try using a @tf.function wrapper, it gives the error
TypeError: outer_factory..inner_factory..tf__func() missing 1 required keyword-only argument: ‘__wrapper’
Here is my code.
import tensorflow as tf
import strawberryfields as sf
from strawberryfields import Program, Engine
from strawberryfields.ops import Rgate, Sgate, Dgate, Vgate, Kgate
# Hyperparameters
cutoff_dim = 6
depth = 8
reps = 5000
passive_sd = 0.1
active_sd = 0.001
# Initialize trainable parameters
params = [
tf.Variable(tf.random.normal(shape=[depth], stddev=active_sd), name="r1"),
tf.Variable(tf.random.normal(shape=[depth], stddev=active_sd), name="sq_r"),
tf.Variable(tf.random.normal(shape=[depth], stddev=passive_sd), name="sq_phi"),
tf.Variable(tf.random.normal(shape=[depth], stddev=passive_sd), name="r2"),
tf.Variable(tf.random.normal(shape=[depth], stddev=active_sd), name="d_r"),
tf.Variable(tf.random.normal(shape=[depth], stddev=passive_sd), name="d_phi"),
tf.Variable(tf.random.normal(shape=[depth], stddev=active_sd), name="kappa"),
]
# Define layer function
def layer(i, q):
Rgate(params[0][i]) | q # r1
Sgate(params[1][i], params[2][i]) | q # sq_r, sq_phi
Rgate(params[3][i]) | q # r2
Dgate(params[4][i], params[5][i]) | q # d_r, d_phi
Kgate(params[6][i]) | q # kappa
return q
# Start SF program to return unevaluated tensor
prog = sf.Program(1)
# Apply circuit of layers with corresponding depth
with prog.context as q:
for k in range(depth):
layer(k, q)
# Run engine
@tf.autograph.experimental.do_not_convert
@tf.function
def create_unevaluated_tensor():
eng = Engine('tf', backend_options={"cutoff_dim": cutoff_dim})
state = eng.run(prog, shots=1)
ket = state.state.ket()
return ket
ketket = create_unevaluated_tensor()
ket_var = tf.Variable(ketket, trainable=True)
ket_var
Without the @tf.function wrapper, ket_var is no longer unevaluated. But using @tf.function gives the following error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 17
15 ket = state.state.ket()
16 return ket
---> 17 ketket = create_unevaluated_tensor()
18 ket_var = tf.Variable(ketket, trainable=True)
19 ket_var
File /opt/anaconda3/lib/python3.12/site-packages/tensorflow/python/autograph/impl/api.py:643, in do_not_convert.<locals>.wrapper(*args, **kwargs)
641 def wrapper(*args, **kwargs):
642 with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED):
--> 643 return func(*args, **kwargs)
File /opt/anaconda3/lib/python3.12/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
151 except Exception as e:
152 filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153 raise e.with_traceback(filtered_tb) from None
154 finally:
155 del filtered_tb
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_filei7hm8__h.py:11, in outer_factory.<locals>.inner_factory.<locals>.tf__create_unevaluated_tensor()
9 retval_ = ag__.UndefinedReturnValue()
10 eng = ag__.converted_call(ag__.ld(Engine), ('tf',), dict(backend_options={'cutoff_dim': ag__.ld(cutoff_dim)}), fscope)
---> 11 state = ag__.converted_call(ag__.ld(eng).run, (ag__.ld(prog),), dict(shots=1), fscope)
12 ket = ag__.converted_call(ag__.ld(state).state.ket, (), None, fscope)
13 try:
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileg6ay94uv.py:146, in outer_factory.<locals>.inner_factory.<locals>.tf__run(self, program, args, compile_options, **kwargs)
144 try:
145 do_return = True
--> 146 retval_ = ag__.converted_call(ag__.converted_call(ag__.ld(super), (), None, fscope)._run, (ag__.ld(program_lst),), dict(args=ag__.ld(args), compile_options=ag__.ld(compile_options), **ag__.ld(eng_run_options)), fscope)
147 except:
148 do_return = False
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileymwh4g5u.py:175, in outer_factory.<locals>.inner_factory.<locals>.tf___run(self, program, args, compile_options, **kwargs)
173 received_rolled = ag__.Undefined('received_rolled')
174 _ = ag__.Undefined('_')
--> 175 ag__.for_stmt(ag__.ld(program), None, loop_body_1, get_state_8, set_state_8, ('modes', 'self.samples', 'self.samples_dict', 'prev'), {'iterate_names': 'p'})
176 ancillae_samples = None
178 def get_state_9():
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileymwh4g5u.py:93, in outer_factory.<locals>.inner_factory.<locals>.tf___run.<locals>.loop_body_1(itr_1)
91 nonlocal p
92 pass
---> 93 ag__.if_stmt(ag__.or_(lambda: 'compiler' in ag__.ld(compile_options), lambda: 'device' in ag__.ld(compile_options)), if_body_2, else_body_2, get_state_2, set_state_2, ('p',), 1)
94 received_rolled = False
96 def get_state_3():
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileymwh4g5u.py:88, in outer_factory.<locals>.inner_factory.<locals>.tf___run.<locals>.loop_body_1.<locals>.if_body_2()
86 def if_body_2():
87 nonlocal p
---> 88 p = ag__.converted_call(ag__.ld(p).compile, (), dict(**ag__.ld(compile_options)), fscope)
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileouep441c.py:210, in outer_factory.<locals>.inner_factory.<locals>.tf__compile(self, device, compiler, **kwargs)
208 DAG = ag__.Undefined('DAG')
209 temp = ag__.Undefined('temp')
--> 210 ag__.if_stmt(ag__.converted_call(ag__.ld(kwargs).get, ('warn_connected', True), None, fscope), if_body_8, else_body_8, get_state_8, set_state_8, (), 0)
212 def get_state_9():
213 return (seq,)
File /var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/__autograph_generated_fileouep441c.py:191, in outer_factory.<locals>.inner_factory.<locals>.tf__compile.<locals>.if_body_8()
189 def if_body_8():
190 DAG = ag__.converted_call(ag__.ld(pu).list_to_DAG, (ag__.ld(seq),), None, fscope)
--> 191 temp = ag__.converted_call(ag__.ld(nx).algorithms.components.number_weakly_connected_components, (ag__.ld(DAG),), None, fscope)
193 def get_state_7():
194 return ()
TypeError: in user code:
File "/var/folders/z9/3chwqgjd5db7cllcjpq_vmtw0000gn/T/ipykernel_3630/4192412521.py", line 14, in create_unevaluated_tensor *
state = eng.run(prog, shots=1)
File "/opt/anaconda3/lib/python3.12/site-packages/strawberryfields/engine.py", line 571, in run *
program_lst, args=args, compile_options=compile_options, **eng_run_options
File "/opt/anaconda3/lib/python3.12/site-packages/strawberryfields/engine.py", line 276, in _run *
p = p.compile(**compile_options)
File "/opt/anaconda3/lib/python3.12/site-packages/strawberryfields/program.py", line 730, in compile *
temp = nx.algorithms.components.number_weakly_connected_components(DAG)
TypeError: outer_factory.<locals>.inner_factory.<locals>.tf__func() missing 1 required keyword-only argument: '__wrapper'
I am using StrawberryFields 0.23.0 and TensorFlow 2.17.0
Any help will be hugely appreciated. Thank you.