You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用multiprocess pool.imap时出现NameError:'run_experiment'未定义求助

解决Multiprocessing中NameError: 'run_experiment'未定义的问题

问题原因

  1. 缩进错误:你的代码中run_experiment、run_wrapper及后续代码的缩进混乱,导致函数未被定义在模块级别,子进程启动时无法识别这些函数。
  2. Windows多进程机制限制:Windows环境下multiprocessing会通过重新导入主模块创建子进程,因此所有需要被子进程调用的函数必须定义在if __name__ == '__main__'代码块之外,且处于模块顶层。

修复步骤

1. 统一代码缩进

确保所有函数、全局变量的缩进一致,if __name__ == '__main__'作为程序入口单独缩进。

2. 调整代码结构

将run_experiment、run_wrapper移至if __name__ == '__main__'代码块之前,保证子进程能正确导入这些函数。

修正后的代码示例

import multiprocessing as mp
# 导入所需依赖模块:hf, qt, numpy等

def run_experiment(args, order):
    # Make a data containers
    QbData = QubitExperiment()
    
    # Resample the control
    resampled_args = hf.resample_u_dft(args, n_discretization)
    control = hf.u_idft(ts, resampled_args)
    
    # Run the experiment
    psi0 = qt.basis(2,1)
    H = [H0, [H1, control]]
    result = qt.mesolve(H, psi0, ts, [], measure_list)
    X = np.array(result.expect)
            
    # Collect strobe data
    Y = fshape(X[:,::i_strobe],  n_strobes)
    Ty = ts[::i_period]

    # We only have monotone controls so we just repeat the pulse
    control_library = [hf.make_control_library(args['u_hat'], order)]*n_periods
    Uy = np.hstack(control_library)
    
    # Save data
    QbData.save(X, Y, Uy, Ty, resampled_args)
    
    return QbData

# Library order
order = 3

# Run multi-process experiments
def run_wrapper(arg):
    return run_experiment(arg, order=order)

# Protect the entry point
if __name__ == '__main__':
    mp.freeze_support()
    with mp.Pool(2) as p:
        r = list(p.imap(run_wrapper, control_list))
    QbData = join_qubit_experiments(r)

额外注意事项

  • 确保n_discretization、ts、H0、H1等全局变量在模块顶层定义,或作为参数传递给run_experiment,避免子进程无法访问。
  • 确认所有依赖模块(如hf、qt)在子进程环境中能正常导入,防止出现其他导入错误。

内容的提问来源于stack exchange,提问作者Iman Garsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:24:49