YOLOv9 Distillation is not working
Search before asking
- I have searched the Ultralytics YOLO issues and found no similar bug report.
Ultralytics YOLO Component
Train
Bug
I am trying to use knowledge distillation to train a yolov9-s from a yolov9-e.
After passing AMP checks, caching images, etc. the training fails to start with the following error:
IndexError Traceback (most recent call last)
Cell In[4], line 2
1 # Pels paràmetres del training, veure https://docs.ultralytics.com/cfg/
----> 2 results = student.train(data="data.yaml", epochs=1000, cache=False, batch=16, imgsz=896, device='4', exist_ok=True, patience=100,
3 name='COCO_PyrVision_yv9sDistiledyv9e',
4 optimizer="AdamW",
5 resume=False,
6 workers=4,
7 distill_model="runs[/detect/COCO_PyrVision_yv9e_HT_Aramunt/weights/best.pt](http://localhost:8888/detect/COCO_PyrVision_yv9e_HT_Aramunt/weights/best.pt)",
8 lr0=0.0001,
9 lrf=0.0047,
10 momentum=0.92324,
11 weight_decay=0.00023,
12 warmup_epochs=4.68856,
13 warmup_momentum=0.6441,
14 box=6.33858,
15 cls=0.48686,
16 dfl=0.60424,
17 hsv_h=0.07261,
18 hsv_s=0.31264,
19 hsv_v=0.9,
20 degrees=0.0,
21 translate=0.04437,
22 scale=0.62024,
23 shear=0.0,
24 perspective=0.0,
25 flipud=0.0,
26 fliplr=0.88818,
27 bgr=0.0,
28 mosaic=0.76456,
29 mixup=0.0,
30 cutmix=0.0,
31 copy_paste=0.0
32 )
File ~/.local/lib/python3.11/site-packages/ultralytics/engine/model.py:880, in Model.train(self, trainer, **kwargs)
877 self.model = self.trainer.model
878 self.predictor = None # this module replaced the one the cached predictor wrapped
--> 880 self.trainer.train()
881 # Update model and cfg after training
882 if RANK in {-1, 0}:
File ~/.local/lib/python3.11/site-packages/ultralytics/engine/trainer.py:254, in BaseTrainer.train(self)
251 ddp_cleanup(self, str(file))
253 else:
--> 254 self._do_train()
255 finally:
256 unset_deterministic() # never leave deterministic state on, including the DDP parent and failed runs
File ~/.local/lib/python3.11/site-packages/ultralytics/engine/trainer.py:537, in BaseTrainer._do_train(self)
535 loss, self.loss_items = unwrap_model(self.model).loss(batch, preds)
536 else:
--> 537 loss, self.loss_items = self.model(batch)
538 self.loss = loss.sum()
539 if RANK != -1:
File ~/.local/lib/python3.11/site-packages/torch/nn/modules/module.py:1739, in Module._wrapped_call_impl(self, *args, **kwargs)
1737 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]
1738 else:
-> 1739 return self._call_impl(*args, **kwargs)
File ~/.local/lib/python3.11/site-packages/torch/nn/modules/module.py:1750, in Module._call_impl(self, *args, **kwargs)
1745 # If we don't have any hooks, we want to skip the rest of the logic in
1746 # this function, and just call forward.
1747 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1748 or _global_backward_pre_hooks or _global_backward_hooks
1749 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1750 return forward_call(*args, **kwargs)
1752 result = None
1753 called_always_called_hooks = set()
File ~[/](http://localhost:8888/).local/lib/python3.11/site-packages/ultralytics/nn/distill_model.py:199, in DistillationModel.forward(self, x, *args, **kwargs)
197 """Forward pass through the student model."""
198 if isinstance(x, dict): # for cases of training and validating while training.
--> 199 return self.loss(x, *args, **kwargs)
200 return self.student_model.predict(x, *args, **kwargs)
File ~/.local/lib/python3.11/site-packages/ultralytics/nn/distill_model.py:233, in DistillationModel.loss(self, batch, preds)
230 regular_loss, loss_items = self.student_model.loss(batch, preds)
231 teacher_head_feat = self._teacher_feats[self.feats_idx[-1]]
232 teacher_scores = (
--> 233 self.decouple_outputs(teacher_head_feat, branch="one2many")["scores"]
234 + self.decouple_outputs(teacher_head_feat, branch="one2one")["scores"]
235 ) / 2
236 # neck feature sizes vary per batch (e.g. multi_scale), so split scores by the live teacher feats
237 neck_feats = [self._teacher_feats[idx] for idx in self.feats_idx[:-1]]
IndexError: too many indices for tensor of dimension 4From the Ultralytics AI: The traceback shows the hook captured a 4D tensor from the teacher’s Detect head, but the loss tries to treat it as a dictionary with a "scores" key. The current distillation code expects that head output structure; your YOLOv9 run is providing a different one. Having both models be YOLOv9 does not prevent this output-format mismatch.
Is there any chance this can be fixed soon in an update?
Thank you very much!
Environment
Ultralytics 8.4.162 Python-3.11.0rc1 torch-2.6.0+cu124 CUDA:0 (NVIDIA RTX 6000 Ada Generation, 48511MiB) Setup complete ✅ (128 CPUs, 755.6 GB RAM, 859.8/878.1 GB disk)
OS Linux-5.15.0-191-generic-x86_64-with-glibc2.35 Environment Docker Python 3.11.0rc1
cloudpickle ✅ 3.1.2>=3.1.1 filelock ✅ 3.20.0>=3.16.1 numpy ✅ 2.4.3>=1.23.0; platform_system != "Darwin" numpy ✅ 2.4.3!=2.0.,!=2.1.,!=2.2.*,!=2.3.0,!=2.3.1,!=2.3.2,!=2.3.3,!=2.3.4,>=1.23.0; platform_system == "Darwin" matplotlib ✅ 3.10.8>=3.3.0 opencv-python ✅ 4.13.0.92!=4.13.0.90,>=4.7.0 pillow ✅ 12.0.0>=7.1.2 pyyaml ✅ 6.0.3>=5.3.1 requests ✅ 2.31.0>=2.23.0 torch ✅ 2.6.0+cu124>=1.8.0 torch ✅ 2.6.0+cu124!=2.4.0,>=1.8.0; sys_platform == "win32" torchvision ✅ 0.21.0+cu124>=0.9.0 psutil ✅ 7.2.2>=5.8.0 polars ✅ 1.38.1>=0.20.0 nvidia-ml-py ✅ 13.610.43>=12.0.0 ultralytics-thop ✅ 2.1.6>=2.1.6 ultralytics-platform ✅ 0.1.65>=0.1.45; python_version >= "3.11"
Minimal Reproducible Example
from ultralytics import YOLO
student = YOLO("yolov9s.pt")
results = student.train(data="data.yaml", epochs=1000, cache=False, batch=16, imgsz=896, device='4', exist_ok=True, patience=100, optimizer="AdamW", workers=4, distill_model="runs/detect/experiment/weights/best.pt")Additional
No response
Are you willing to submit a PR?
- Yes I'd like to help by submitting a PR!
Source: ultralytics/ultralytics