気の向くままに辿るIT/ICT/IoT
ハードウェア

AMD Ryzen AIチュートリアルGetting Started ResNet

ホーム前へ次へ
AMD Ryzen AIソフトウェアって?

AMD Ryzen AIチュートリアルGetting Started ResNet

AMD Ryzen AIチュートリアルGetting Started ResNet

2025/03/31

 AMD Ryzen AIソフトウェアとNPUドライバをインストールした自身初購入のミニパソコンRyzen 7 8845HS搭載AOOSTAR GEM12 Pro MAX/Windows 11 Proにamd / RyzenAI-SWをgit cloneしてAI学習するGetting Started ResNet編。

 ResNet(Residual Network/残差ネットワーク)。

getting_started_resnetの概要

 詳細は、Getting Started Tutorial

 おおまなか手順としては、Ryzen AIソフトウェアを使用して

  1. データセットCIFAR-10とONNXモデルをダウンロード・準備(prepare_model_data.py)
  2. ONNXモデルを量子化(resnet_quantize.py)
  3. ONNXモデルをCPU、Ryzen AI NPUそれぞれでデプロイ・展開、予測(CPU:predict.py/NPU:predict.py --ep npu)
  4. 結果を眺め比較・評価

 尚、ここではPythonのみとしていますが、デプロイについてはC++の説明もあります。

getting_started_resnetを実行する前に

 まず、getting_started_resnetでは、比較的大きなモデルファイルのダウンロードを伴うのでGitとGit LFSをインストールした後にリポジトリamd / RyzenAI-SWをgit cloneしておかないとエラーでハマるので要注意です。

File "path\to\RyzenAI-SW-main\RyzenAI-SW-main\tutorial\getting_started_resnet\venv\Lib\site-packages\torch\serialization.py", line 1744, in _legacy_load
  magic_number = pickle_module.load(f, **pickle_load_args)
 
_pickle.UnpicklingError: invalid load key, 'v'.

 そうしておかないと、こんなエラーに見舞われます。(当初、環境構築ミスった自身だけかも?)

PS C:\Users\xxx cd path\to\RyzenAI-SW-main\RyzenAI-SW-main\tutorial\getting_started_resnet> cat .\prepare_model_data.py
...
  #model = torch.load(str(models_dir / "resnet_trained_for_cifar10.pt"))
              ↓
  model = torch.load(str(models_dir / "resnet_trained_for_cifar10.pt"), weights_only=False)
...
(ryzen-ai-1.4.0) path\to\RyzenAI-SW-main\RyzenAI-SW-main\tutorial\getting_started_resnet>

 尚、その上であっても少なくとも今日時点、getting_started_resnetで使うtorch 2.6.0含む以降のセキュリティ強化により、prepare_model_data.pyで1ヶ所、例えば、このような追記・修正が必要となります。

  raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
_pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint.
    (1) In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source.
    (2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message.
    WeightsUnpickler error: Unsupported global: GLOBAL torchvision.models.resnet.ResNet was not an allowed global by default. Please use `torch.serialization.add_safe_globals([ResNet])` or the `torch.serialization.safe_globals([ResNet])` context manager to allowlist this global if you trust this class/function.
 
Check the documentation of torch.load to learn more about types accepted by default with weights_only https://pytorch.org/docs/stable/generated/torch.load.html.

 尚、先の修正例は、修正前に実行した結果、このようなエラーとなりつつ、改善提案としていくつか提示された内の1つです。

 他にもエラーは出るかと思いますが、ModuleNotFoundError: No module named ...くらいで...のパッケージをpip installする程度で通ると思います。

WindowsでRyzen AI Softwareチュートリアルgetting_started_resnet

path\to\getting_started_resnet> conda activate ryzen-ai-1.4.0
(ryzen-ai-1.4.0) path\to\getting_started_resnet>

 まずは、quicktest時と同様に仮想環境を作って、仮想環境を有効にしてから始めます。

 ryzen-ai-1.4.0は、Ryzen AIソフトウェアのインストール中に指定時、デフォルトのconda仮想環境名、もしくは、それをベースに変更したconda仮想環境名です。

(ryzen-ai-1.4.0) path\to\getting_started_resnet> pip install -r requirements.txt

 続いて当該プロジェクトで必要なパッケージのインストール。

  cifar-10-batches-bin
  cifar-10-batches-py
  cifar-10-binary.tar.gz
  cifar-10-python.tar.gz

 CIFAR-10データセットとONNXモデルをダウンロード・準備するprepare_model_data.pyを実行するとdata\フォルダにCIFAR-10データセットがダウンロードされ、このようになります。

 次にONNXモデルを量子化するresnet_quantize.pyを実行。

 続いてONNXモデルをデプロイ(展開)するわけですが、PythonとC++の例があり、それぞれ、CPU、Ryzen AI NPUで処理した結果を比較できます。

 ここでは、Pythonを使いました。

 Pythonでは、CPUによる予測をpredict.py、NPUによる予測をスイッチ付きでpredict.py --ep npuとして実行し、CPU、NPUの予測結果を取得できるようになっています。

Ryzen AI Softwareチュートリアルgetting_started_resnetサンプル画像10点

 getting_started_resnetデフォルトのAIに予測してもらったサンプル画像がこちら(等倍だと見づらいので1.5倍ほどに拡大、別タブで開けば確認可)。

(get_resnet-1.4.0) path\to\getting_started_resnet>python predict.py
Image 0: Actual Label cat, Predicted Label cat
Image 1: Actual Label ship, Predicted Label ship
Image 2: Actual Label ship, Predicted Label ship
Image 3: Actual Label airplane, Predicted Label airplane
Image 4: Actual Label frog, Predicted Label frog
Image 5: Actual Label frog, Predicted Label frog
Image 6: Actual Label automobile, Predicted Label truck
Image 7: Actual Label frog, Predicted Label frog
Image 8: Actual Label cat, Predicted Label cat
Image 9: Actual Label automobile, Predicted Label automobile
 
(get_resnet-1.4.0) path\to\getting_started_resnet>

 オプションなしのpredict.pyを実行したCPUの予測結果。

(get_resnet-1.4.0) path\to\getting_started_resnet>python predict.py --ep npu
WARNING: Logging before InitGoogleLogging() is written to STDERR
I20250411 08:09:47.389912 15588 vitisai_compile_model.cpp:1144] Vitis AI EP Load ONNX Model Success
I20250411 08:09:47.389912 15588 vitisai_compile_model.cpp:1145] Graph Input Node Name/Shape (1)
I20250411 08:09:47.389912 15588 vitisai_compile_model.cpp:1149] input : [-1x3x32x32]
I20250411 08:09:47.389912 15588 vitisai_compile_model.cpp:1155] Graph Output Node Name/Shape (1)
I20250411 08:09:47.390913 15588 vitisai_compile_model.cpp:1159] output : [-1x10]
[Vitis AI EP] No. of Operators : CPU 2 NPU 398
[Vitis AI EP] No. of Subgraphs : NPU 1 Actually running on NPU 1
2025-04-11 08:10:10.3571463 [W:onnxruntime:, session_state.cc:1168 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Some nodes were not assigned to the preferred execution providers which may or may not have an negative impact on performance. e.g. ORT explicitly assigns shape related ops to CPU to improve perf.
2025-04-11 08:10:10.3644126 [W:onnxruntime:, session_state.cc:1170 onnxruntime::VerifyEachNodeIsAssignedToAnEp] Rerunning with verbose output on a non-minimal build will show node assignments.
Image 0: Actual Label cat, Predicted Label cat
Image 1: Actual Label ship, Predicted Label ship
Image 2: Actual Label ship, Predicted Label ship
Image 3: Actual Label airplane, Predicted Label airplane
Image 4: Actual Label frog, Predicted Label frog
Image 5: Actual Label frog, Predicted Label frog
Image 6: Actual Label automobile, Predicted Label truck
Image 7: Actual Label frog, Predicted Label frog
Image 8: Actual Label cat, Predicted Label cat
Image 9: Actual Label automobile, Predicted Label automobile
 
(get_resnet-1.4.0) path\to\getting_started_resnet>

 続いてpredict.py --ep npuを実行したNPUの予測結果。

 何れの予測も同一で[Image 6:]の実際はautomobileをtruckと予測してしまっていますが、学習データにこうしたものがあったのか、あえて学習させなかったのか、乗用車のドアとハッチバックを開放した状態なのでトラックと見間違えるのも、わからなくもないかなと。

 他のネコ、船、飛行機、カエル、自動車は、見事正解してるので優秀。

 ちなみに等倍だと自身の「視力」では、せいぜい1つか2つくらいしかわからないかも...、ビットマップなら...もっとわかんない。

終わったらconda deactivateを忘れずに

(ryzen-ai-1.4.0) path\to\getting_started_resnet> conda deactivate
path\to\getting_started_resnet>

 condaの仮想環境での作業が一通り終わったら、conda deactivate(activateの反対語deactivate)しましょう。

 これを忘れると、たいてい痛い目にあうので要注意。

conda info -e
 
# conda environments
#
 
base                path\to\anaconda3
ryzen-ai-1.4.0      path\to\anaconda3\envs\ryzen-ai-1.4.0

 conda deactivateしたら、都度、conda info -eで[*]のついた仮想環境がないことを確認しておくと安心です。

 なぜなら、一見、作業ディレクトリパス先頭から(ryzen-ai-1.4.0)といった仮想環境の表記が消えてもconda info -eで確認すると、まだ[*]が付いているなんてことがあったり、なぜか、代わりに(base)という仮想環境に入ってしまっていたり、知らずにAnacondaコマンドプロンプトを閉じて戻っても同様だったりすることもあったりするので。

 仮想環境baseになってしまう場合、ディレクトリパス先頭に表示されるとは言え、本来の仮想環境については、deactivateコマンドを実行した確信が手伝うのか、意外と気づかないことも多く...。

 何れにせよ、condaの仮想環境にいることを、知らずに、そのまま作業し続けると何かとハマりやすいので要注意。

2025/04/11 訂正・追記
(ryzen-ai-1.4.0) path\to\getting_started_resnet> python -m virtualenv .venv
(ryzen-ai-1.4.0) path\to\getting_started_resnet> .\.venv\Scripts\activate

 ページを分けた関係で改めて書くと、まずは、quicktest時と同様に仮想環境を作って、仮想環境を有効にしてから始めます。

 ここでは、condaではなく、pipを使いますが、pip install virtualenvは既に済んでいるものとします。

(ryzen-ai-1.4.0) path\to\getting_started_resnet> pip install -r requirements.txt

 続いて当該プロジェクトで必要なパッケージのインストール。

  cifar-10-batches-bin
  cifar-10-batches-py
  cifar-10-binary.tar.gz
  cifar-10-python.tar.gz

 肝心のサンプルスクリプトですが、概要に記したように、いくつかありますが、今回は、目立った成果物はないので最初のprepare_model_data.pyの実行結果だけ示しておくことにします。

 prepare_model_data.pyを実行するとdata\フォルダにCIFAR-10データセットがダウンロードされ、このようになります。

 尚、[ModuleNotFoundError: No module named xxx]というエラーが出るかもしれません。

 今回は、[xxx]にあたるのは、[onnxruntime]と[quark]でしたが、onnxruntimeならonnxruntimeを、quarkなら、amd-quarkをpip install。

 Pypiには、quark系がたくさんあるので注意、ここで必要なのは、amd-quark。

 そんなこんなで以後のサンプルスクリプトは、詳細に説明がなされているので公式チュートリアルを参照しましょう。

ホーム前へ次へ