File size: 9,004 Bytes
a54a01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Standalone YOLO Experiments For Varroa

This folder is independent from `object_detection_related`. It reads the
original dataset layout directly:

```text
train|val|test/
  videos/<video-id>/*.png
  labels/<video-id>/*.txt
```

Original labels contain a first count line, then absolute pixel `xyxy` boxes.
The converter writes Ultralytics YOLO labels with class `0 = varroa`.

Activate an environment with `torch`, `ultralytics`, and `pillow` installed:

```bash
conda activate ml2
python --version
```

If your shell cannot use `conda activate`, use `conda run -n ml2` before the
`python` command. The training and evaluation scripts default to `device=cpu`.

## Prepare Dataset

Full conversion:

```bash
python yolo_related/prepare_dataset.py \
  --root . \
  --out-dir yolo_related/datasets/varroa_yolo
```

Small smoke dataset:

```bash
python yolo_related/prepare_dataset.py \
  --root . \
  --out-dir /tmp/varroa_yolo_smoke \
  --limit 2
```

## Train

YOLOv8 baseline:

```bash
python yolo_related/train.py \
  --root . \
  --weights yolov8n.pt \
  --epochs 100 \
  --imgsz 640 \
  --batch-size 4 \
  --device cpu \
  --name yolov8n_varroa_cpu
```

YOLOv8 custom YAML with pretrained partial load:

```bash
python yolo_related/train.py \
  --root . \
  --model-yaml yolo_related/models/yolov8_varroa_custom.yaml \
  --pretrained yolov8n.pt \
  --epochs 100 \
  --imgsz 640 \
  --batch-size 4 \
  --device cpu \
  --name yolov8n_varroa_custom_cpu
```

YOLOv10 baseline, if your Ultralytics version supports the weight:

```bash
python yolo_related/train.py \
  --root . \
  --weights yolov10n.pt \
  --epochs 100 \
  --imgsz 640 \
  --batch-size 4 \
  --device cpu \
  --name yolov10n_varroa_cpu
```

## Evaluate

```bash
python yolo_related/eval.py \
  --root . \
  --weights yolo_related/runs/train/yolov8n_varroa_cpu/weights/best.pt \
  --split test \
  --device cpu
```

Outputs:

- `yolo_related/runs/eval/<name>/test_per_image.csv`
- `yolo_related/runs/eval/<name>/test_summary.csv`

## Local Ultralytics Clone

Custom YAML module names are resolved by Ultralytics internals, not by normal
project imports. This repo uses a patched local clone:

```text
yolo_related/ultralytics
```

`yolo_related/train.py` and `yolo_related/eval.py` call
`prefer_local_ultralytics()` before importing `ultralytics`, so they use this
clone automatically.

Manual one-liners do not use the clone unless you add it to `PYTHONPATH`:

```bash
PYTHONPATH=yolo_related/ultralytics \
python -c \
"import ultralytics; print(ultralytics.__file__)"
```

Expected path:

```text
<repo>/yolo_related/ultralytics/ultralytics/__init__.py
```

If the path contains `site-packages/ultralytics`, your manual command is not
using the patched clone and custom block names may fail with `KeyError`.

## Current Custom Blocks

These blocks are already registered in the patched clone:

- `VarroaConvBlock`
- `VarroaSEBlock`

Registration locations:

- `yolo_related/ultralytics/ultralytics/nn/modules/block.py`
- `yolo_related/ultralytics/ultralytics/nn/modules/__init__.py`
- `yolo_related/ultralytics/ultralytics/nn/tasks.py`

`yolo_related/custom_blocks.py` is only a readable reference copy. The YAML
resolver uses the classes registered inside the local Ultralytics clone.

`yolo_related/models/yolov8_varroa_custom.yaml` currently uses a real custom
block:

```yaml
- [-1, 3, VarroaConvBlock, [128, 3, True]]
```

## Step By Step: Replace A Block

Prefer replacement first because layer indices stay the same.

For YOLOv8, edit:

```text
yolo_related/models/yolov8_varroa_custom.yaml
```

For YOLOv10, edit:

```text
yolo_related/models/yolov10_varroa_custom.yaml
```

Original YOLOv8 line:

```yaml
- [-1, 3, C2f, [128, True]]
```

Custom replacement:

```yaml
- [-1, 3, VarroaConvBlock, [128, 3, True]]
```

Layer format:

```text
[from, repeats, module, args]
```

For `VarroaConvBlock`, YAML args are:

```text
[c2, kernel_size, shortcut]
```

Because `VarroaConvBlock` is in `parse_model()` `base_modules`, Ultralytics
injects `c1` from the previous layer and scales `c2` according to the selected
model scale.

### What `c1` And `c2` Mean

Ultralytics modules usually use:

- `c1`: input channels, inferred from the previous layer.
- `c2`: output channels, written as the first value in YAML `args`.

You do not write `c1` in the YAML for modules in `base_modules`. For this line:

```yaml
- [-1, 3, VarroaConvBlock, [128, 3, True]]
```

Ultralytics reads:

```text
from=-1, repeats=3, module=VarroaConvBlock, args=[128, 3, True]
```

Then `parse_model()` converts it to a constructor call like:

