前提
https://qiita.com/r-osugi/items/60dd2c77ff614dd6e01d
https://dev.classmethod.jp/articles/yolov7-train-with-customize-dataset/
こちらの記事を参考に自分で用意した画像から任意の物体を検出したいと考えています。
まずvottでアノテーションしたデータをroboflowにてYOLO v7 PyTorch形式に変換し、google colaboratoryで下記の文を実行しようとしました。
しかしRuntimeErrorが返されてしまい、一応出力された.ptファイルで推論を実行してみたのですが機能しませんでした。
なぜRuntimeErrorが出るのか教えていただきたいです。
実現したいこと
発生している問題・エラーメッセージ
このような文と共にさいごRuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)と表示されてしまいます。 Epoch gpu_mem box obj cls total labels img_size 0% 0/1 [00:05<?, ?it/s] Traceback (most recent call last): File "train_aux.py", line 612, in <module> train(hyp, opt, device, tb_writer) File "train_aux.py", line 362, in train loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size File "/content/drive/MyDrive/Colab Notebooks/yolo/yolov7/utils/loss.py", line 1206, in __call__ bs_aux, as_aux_, gjs_aux, gis_aux, targets_aux, anchors_aux = self.build_targets2(p[:self.nl], targets, imgs) File "/content/drive/MyDrive/Colab Notebooks/yolo/yolov7/utils/loss.py", line 1559, in build_targets2 from_which_layer = from_which_layer[fg_mask_inboxes] RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)
該当のソースコード
python
1 2from google.colab import drive 3drive.mount('/content/drive') 4 5%cd /content/drive/My\ Drive/Colab\ Notebooks 6%mkdir yolo 7%cd yolo 8 9!git clone https://github.com/WongKinYiu/yolov7 10%cd yolov7 11 12# google colaboratoryで実行しようとすると衝突が発生するようなので/yolov7/requirements.txt の中身を下記の文に変更しました。 13 14# # Usage: pip install -r requirements.txt 15 16# # Base ---------------------------------------- 17# matplotlib>=3.2.2 18# numpy>=1.18.5 19# opencv-python>=4.1.1 20# Pillow>=7.1.2 21PyYAML>=5.3.1 22# requests>=2.23.0 23# scipy>=1.4.1 24# torch>=1.7.0,!=1.12.0 25# torchvision>=0.8.1,!=0.13.0 26# tqdm>=4.41.0 27# protobuf<4.21.3 28 29# # Logging ------------------------------------- 30# tensorboard>=2.4.1 31# # wandb 32 33# # Plotting ------------------------------------ 34# pandas>=1.1.4 35# seaborn>=0.11.0 36 37# # Export -------------------------------------- 38# # coremltools>=4.1 # CoreML export 39# # onnx>=1.9.0 # ONNX export 40# # onnx-simplifier>=0.3.6 # ONNX simplifier 41# # scikit-learn==0.19.2 # CoreML quantization 42# # tensorflow>=2.4.1 # TFLite export 43# # tensorflowjs>=3.9.0 # TF.js export 44# # openvino-dev # OpenVINO export 45 46# # Extras -------------------------------------- 47# ipython # interactive notebook 48# psutil # system utilization 49# thop # FLOPs computation 50# # albumentations>=1.0.3 51# # pycocotools>=2.0 # COCO mAP 52# # roboflow 53 54#変更終了 55 56 57!pip install -r requirements.txt 58 59 60 61#用意された画像と構築済みモデルでお試し 62!wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6.pt -P ./checkpoints 63!python detect.py --source inference/images/horses.jpg \ 64 --weights checkpoints/yolov7-e6.pt \ 65 --conf 0.25 --img-size 1280 --device 0 66from IPython.display import Image 67Image("/content/drive/MyDrive/Colab Notebooks/yolo/yolov7/runs/detect/exp/horses.jpg") 68#ここまでは上手くいけました 69 70 71mkdir dataset 72 73# roboflowにて変換したアノテーションデータをアップロード、ファイル構造は以下 74yolov7/ 75 ├─ dataset/ 76 │ ├─ train/ 77 │ │ ├─ images/ 78 │ │ │ ├─ XXX.png 79 │ │ │ └─ ... 80 │ │ └─ labels/ 81 │ │ ├─ XXX.txt 82 │ │ └─ ... 83 │ └─ valid/ 84 │ ├─ images/ 85 │ │ ├─ XXX.png 86 │ │ └─ ... 87 │ └─ labels/ 88 │ ├─ XXX.txt 89 │ └─ ... 90 ├─ data 91 │ ├─ data.yaml 92 │ └─ ... 93 └─ ... 94 95 96# data.yamlの下記文を変更 97(変更前) 98train: ../train/images 99val: ../valid/images 100(変更後) 101train: /content/drive/MyDrive/Colab Notebooks/yolo/yolov7/dataset/train/images 102val: /content/drive/MyDrive/Colab Notebooks/yolo/yolov7/dataset/valid/images 103#変更終了 104 105from typing_extensions import dataclass_transform 106 107 108!python train_aux.py --workers 2 --batch-size 8 \ 109 --data /content/drive/MyDrive/Colab Notebooks/yolo/yolov7/data/data.yaml \ 110 --cfg cfg/training/yolov7-e6.yaml \ 111 --weights 'checkpoints/yolov7-e6.pt' \ 112 --name yolov7-teibou \ 113 --hyp data/hyp.scratch.p6.yaml \ 114 --epochs 10 \ 115 --device 0 116 117 118
試したこと
python - YOLOv7 - RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu) - Stack Overflow
上記のページで下記のような回答があったので
you have to replace the line in the file yolo7/utils/loss.py
"from_which_layer.append((torch.ones(size=(len(b),)) * i)"
to "from_which_layer.append((torch.ones(size=(len(b),)) * i).to('cuda'))",
and add new line "fg_mask_inboxes = fg_mask_inboxes.to(torch.device('cuda'))"
after "fg_mask_inboxes = matching_matrix.sum(0) > 0.0"
so you need to do it 3 times in the file
loss.pyの"from_which_layer.append((torch.ones(size=(len(b),)) * i)"
を
"from_which_layer.append((torch.ones(size=(len(b),)) * i).to('cuda'))",
に書き換え
"fg_mask_inboxes = fg_mask_inboxes.to(torch.device('cuda'))"
という文を
"fg_mask_inboxes = matching_matrix.sum(0) > 0.0"
の後ろに追加したりもしたのですがRuntimeErrorは改善されませんでした。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。

下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。