Insightfaceをpython3.13でプレビルドを作成してインストールする話@Paperspace
GJLさんの記事でもありますが、Insightfaceをpython3.13でプレビルドを作成すると、上のリポジトリのthird partyの所にある
insightface/python-package/insightface/thirdparty/face3d/mesh/cython at master · deepinsight/insightface
という部分でpython 3.13に合わないため上手くビルド出来ない問題があります。

この中で「mesh_core_cython.cpp」を解析してもらうと、Cython 0.29.32という古いバージョンで生成されたものと分かりました。
Pythonはバージョン3.11以降、内部のC言語APIに大きな変更を加えており、古いCythonが生成したコードは新しいPythonではコンパイルエラーを引き起こすため、この問題が起きているようです。
<解決策:>
この古いファイルを削除し、最新のCythonをインストールした環境でビルドプロセスを実行することで、Python 3.13に対応した新しいmesh_core_cython.cppを自動生成させる。
PaperspaceのA4000の自作コンテナでプレビルドを作成してみました。
①環境構築コマンド
# -----------------------------------------------------------------
# ■ ステップ1: 依存ライブラリのインストールとツールの最新化
# -----------------------------------------------------------------
# C++コンパイラやcmakeなど、ビルドに必要な基本ツールをインストール
!apt-get update && apt-get install -y build-essential cmake libgl1-mesa-glx
# onnxruntime-gpuなどのPython依存関係をインストール
!pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
!pip install numpy tqdm requests matplotlib Pillow scipy scikit-learn scikit-image easydict albumentations prettytable opencv-python-headless
# ★★★ 最重要: Cythonを最新バージョンにアップグレード ★★★
# これにより、Python 3.13対応のC++コードが自動生成されるようになります。
!pip install --upgrade cython②リポジトリのクローンなどのコマンドとビルドコマンド
# -----------------------------------------------------------------
# ■ ステップ2: リポジトリのクローンとサブモジュールのセットアップ
# -----------------------------------------------------------------
# 作業ディレクトリに移動
%cd /notebooks/
# 既存のディレクトリが残っている場合は削除
!rm -rf insightface_build
# ビルド用のディレクトリを作成して移動
!mkdir insightface_build
%cd insightface_build
# Gitリポジトリをクローン
!git clone https://github.com/deepinsight/insightface.git
%cd insightface
# サブモジュールを初期化・更新
!git submodule update --init --recursive
# -----------------------------------------------------------------
# ■ ステップ3: ビルドの実行
# -----------------------------------------------------------------
# setup.pyが存在するディレクトリへ移動
%cd python-package
# ★★★ 重要: 古いビルド成果物やCythonが生成した古いC++ファイルを削除 ★★★
!rm -rf build dist *.so insightface/thirdparty/face3d/mesh/cython/mesh_core_cython.cpp
# ビルドコマンドの実行
# 1. build_ext: 最新のCythonが.pyxから.cppを自動生成し、コンパイルします。
# 2. bdist_wheel: インストール用の.whlパッケージを作成します。
!python setup.py build_ext --inplace
!python setup.py bdist_wheel
# distディレクトリにwheelファイルが生成されていることを確認
!ls -l dist/④インストールコマンド
# -----------------------------------------------------------------
# ■ ステップ4: ビルドしたパッケージのインストール
# -----------------------------------------------------------------
# distディレクトリに生成されたwheelファイルをpipでインストールします。
# アスタリスク(*)を使うことで、バージョン番号を問わずファイルにマッチさせます。
!pip install /notebooks/insightface_build/insightface/python-package/dist/insightface-0.7.3-cp313-cp313-linux_x86_64.whl
# -----------------------------------------------------------------
# ✓ これでインストールは完了です!
# -----------------------------------------------------------------実際にインストールした状態で、insightfaceの機能について確認しました。
予め「onnxruntime-gpu」をインストールしておく必要があります。
※onnxruntimeが入っているとcpuが優先的に使用されるため、削除したコマンドです。
# ステップ1: 競合しているパッケージを完全にアンインストール
!pip uninstall -y onnxruntime onnxruntime-gpu
# ステップ2: GPU版のみをクリーンインストール
!pip install onnxruntime-gpu==1.22.0 --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/Insightfaceの機能確認コマンド
import numpy as np
import cv2
import insightface
from insightface.app import FaceAnalysis
# -----------------------------------------------------------------
# テスト1: insightfaceライブラリの基本的なインポートと初期化
# -----------------------------------------------------------------
print("🧪 テスト1: ライブラリの基本的な動作確認を開始します...")
try:
# バージョン情報を表示して、インストールされていることを確認
print(f"✅ insightfaceのバージョン: {insightface.__version__}")
# FaceAnalysisクラスを初期化(モデルのダウンロードが走る場合があります)
app = FaceAnalysis(providers=['CUDAExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))
print("✅ FaceAnalysisの初期化に成功しました。ONNXモデルも正常に読み込めています。")
except Exception as e:
print(f"❌ テスト1でエラーが発生しました: {e}")
print(" 基本的な初期化に失敗しました。インストール自体がうまくいっていない可能性があります。")
print("\n" + "="*50 + "\n")
# -----------------------------------------------------------------
# テスト2: 問題があったC++/Cythonモジュールの直接的な動作確認
# -----------------------------------------------------------------
print("🧪 テスト2: 今回ビルドした3Dメッシュ関連モジュールの動作確認を開始します...")
try:
# この`render`モジュールが、内部でコンパイルした`mesh_core_cython.so`を呼び出します。
from insightface.thirdparty.face3d.mesh import render
print("✅ コンパイルされたCythonモジュールを含む`render`のインポートに成功しました。")
# ダミーデータを作成して、実際にレンダリング関数を呼び出してみる
# これがエラーなく実行できれば、C++拡張機能は完全に動作しています。
print(" ダミーデータでレンダリング関数を実行します...")
dummy_vertices = np.random.rand(10, 3).astype(np.float32) * 256
dummy_triangles = np.array([[0, 1, 2], [3, 4, 5]], dtype=np.int32)
dummy_colors = np.random.rand(10, 3).astype(np.float32)
# レンダリング関数を実行
rendered_image = render.render_colors(dummy_vertices, dummy_triangles, dummy_colors, 256, 256)
# 結果の形状を表示
print(f"🖼️ レンダリング関数が正常に実行されました!")
print(f" 生成された画像の形状: {rendered_image.shape} (高さ, 幅, チャンネル)")
print("✅ すべてのテストが正常に完了しました!ビルドは成功です。")
except Exception as e:
print(f"❌ テスト2でエラーが発生しました: {e}")
print(" コンパイルされたC++/Cythonモジュールの呼び出しで問題が発生しました。")これを実行すると以下のようになり、課題であった部分が解消されたものになりました。
🧪 テスト1: ライブラリの基本的な動作確認を開始します... ✅ insightfaceのバージョン: 0.7.3 Applied providers: ['CUDAExecutionProvider', 'CPUExecutionProvider'], with options: {'CPUExecutionProvider': {}, 'CUDAExecutionProvider': {'sdpa_kernel': '0', 'use_tf32': '1', 'fuse_conv_bias': '0', 'prefer_nhwc': '0', 'tunable_op_max_tuning_duration_ms': '0', 'enable_skip_layer_norm_strict_mode': '0', 'tunable_op_tuning_enable': '0', 'tunable_op_enable': '0', 'use_ep_level_unified_stream': '0', 'device_id': '0', 'has_user_compute_stream': '0', 'gpu_external_empty_cache': '0', 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'cudnn_conv1d_pad_to_nc1d': '0', 'gpu_mem_limit': '18446744073709551615', 'gpu_external_alloc': '0', 'gpu_external_free': '0', 'arena_extend_strategy': 'kNextPowerOfTwo', 'do_copy_in_default_stream': '1', 'enable_cuda_graph': '0', 'user_compute_stream': '0', 'cudnn_conv_use_max_workspace': '1'}} find model: /root/.insightface/models/buffalo_l/1k3d68.onnx landmark_3d_68 ['None', 3, 192, 192] 0.0 1.0 Applied providers: ['CUDAExecutionProvider', 'CPUExecutionProvider'], with options: {'CPUExecutionProvider': {}, 'CUDAExecutionProvider': {'sdpa_kernel': '0', 'use_tf32': '1', 'fuse_conv_bias': '0', 'prefer_nhwc': '0', 'tunable_op_max_tuning_duration_ms': '0', 'enable_skip_layer_norm_strict_mode': '0', 'tunable_op_tuning_enable': '0', 'tunable_op_enable': '0', 'use_ep_level_unified_stream': '0', 'device_id': '0', 'has_user_compute_stream': '0', 'gpu_external_empty_cache': '0', 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'cudnn_conv1d_pad_to_nc1d': '0', 'gpu_mem_limit': '18446744073709551615', 'gpu_external_alloc': '0', 'gpu_external_free': '0', 'arena_extend_strategy': 'kNextPowerOfTwo', 'do_copy_in_default_stream': '1', 'enable_cuda_graph': '0', 'user_compute_stream': '0', 'cudnn_conv_use_max_workspace': '1'}} find model: /root/.insightface/models/buffalo_l/2d106det.onnx landmark_2d_106 ['None', 3, 192, 192] 0.0 1.0 Applied providers: ['CUDAExecutionProvider', 'CPUExecutionProvider'], with options: {'CPUExecutionProvider': {}, 'CUDAExecutionProvider': {'sdpa_kernel': '0', 'use_tf32': '1', 'fuse_conv_bias': '0', 'prefer_nhwc': '0', 'tunable_op_max_tuning_duration_ms': '0', 'enable_skip_layer_norm_strict_mode': '0', 'tunable_op_tuning_enable': '0', 'tunable_op_enable': '0', 'use_ep_level_unified_stream': '0', 'device_id': '0', 'has_user_compute_stream': '0', 'gpu_external_empty_cache': '0', 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'cudnn_conv1d_pad_to_nc1d': '0', 'gpu_mem_limit': '18446744073709551615', 'gpu_external_alloc': '0', 'gpu_external_free': '0', 'arena_extend_strategy': 'kNextPowerOfTwo', 'do_copy_in_default_stream': '1', 'enable_cuda_graph': '0', 'user_compute_stream': '0', 'cudnn_conv_use_max_workspace': '1'}} find model: /root/.insightface/models/buffalo_l/det_10g.onnx detection [1, 3, '?', '?'] 127.5 128.0 Applied providers: ['CUDAExecutionProvider', 'CPUExecutionProvider'], with options: {'CPUExecutionProvider': {}, 'CUDAExecutionProvider': {'sdpa_kernel': '0', 'use_tf32': '1', 'fuse_conv_bias': '0', 'prefer_nhwc': '0', 'tunable_op_max_tuning_duration_ms': '0', 'enable_skip_layer_norm_strict_mode': '0', 'tunable_op_tuning_enable': '0', 'tunable_op_enable': '0', 'use_ep_level_unified_stream': '0', 'device_id': '0', 'has_user_compute_stream': '0', 'gpu_external_empty_cache': '0', 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'cudnn_conv1d_pad_to_nc1d': '0', 'gpu_mem_limit': '18446744073709551615', 'gpu_external_alloc': '0', 'gpu_external_free': '0', 'arena_extend_strategy': 'kNextPowerOfTwo', 'do_copy_in_default_stream': '1', 'enable_cuda_graph': '0', 'user_compute_stream': '0', 'cudnn_conv_use_max_workspace': '1'}} find model: /root/.insightface/models/buffalo_l/genderage.onnx genderage ['None', 3, 96, 96] 0.0 1.0 Applied providers: ['CUDAExecutionProvider', 'CPUExecutionProvider'], with options: {'CPUExecutionProvider': {}, 'CUDAExecutionProvider': {'sdpa_kernel': '0', 'use_tf32': '1', 'fuse_conv_bias': '0', 'prefer_nhwc': '0', 'tunable_op_max_tuning_duration_ms': '0', 'enable_skip_layer_norm_strict_mode': '0', 'tunable_op_tuning_enable': '0', 'tunable_op_enable': '0', 'use_ep_level_unified_stream': '0', 'device_id': '0', 'has_user_compute_stream': '0', 'gpu_external_empty_cache': '0', 'cudnn_conv_algo_search': 'EXHAUSTIVE', 'cudnn_conv1d_pad_to_nc1d': '0', 'gpu_mem_limit': '18446744073709551615', 'gpu_external_alloc': '0', 'gpu_external_free': '0', 'arena_extend_strategy': 'kNextPowerOfTwo', 'do_copy_in_default_stream': '1', 'enable_cuda_graph': '0', 'user_compute_stream': '0', 'cudnn_conv_use_max_workspace': '1'}} find model: /root/.insightface/models/buffalo_l/w600k_r50.onnx recognition ['None', 3, 112, 112] 127.5 127.5 set det-size: (640, 640) ✅ FaceAnalysisの初期化に成功しました。ONNXモデルも正常に読み込めています。 ================================================== 🧪 テスト2: 今回ビルドした3Dメッシュ関連モジュールの動作確認を開始します... ✅ コンパイルされたCythonモジュールを含む`render`のインポートに成功しました。 ダミーデータでレンダリング関数を実行します... 🖼️ レンダリング関数が正常に実行されました! 生成された画像の形状: (256, 256, 3) (高さ, 幅, チャンネル) ✅ すべてのテストが正常に完了しました!ビルドは成功です。
これで、python 3.13のnunchakuのインポートも出来るようになりました。
以下、ビルドしたwhlです。
