Tracker#
什么是 Tracker?#
Tracker 是一个用于跟踪和分析量子程序执行过程的工具包。它可以帮助你记录量子计算任务的执行情况,包括执行时间、参数变化、结果数据等信息,让你更好地理解和优化量子程序。
开始使用 Tracker#
导入必要的模块#
在你的 Python 代码中,导入以下模块:
from qpanda3_runtime import RuntimeService, Tracker
第一个 Tracker 示例#
让我们从一个简单的例子开始,了解如何使用 Tracker 跟踪量子操作:
# 初始化 RuntimeService
service = RuntimeService(auto_track=True, trace_record_file='./trace_record.jsonl')
service.login('your_valid_api_key')
# 使用上下文管理器进行跟踪
with Tracker(service, name="quantum_operation") as t:
# 记录数据
t.record({"operation": "quantum_circuit", "qubit_count": 2})
# 这里可以执行你的量子操作
# ...
# 记录结果
t.record({"result": "success"})
这个例子展示了 Tracker 的基本用法:
初始化 RuntimeService 时启用自动跟踪
使用
with语句创建一个跟踪上下文在上下文中记录数据
Tracker 的三种使用模式#
1. 上下文管理器模式#
这是最常用的模式,使用 with 语句自动管理跟踪的开始和结束:
with Tracker(service, name="my_operation") as t:
t.record({"step": "start", "params": [0.1, 0.2]})
# 执行操作
t.record({"step": "completed", "result": 0.5})
2. 装饰器模式#
使用 @tracker 装饰器自动跟踪函数的执行:
from qpanda3_runtime import tracker
@tracker(service, data={"function_name": "my_function"})
def my_function():
# 函数逻辑
return "result"
# 调用函数时会自动跟踪
result = my_function()
3. 手动跟踪模式#
如果你需要更精细的控制,可以手动管理跟踪过程:
t = Tracker(service)
t.start("manual_operation")
t.record({"step": "start"})
# 执行操作
t.record({"step": "end", "result": "completed"})
t.end({"status": "success"})
记录数据的技巧#
添加标签#
为记录添加标签,方便后续分析:
with Tracker(service, name="quantum_operation") as t:
t.record({"operation": "circuit_execution"}, labels=["quantum", "circuit"])
# 执行操作
t.record({"result": "success"}, labels=["quantum", "result"])
记录执行时间#
记录操作的执行时间:
import time
start_time = time.time()
with Tracker(service, name="time_tracking") as t:
# 执行操作
time.sleep(1)
end_time = time.time()
t.record({"execution_time": end_time - start_time})
嵌套跟踪#
跟踪复杂的执行流程:
with Tracker(service, name="outer_operation") as outer:
outer.record({"step": "start"})
with Tracker(service, name="inner_operation") as inner:
inner.record({"step": "processing"})
# 执行内部操作
inner.record({"step": "completed"})
outer.record({"step": "completed"})
实际应用:错误调试与任务恢复#
1. 跟踪一个真机采样任务(预期会因设备不可用而导致该计算任务失败)#
import os
import json
from pyqpanda3.core import QProg, X, CNOT, measure, CZ, H
from qpanda3_runtime import RuntimeService, Tracker
def track_failed_sampling_task():
# 初始化 RuntimeService
service = RuntimeService(auto_track=True, trace_record_file='./trace_record260330.jsonl')
service.login('your_valid_api_key')
prog = QProg()
prog << X(0)<<CNOT(0,1)<<measure(0,0)<<measure(1,1)
prog2 = QProg()
prog2 << CZ(1, 2) << measure(2, 2)
prog3 = QProg()
prog3 << H(1)<<CNOT(1, 2) << measure(2, 2)
task = service.sample(
circuits=[prog.originir(),prog2.originir(),prog3],
device=service.device('20'),
shots=10
)
res = task.get_result_sync()
print('res:',res)
if __name__ == '__main__':
track_failed_sampling_task()
执行结果(每次运行可能不一样)记录在文件 trace_record260330.jsonl 中:
{"row_id":1,"row_type":"CONTEXT_START","row_parent_id":0,"data":{"node_name":"init runtime service"},"labels":["RUNTIME_SERVICE"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":2,"row_type":"DATA","row_parent_id":1,"data":null,"labels":[],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":3,"row_type":"CONTEXT_START","row_parent_id":1,"data":{"node_name":"login"},"labels":["LOGIN"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":4,"row_type":"DATA","row_parent_id":3,"data":null,"labels":[],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":5,"row_type":"CONTEXT_END","row_parent_id":3,"data":{},"labels":["SUCCESS"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":6,"row_type":"CONTEXT_END","row_parent_id":1,"data":{},"labels":["SUCCESS"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":7,"row_type":"CONTEXT_START","row_parent_id":0,"data":{"node_name":"list devices"},"labels":["QUERY_DEVICE"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":8,"row_type":"DATA","row_parent_id":7,"data":null,"labels":[],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":9,"row_type":"CONTEXT_END","row_parent_id":7,"data":{},"labels":["SUCCESS"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":10,"row_type":"CONTEXT_START","row_parent_id":0,"data":{"node_name":"RuntimeService sample"},"labels":["QTASK","SAMPLE"],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":11,"row_type":"DATA","row_parent_id":10,"data":null,"labels":[],"timestamp":"2026-03-30T14:04:41.274114"}
{"row_id":12,"row_type":"CONTEXT_END","row_parent_id":10,"data":{"error":"{'position': 'runtime_server[qcloud]', 'error_code': 400, 'error_info': 'resource is null', 'error_type': 'InvalidRequest', 'trace_record': ['qcloud_code: 10002', 'obj_str: {\"code\":10002,\"message\":\"resource is null\",\"obj\":null,\"success\":false}'], 'help_info': ''}","task_metadata":{"type":"SampleQTaskInfo","qtask_type":"sample","circuits":{"type":"List[QProgUnionType]","data":["QINIT 2\nCREG 2\nX q[0]\nCNOT q[0],q[1]\nMEASURE q[0],c[0]\nMEASURE q[1],c[1]\n","QINIT 3\nCREG 3\nCZ q[1],q[2]\nMEASURE q[2],c[2]\n","QINIT 3\nCREG 3\nH q[1]\nCNOT q[1],q[2]\nMEASURE q[2],c[2]\n"]},"device":{"type":"QDevice","basic_info":{"channel":"qcloud","chip_id":"20","chipId":20,"chipName":"硅基量子计算机","chipNameEn":"Silicon Quantum Computer","machineType":5,"nameDetail":"\"Silicon Quantum Computer\"","onlineFlag":true},"config_info":{}},"measure_qubits":null,"specified_block":null,"shots":10,"is_amend":true,"is_mapping":true,"is_optimization":true,"point_label":0,"task_describe":""}},"labels":["ERROR"],"timestamp":"2026-03-30T14:04:41.274114"}
2. 查看标签为"ERROR"的跟踪记录#
import os
import json
from pyqpanda3.core import QProg, X, CNOT, measure, CZ, H
from qpanda3_runtime import RuntimeService, Tracker
def retrieve_error_message():
# 加载跟踪记录
trace_file = r'./trace_record260330.jsonl'
#打开文件,知道labels中有'ERROR'行
with open(trace_file, 'r', encoding='utf-8') as file:
for line in file:
# 通过labels中的标签检索对应记录行
if 'ERROR' in line:
#转为json字典
record = json.loads(line)
# 再次检验labels中是否有ERROR标签
if 'ERROR' not in record['labels']:
continue
print(record)
if __name__ == '__main__':
retrieve_error_message()
输出结果:
{
"row_id": 12,
"row_type": "CONTEXT_END",
"row_parent_id": 10,
"data": {
"error": "{'position': 'runtime_server[qcloud]', 'error_code': 400, 'error_info': 'resource is null', 'error_type': 'InvalidRequest', 'trace_record': ['qcloud_code: 10002', 'obj_str: {\"code\":10002,\"message\":\"resource is null\",\"obj\":null,\"success\":false}'], 'help_info': ''}",
"task_metadata": {
"type": "SampleQTaskInfo",
"qtask_type": "sample",
"circuits": {
"type": "List[QProgUnionType]",
"data": [
"QINIT 2\nCREG 2\nX q[0]\nCNOT q[0],q[1]\nMEASURE q[0],c[0]\nMEASURE q[1],c[1]\n",
"QINIT 3\nCREG 3\nCZ q[1],q[2]\nMEASURE q[2],c[2]\n",
"QINIT 3\nCREG 3\nH q[1]\nCNOT q[1],q[2]\nMEASURE q[2],c[2]\n"
]
},
"device": {
"type": "QDevice",
"basic_info": {
"channel": "qcloud",
"chip_id": "20",
"chipId": 20,
"chipName": "硅基量子计算机",
"chipNameEn": "Silicon Quantum Computer",
"machineType": 5,
"nameDetail": "\"Silicon Quantum Computer\"",
"onlineFlag": true
},
"config_info": {}
},
"measure_qubits": null,
"specified_block": null,
"shots": 10,
"is_amend": true,
"is_mapping": true,
"is_optimization": true,
"point_label": 0,
"task_describe": ""
}
},
"labels": ["ERROR"],
"timestamp": "2026-03-30T14:04:41.274114"
}
说明:这是文件 trace_record260330.jsonl 第12行的内容,是一个json字符串。
3. 查看之前程序运行过程中的出错提示#
import os
import json
from pyqpanda3.core import QProg, X, CNOT, measure, CZ, H
from qpanda3_runtime import RuntimeService, Tracker
def retrieve_error_notification():
# 加载跟踪记录
trace_file = r'./trace_record260330.jsonl'
#打开文件,知道labels中有'ERROR'行
with open(trace_file, 'r', encoding='utf-8') as file:
for line in file:
# 通过labels中的标签检索对应记录行
if 'ERROR' in line:
#转为json字典
record = json.loads(line)
# 再次检验labels中是否有ERROR标签
if 'ERROR' not in record['labels']:
continue
error_info = record['data']['error']
# 'error_info': 'resource is null',表示对应的芯片不可用
print('error_info:',error_info)
if __name__ == '__main__':
retrieve_error_notification()
执行结果:
error_info: {'position': 'runtime_server[qcloud]', 'error_code': 400, 'error_info': 'resource is null', 'error_type': 'InvalidRequest', 'trace_record': ['qcloud_code: 10002', 'obj_str: {"code":10002,"message":"resource is null","obj":null,"success":false}'], 'help_info': ''}
说明:
这是文件
trace_record260330.jsonl第12行的内容中的error字段该错误信息由’qcloud’访问通道最初生成,对应的错误码是400,错误信息是resource is null,即对应的芯片不可用
4. 恢复提交这个计算任务时实际传入的接口参数#
# 自动工作功能演示
import os
import json
from pyqpanda3.core import QProg, X, CNOT, measure, CZ, H
from qpanda3_runtime import RuntimeService, Tracker
from qpanda3_runtime.task.qtask_info import SampleQTaskInfo,EstimateQTaskInfo
def reproduce_function_input_parameters_when_task_was_submitted():
# 加载跟踪记录
service = RuntimeService()
service.login('your_valid_api_key')
# 定义检索函数
trace_file = r'./trace_record260330.jsonl'
#打开文件,知道labels中有'ERROR'行
with open(trace_file, 'r', encoding='utf-8') as file:
for line in file:
# 通过labels中的标签检索对应记录行
if 'ERROR' in line:
#转为json字典
record = json.loads(line)
# 再次检验labels中是否有ERROR标签
if 'ERROR' not in record['labels']:
continue
task_metadata = record['data']['task_metadata']
if task_metadata['qtask_type'] == 'sample':
task_info:SampleQTaskInfo = SampleQTaskInfo.from_json_dict(service,task_metadata)
circuits, device, measure_qubits, specified_block, shots, is_amend, is_mapping, is_optimization, point_label, task_describe = task_info.input_for_service_sample()
print('circuits:',circuits)
print('device:',device)
print('measure_qubits:',measure_qubits)
print('specified_block:',specified_block)
print('shots:',shots)
print('is_amend:',is_amend)
print('is_mapping:',is_mapping)
print('is_optimization:',is_optimization)
print('point_label:',point_label)
print('task_describe:',task_describe)
else:
task_info:EstimateQTaskInfo = EstimateQTaskInfo.from_json_dict(service,task_metadata)
circuit_with_observable, device, specified_block, shots, is_amend, is_mapping, is_optimization, task_describe = task_info.input_for_service_estimate()
print('circuit_with_observable:',circuit_with_observable)
print('device:',device)
print('specified_block:',specified_block)
print('shots:',shots)
print('is_amend:',is_amend)
print('is_mapping:',is_mapping)
print('is_optimization:',is_optimization)
print('task_describe:',task_describe)
if __name__ == '__main__':
reproduce_function_input_parameters_when_task_was_submitted()
执行结果:
circuits: [<pyqpanda3.core.core.QProg object at 0x00000263B5265030>, <pyqpanda3.core.core.QProg object at 0x00000263B53133F0>, <pyqpanda3.core.core.QProg object at 0x00000263B5313430>]
device: {'channel': 'qcloud', 'chip_id': '20', 'chipId': 20, 'chipName': '硅基量子计算机', 'chipNameEn': 'Silicon Quantum Computer', 'machineType': 5, 'nameDetail': '"Silicon Quantum Computer"', 'onlineFlag': True}
measure_qubits: None
specified_block: None
shots: 10
is_amend: True
is_mapping: True
is_optimization: True
point_label: 0
task_describe:
5. 更换可用的计算设备重新提交任务#
import os
import json
from pyqpanda3.core import QProg, X, CNOT, measure, CZ, H
from qpanda3_runtime import RuntimeService, Tracker
from qpanda3_runtime.task.qtask_info import SampleQTaskInfo,EstimateQTaskInfo
def change_device_and_resubmit_task():
# 加载跟踪记录
service = RuntimeService(auto_track=True, trace_record_file='./trace_record_4.jsonl')
service.login('your_valid_api_key')
# 定义检索函数
trace_file = r'./trace_record260330.jsonl'
#打开文件,知道labels中有'ERROR'行
with open(trace_file, 'r', encoding='utf-8') as file:
for line in file:
# 通过labels中的标签检索对应记录行
if 'ERROR' in line:
#转为json字典
record = json.loads(line)
# 再次检验labels中是否有ERROR标签
if 'ERROR' not in record['labels']:
continue
task_metadata = record['data']['task_metadata']
if task_metadata['qtask_type'] == 'sample':
task_info:SampleQTaskInfo = SampleQTaskInfo.from_json_dict(service,task_metadata)
circuits, device, measure_qubits, specified_block, shots, is_amend, is_mapping, is_optimization, point_label, task_describe = task_info.input_for_service_sample()
task = service.sample(circuits, service.device('72'), measure_qubits, specified_block, shots, is_amend, is_mapping, is_optimization, point_label)
else:
task_info:EstimateQTaskInfo = EstimateQTaskInfo.from_json_dict(service,task_metadata)
circuit_with_observable, device, specified_block, shots, is_amend, is_mapping, is_optimization, task_describe = task_info.input_for_service_estimate()
task = service.estimate(circuit_with_observable, service.device('72'), specified_block, shots, is_amend, is_mapping, is_optimization)
res = task.get_result_sync()
print('res:',res)
if __name__ == '__main__':
change_device_and_resubmit_task()
执行结果:
res: [[{'key': ['0x3'], 'value': [1]}, {'key': ['0x0', '0x1'], 'value': [0.9, 0.1]}, {'key': ['0x0', '0x1'], 'value': [0.5, 0.5]}]]
说明:更换可用设备后,计算任务提交成功并成功执行得到计算结果。
实际应用:在变分计算任务中使用 Tracker#
变分量子计算(Variational Quantum Computing)是一种重要的量子计算范式,通常涉及参数化量子电路的迭代优化。Tracker 可以很好地跟踪这类复杂任务的执行过程。
使用函数装饰器跟踪函数#
1. 简单装饰器使用:跟踪函数的函数名和返回值#
service = RuntimeService(auto_track=False, trace_record_file='./trace_record_vqtask.jsonl')
service.login('your_valid_api_key')
@tracker(service)
def update_gate_params(old_params):
# 用于模拟参数更新,这里可替换为实际的参数更新逻辑
return old_params * 2
2. 带 TrackerRef 的装饰器使用:在函数内部记录额外数据#
service = RuntimeService(auto_track=False, trace_record_file='./trace_record_vqtask.jsonl')
service.login('your_valid_api_key')
ref = TrackerRef()
@tracker(service, ref)
def check_for_stop_iter(params, count):
# 模拟检测是否该停止迭代
if count >= 2:
ref.record({"count": count}, labels=["ITERATION"])
return True
return False
使用 with 语法跟踪任意代码块#
在变分量子计算任务中,通常需要跟踪整个迭代过程:
service = RuntimeService(auto_track=False, trace_record_file='./trace_record_vqtask.jsonl')
service.login('your_valid_api_key')
with Tracker(service, name="vqsession") as t:
with service.vqsession(
vqcircuit=vqc,
device=service.device('180'),
shots=10,
life_time=300
) as vqs:
while True: # 模拟迭代过程
vqtask = vqs.run_vqtask(params, measure_qubits)
task_id = vqtask.id()
print(f'task_id:{task_id}')
res = vqtask.get_result_sync()
print(f'res:{res}')
t.record({"task_id": task_id, "result": res}, labels=["VQTASK", "RESULT"])
count += 1
if check_for_stop_iter(params, count):
print('Iteration Completed')
break
else:
params = update_gate_params(params)
完整示例:变分量子计算任务跟踪#
下面是一个完整的变分量子计算任务示例,展示了如何综合使用上述技术:
import os
from pyqpanda3.vqcircuit import VQCircuit
from pyqpanda3.core import *
import numpy as np
from qpanda3_runtime import RuntimeService, Tracker, tracker, TrackerRef
# 创建量子电路
vqc = VQCircuit()
vqc.set_Param([2])
vqc << RX(0, vqc.Param([0])) << RY(1, vqc.Param([1]))
# 初始化参数
init_params = np.array([0.14, 1.13])
service = RuntimeService(auto_track=False, trace_record_file='./trace_record_vqtask.jsonl')
service.login('your_valid_api_key')
@tracker(service)
def update_gate_params(old_params):
# 用于模拟参数更新,这里可替换为实际的参数更新逻辑
return old_params * 2
ref = TrackerRef()
@tracker(service, ref)
def check_for_stop_iter(params, count):
# 模拟检测是否该停止迭代
if count >= 2:
ref.record({"count": count}, labels=["ITERATION"])
return True
return False
measure_qubits = [0, 1]
params = init_params
count = 0
with Tracker(service, name="vqsession") as t:
with service.vqsession(
vqcircuit=vqc,
device=service.device('72'),
shots=10,
life_time=300
) as vqs:
while True: # 模拟迭代过程
vqtask = vqs.run_vqtask(params, measure_qubits)
task_id = vqtask.id()
print(f'task_id:{task_id}')
res = vqtask.get_result_sync()
print(f'res:{res}')
t.record({"task_id": task_id, "result": res}, labels=["VQTASK", "RESULT"])
count += 1
if check_for_stop_iter(params, count):
print('Iteration Completed')
break
else:
params = update_gate_params(params)
执行结果和记录分析#
执行上述代码后,跟踪记录被写入到文件 ./trace_record_vqtask.jsonl 中。以下是关键记录的分析:
1. check_for_stop_iter 函数的调用记录#
第一次调用(count=1,返回 False):
{"row_id":4,"row_type":"CONTEXT_START","row_parent_id":1,"data":{"node_name":"check_for_stop_iter"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":5,"row_type":"DATA","row_parent_id":4,"data":null,"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":6,"row_type":"CONTEXT_END","row_parent_id":4,"data":{"result":"False"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
第二次调用(count=2,返回 True):
{"row_id":11,"row_type":"CONTEXT_START","row_parent_id":1,"data":{"node_name":"check_for_stop_iter"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":12,"row_type":"DATA","row_parent_id":11,"data":null,"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":13,"row_type":"DATA","row_parent_id":11,"data":{"count":2},"labels":["ITERATION"],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":14,"row_type":"CONTEXT_END","row_parent_id":11,"data":{"result":"True"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
注意:第二次调用时,通过 ref.record() 记录了 {"count": 2} 数据,并添加了 ["ITERATION"] 标签。
2. update_gate_params 函数的调用记录#
{"row_id":7,"row_type":"CONTEXT_START","row_parent_id":1,"data":{"node_name":"update_gate_params"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":8,"row_type":"DATA","row_parent_id":7,"data":null,"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
{"row_id":9,"row_type":"CONTEXT_END","row_parent_id":7,"data":{"result":"[0.28 2.26]"},"labels":[],"timestamp":"2026-03-30T16:31:17.958228"}
更新后的参数为 [0.28 2.26]。
3. t.record() 的记录#
{"row_id":10,"row_type":"DATA","row_parent_id":1,"data":{"task_id":"E4190A1832FC564D94C7E225CE82C6EB","result":[[{"key":["0x0","0x2","0x3"],"value":[0.1,0.8,0.1]}]]},"labels":["VQTASK","RESULT"],"timestamp":"2026-03-30T16:31:17.958228"}
这条记录包含了任务ID和计算结果,并添加了 ["VQTASK", "RESULT"] 标签。
总结#
通过这个示例,我们可以看到 Tracker 在变分量子计算任务中的强大应用:
装饰器模式可以自动跟踪函数的调用和返回值
TrackerRef允许在装饰函数内部记录额外数据
with 语法可以跟踪复杂的代码块和迭代过程
标签系统方便对记录进行分类和筛选
这些功能使得 Tracker 成为调试和优化变分量子计算任务的强大工具。