在复现一个 baseline 时,我通过 conda 安装 Pytorch 2.4.1 后在 import torch 时遇到了一个报错:

ImportError: .../torch/lib/libtorch_cpu.so: undefined symbol: iJIT_NotifyEvent

尝试重装了几次环境无果……终于在 google 后找到了解决方案,这里记录一下:

  1. 首先下载官方 ITT 包
conda install -c conda-forge ittapi -y
  1. 写一个包含这些 symbol 的 C 文件
#ifdef __cplusplus
extern "C" {
#endif
 
void iJIT_NotifyEvent(...) {}
void iJIT_NotifyEventW(...) {}
int  iJIT_IsProfilingActive(void) { return 0; }
int  iJIT_GetNewMethodID(void) { return 1; }
int  iJIT_GetNewMethodIDEx(void) { return 1; }
void iJIT_NotifyEventStr(...) {}
void iJIT_NotifyEventEx(...) {}
 
#ifdef __cplusplus
}
#endif
  1. 编译这个文件,我试了一下论坛中的命令会报错,改成了 g++ 编译后正常了
g++ -shared -fPIC -O2 -o "$CONDA_PREFIX/lib/libittnotify.so" "$CONDA_PREFIX/lib/itt_stub.c"
  1. 添加脚本使得激活环境时自动加载这个 stub
mkdir -p $CONDA_PREFIX/etc/conda/activate.d $CONDA_PREFIX/etc/conda/deactivate.d
vim $CONDA_PREFIX/etc/conda/activate.d/itt_preload.sh
export _OLD_LD_PRELOAD="${LD_PRELOAD:-}"
export LD_PRELOAD="$CONDA_PREFIX/lib/libittnotify.so${LD_PRELOAD:+:$LD_PRELOAD}"
vim $CONDA_PREFIX/etc/conda/deactivate.d/itt_preload.sh
export LD_PRELOAD="$_OLD_LD_PRELOAD"
unset _OLD_LD_PRELOADEOF
  1. 重新打开终端并激活环境,python -c "import torch" 正常运行不再报错