```python
VarroaConvBlock(c1=previous_layer_channels, c2=scaled_128, kernel_size=3, shortcut=True)
```

With YOLOv8 nano scale, `128` is scaled by width multiplier `0.25`, so the
actual `c2` becomes `32`. That is why model printout can show:

```text
Conv2d(32, 32, kernel_size=(3, 3), ...)
```

For blocks not in `base_modules`, Ultralytics does not inject `c1/c2`; you must
handle their args manually in `parse_model()`.

## Step By Step: Insert A Block

Insert only after a replacement build works. Example after `SPPF`:

Edit the model YAML you are training, usually:

```text
yolo_related/models/yolov8_varroa_custom.yaml
```

```yaml
- [-1, 1, SPPF, [1024, 5]]
- [-1, 1, VarroaSEBlock, [1024, 8]]
```

For `VarroaSEBlock`, YAML args are:

```text
[c2, reduction]
```

Warning: inserting a layer shifts later layer indices. Update downstream
`from` references such as `[-1, 9]` or `[15, 18, 21]` when needed.

## Step By Step: Add A New Block Class

For a new block named `MyBlock`:

1. Add the class to `yolo_related/ultralytics/ultralytics/nn/modules/block.py`.
2. Add `"MyBlock"` to `block.py` `__all__`.
3. Import `MyBlock` in `yolo_related/ultralytics/ultralytics/nn/modules/__init__.py`.
4. Add `"MyBlock"` to `ultralytics/nn/modules/__init__.py` `__all__`.
5. Import `MyBlock` in `yolo_related/ultralytics/ultralytics/nn/tasks.py`.
6. Add `MyBlock` to `base_modules` in `parse_model()` if its constructor starts
   with `(c1, c2, ...)`.
7. Add `MyBlock` to `repeat_modules` only if its constructor expects an
   internal repeat count `n`, like `C2f(c1, c2, n, ...)`.
8. Reference `MyBlock` in the model YAML you train, for example
   `yolo_related/models/yolov8_varroa_custom.yaml`.

Simple class shape:

```python
class MyBlock(nn.Module):
    def __init__(self, c1: int, c2: int, kernel_size: int = 3):
        super().__init__()
        self.conv = nn.Conv2d(c1, c2, kernel_size, padding=kernel_size // 2)

    def forward(self, x):
        return self.conv(x)
```

YAML:

```yaml
- [-1, 1, MyBlock, [256, 3]]
```

Ultralytics constructs it as:

```python
MyBlock(c1=previous_layer_channels, c2=256, kernel_size=3)
```

## Step By Step: Test After Editing

1. Confirm the patched clone is active:

```bash
PYTHONPATH=yolo_related/ultralytics \
python -c \
"import ultralytics; print(ultralytics.__file__)"
```

2. Build the model and print the edited layer:

```bash
PYTHONPATH=yolo_related/ultralytics \
python -c \
"from ultralytics import YOLO; m=YOLO('yolo_related/models/yolov8_varroa_custom.yaml'); print(m.model.model[2]); m.info(detailed=True)"
```

3. Run a dummy forward:

```bash
PYTHONPATH=yolo_related/ultralytics \
python -c \
"import torch; from ultralytics import YOLO; m=YOLO('yolo_related/models/yolov8_varroa_custom.yaml'); y=m.model(torch.randn(1, 3, 640, 640)); print(type(y))"
```

4. Check pretrained partial loading:

```bash
PYTHONPATH=yolo_related/ultralytics \
python -c \
"from ultralytics import YOLO; m=YOLO('yolo_related/models/yolov8_varroa_custom.yaml'); m.load('yolov8n.pt')"
```

Expected: a line like `Transferred X/Y items from pretrained weights` with
`X > 0`. The exact numbers change when the architecture changes. Lower transfer
counts are normal after replacing layers or changing channel shapes. The detect
head often transfers partially or not at all because this dataset uses `nc: 1`
while COCO pretrained weights use `nc: 80`.

5. Run a CPU smoke train:

```bash
python yolo_related/train.py \
  --root . \
  --yolo-dir /tmp/varroa_yolo_smoke \
  --model-yaml yolo_related/models/yolov8_varroa_custom.yaml \
  --pretrained yolov8n.pt \
  --epochs 1 \
  --imgsz 160 \
  --batch-size 2 \
  --device cpu \
  --workers 0 \
  --limit 2 \
  --project /tmp/varroa_yolo_runs \
  --name smoke_custom_block_cpu
```

## Safe Editing Rules

- Replace first, insert later.
- Keep custom block output `c2` compatible with the layer being replaced.
- Change one block at a time, then run the test steps.
- If inserting layers, update later `from` indices.
- Keep `Detect` for YOLOv8 and `v10Detect` for YOLOv10 unchanged until simpler
  backbone/neck edits train cleanly.

## Original YAML Files

Local patched clone:

```text
yolo_related/ultralytics/ultralytics/cfg/models/v8/yolov8.yaml
```

Installed `ml2` package:

```bash
python -c \
"import ultralytics, pathlib; root=pathlib.Path(ultralytics.__file__).parent; print(root/'cfg'/'models'/'v8'/'yolov8.yaml')"
```