attr-eomt 2.0.0__tar.gz → 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. attr_eomt-2.1.0/.github/workflows/prerelease.yml +85 -0
  2. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/.github/workflows/release.yml +4 -1
  3. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/PKG-INFO +65 -1
  4. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/README.md +64 -0
  5. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/aux_cls.py +29 -0
  6. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/__init__.py +5 -0
  7. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/config.py +3 -3
  8. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/sets.py +86 -6
  9. attr_eomt-2.1.0/eomt/data/subjects.py +278 -0
  10. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/train.py +113 -19
  11. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/validate.py +77 -39
  12. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/loss.py +51 -10
  13. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/model.py +14 -3
  14. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/pyproject.toml +1 -1
  15. attr_eomt-2.1.0/tests/test_subjects.py +242 -0
  16. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_xview.py +86 -8
  17. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/.github/workflows/pages.yml +0 -0
  18. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/.github/workflows/publish.yml +0 -0
  19. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/.github/workflows/tests.yml +0 -0
  20. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/.gitignore +0 -0
  21. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/LICENSE +0 -0
  22. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/configs/coco.yaml +0 -0
  23. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/configs/xview.yaml +0 -0
  24. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/assets/00-hero-banner.png +0 -0
  25. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/assets/00-hero-banner.svg +0 -0
  26. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/examples/billie_eilish.jpg +0 -0
  27. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/examples/rosalia.jpg +0 -0
  28. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/examples/sample.jpg +0 -0
  29. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/docs/examples/taylor_swift.jpg +0 -0
  30. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/__init__.py +0 -0
  31. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/api.py +0 -0
  32. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/box_loss.py +0 -0
  33. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/compress.py +0 -0
  34. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/config.py +0 -0
  35. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/coco.py +0 -0
  36. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/download.py +0 -0
  37. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/data/transforms.py +0 -0
  38. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/device.py +0 -0
  39. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/ema.py +0 -0
  40. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/__init__.py +0 -0
  41. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/distributed.py +0 -0
  42. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/match.py +0 -0
  43. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/predict.py +0 -0
  44. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/engine/track.py +0 -0
  45. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/plotting.py +0 -0
  46. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/postprocess.py +0 -0
  47. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/preprocess.py +0 -0
  48. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/reid.py +0 -0
  49. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/serialization.py +0 -0
  50. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/tta.py +0 -0
  51. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/eomt/visualize.py +0 -0
  52. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/README.md +0 -0
  53. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/annotations/instances_train.json +0 -0
  54. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/annotations/instances_val.json +0 -0
  55. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/data.yaml +0 -0
  56. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/images/train/.gitkeep +0 -0
  57. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/images/val/.gitkeep +0 -0
  58. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/sample_data/run.yaml +0 -0
  59. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/info.py +0 -0
  60. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/match.py +0 -0
  61. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/predict.py +0 -0
  62. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/push_to_hub.py +0 -0
  63. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/track.py +0 -0
  64. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/train.py +0 -0
  65. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/train_detect_coco.sh +0 -0
  66. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/train_multiview.py +0 -0
  67. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/scripts/val.py +0 -0
  68. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/site/index.html +0 -0
  69. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_api.py +0 -0
  70. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_architecture.py +0 -0
  71. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_augment.py +0 -0
  72. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_compress.py +0 -0
  73. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_ddp.py +0 -0
  74. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_hires.py +0 -0
  75. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_parity.py +0 -0
  76. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_recipe.py +0 -0
  77. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_regression_attr.py +0 -0
  78. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_reid.py +0 -0
  79. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_run_config.py +0 -0
  80. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_smoke.py +0 -0
  81. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_sweep.py +0 -0
  82. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tests/test_tta.py +0 -0
  83. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tools/attr_tagger/README.md +0 -0
  84. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/tools/attr_tagger/tag.py +0 -0
  85. {attr_eomt-2.0.0 → attr_eomt-2.1.0}/uv.lock +0 -0
@@ -0,0 +1,85 @@
1
+ name: prerelease
2
+
3
+ # Publish a pre-release of any branch to PyPI, to try a change in another project before the final release.
4
+ #
5
+ # 1. On the branch, set a PEP 440 pre-release version in pyproject.toml: `version = "2.1.0rc1"` (or 2.1.0a1,
6
+ # 2.1.0b1, 2.1.0.dev1) and commit it.
7
+ # 2. Tag that commit with the version and push the tag (the branch too, if you like):
8
+ # git tag v2.1.0rc1 && git push origin v2.1.0rc1
9
+ # Once this file is on main, GitHub -> Actions -> prerelease -> "Run workflow" on a branch works as well
10
+ # (GitHub lists manual workflows from the default branch only; a pushed tag runs the workflow of its own commit).
11
+ # 3. The tests run, a GitHub pre-release vX.Y.ZrcN is cut on that commit and the package goes to PyPI.
12
+ #
13
+ # pip and uv skip pre-releases unless asked, so nothing that depends on `attr-eomt>=...` picks it up by accident:
14
+ # pip install attr-eomt==2.1.0rc1 uv add "attr-eomt==2.1.0rc1" (or --prerelease allow)
15
+ # A version already released is refused (bump rcN for the next try); the final release stays release.yml's job
16
+ # (merge to main with the final version).
17
+ #
18
+ # NOTE: the PyPI trusted publisher (workflow publish.yml, environment pypi) must accept runs from branches other
19
+ # than main: if the `pypi` environment limits its deployment branches, allow these branches (or tags) there.
20
+
21
+ on:
22
+ push:
23
+ tags: ["v*a[0-9]*", "v*b[0-9]*", "v*rc[0-9]*", "v*.dev[0-9]*"]
24
+ workflow_dispatch:
25
+
26
+ permissions:
27
+ contents: read
28
+
29
+ jobs:
30
+ check:
31
+ runs-on: ubuntu-latest
32
+ outputs:
33
+ version: ${{ steps.v.outputs.version }}
34
+ steps:
35
+ - uses: actions/checkout@v5
36
+ - name: Read the version and check it is a new pre-release
37
+ id: v
38
+ env:
39
+ GH_TOKEN: ${{ github.token }}
40
+ run: |
41
+ VERSION=$(grep -m1 -E '^version *= *"' pyproject.toml | sed -E 's/.*"([^"]+)".*/\1/')
42
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
43
+ if ! python3 -c "import re, sys; sys.exit(0 if re.search(r'(a|b|rc|\.dev)[0-9]+$', '$VERSION') else 1)"; then
44
+ echo "::error::$VERSION is not a pre-release version (X.Y.ZaN / bN / rcN / .devN); final releases go through release.yml"
45
+ exit 1
46
+ fi
47
+ if [ "$GITHUB_REF_TYPE" = tag ] && [ "$GITHUB_REF_NAME" != "v$VERSION" ]; then
48
+ echo "::error::tag $GITHUB_REF_NAME does not match pyproject.toml's version $VERSION"
49
+ exit 1
50
+ fi
51
+ if gh release view "v$VERSION" >/dev/null 2>&1; then
52
+ echo "::error::v$VERSION is already released; bump the pre-release number"
53
+ exit 1
54
+ fi
55
+ echo "::notice::pre-releasing v$VERSION from ${GITHUB_REF_NAME}"
56
+
57
+ test:
58
+ needs: check
59
+ uses: ./.github/workflows/tests.yml
60
+
61
+ release:
62
+ needs: [check, test]
63
+ runs-on: ubuntu-latest
64
+ permissions:
65
+ contents: write # create the tag + GitHub pre-release
66
+ steps:
67
+ - uses: actions/checkout@v5
68
+ - name: Create the GitHub pre-release
69
+ env:
70
+ GH_TOKEN: ${{ github.token }}
71
+ VERSION: ${{ needs.check.outputs.version }}
72
+ run: |
73
+ # on a tag push the tag exists already and the release is cut on it; on a manual run the tag is created
74
+ gh release create "v$VERSION" \
75
+ --title "v$VERSION" \
76
+ --prerelease \
77
+ --generate-notes \
78
+ --target "$GITHUB_SHA"
79
+
80
+ publish:
81
+ needs: [check, release]
82
+ permissions:
83
+ id-token: write # PyPI Trusted Publishing (OIDC)
84
+ contents: read
85
+ uses: ./.github/workflows/publish.yml
@@ -8,6 +8,7 @@ name: release
8
8
  # To ship a new version:
9
9
  # 1. In your PR, bump `version = "X.Y.Z"` in pyproject.toml.
10
10
  # 2. Merge to main. That's it — this workflow tags vX.Y.Z and publishes.
11
+ # To try a branch first, publish a pre-release of it with prerelease.yml (version X.Y.ZrcN).
11
12
  # Pushes that don't change the version are no-ops (the Release already exists).
12
13
  #
13
14
  # Publishing is delegated to publish.yml via `workflow_call` (not the release event),
@@ -65,10 +66,12 @@ jobs:
65
66
  GH_TOKEN: ${{ github.token }}
66
67
  VERSION: ${{ needs.check.outputs.version }}
67
68
  run: |
69
+ # a pre-release version (aN / bN / rcN / .devN) merged to main is released as a GitHub pre-release
70
+ PRE=$(python3 -c "import re; print('--prerelease' if re.search(r'(a|b|rc|\.dev)[0-9]+$', '$VERSION') else '')")
68
71
  gh release create "v$VERSION" \
69
72
  --title "v$VERSION" \
70
73
  --generate-notes \
71
- --target "$GITHUB_SHA"
74
+ --target "$GITHUB_SHA" $PRE
72
75
 
73
76
  publish:
74
77
  needs: [check, release]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: attr-eomt
3
- Version: 2.0.0
3
+ Version: 2.1.0
4
4
  Summary: Standalone EoMT (Encoder-only Mask Transformer) for instance segmentation, with DINOv2 init, COCO training/validation and inference.
5
5
  Project-URL: Homepage, https://github.com/imagra93/attr-eomt
6
6
  Project-URL: Documentation, https://imagra93.github.io/attr-eomt
@@ -483,6 +483,70 @@ them one by one); `"partition"` groups similar photos (mean patch token of a sma
483
483
  other photos of the subject, not a particular one. `scripts/predict.py --subject [MODE]` and
484
484
  `predict(subject=MODE)` take the mode (`--subject` alone is `"order"`).
485
485
 
486
+ ### Real multi-photo datasets
487
+
488
+ Synthetic sets need no multi-photo annotations, but they show no real viewpoint change. With
489
+ annotated photos of the same subjects, the post-training also draws **real sets**: several
490
+ photos of one subject, each predicted with the others, the instances linked across them. The
491
+ data is a COCO instance-segmentation file like any other, with four optional additions
492
+ ([`eomt/data/subjects.py`](eomt/data/subjects.py)):
493
+
494
+ ```jsonc
495
+ "images": [
496
+ {"id": 1, "file_name": "subject_42/front.jpg", "subject_id": "subject_42"}, // a photo of subject_42
497
+ {"id": 2, "file_name": "subject_42/closeup.jpg", "subject_id": "subject_42", "supervision": "positives"},
498
+ {"id": 3, "file_name": "subject_42/side.jpg", "subject_id": "subject_42", "supervision": "none"}
499
+ ],
500
+ "annotations": [
501
+ {"id": 10, "image_id": 1, "category_id": 3, "instance_id": 7, ...}, // the same physical instance ...
502
+ {"id": 11, "image_id": 2, "category_id": 3, "instance_id": 7, ...}, // ... in another photo of subject_42
503
+ {"id": 12, "image_id": 1, "category_id": 5, ...}, // not linked to the other photos
504
+ {"id": 13, "image_id": 3, "category_id": 3, "iscrowd": 1, ...} // a region to leave out of the loss
505
+ ]
506
+ ```
507
+
508
+ | key | meaning |
509
+ |-----|---------|
510
+ | image `subject_id` | photos with the same id show the same subject; photos without one take no part in the real sets |
511
+ | image `supervision` | `full` (default): every instance is annotated, the rest is background. `positives`: only some are; nothing unannotated is taught as background (the photo's unmatched queries take no "no object" loss). `none`: input only for the other photos of its set |
512
+ | annotation `instance_id` | the same physical instance in every photo of the subject that shows it (a number or string); the matching head learns those links. Absent: linked to nothing |
513
+ | annotation `iscrowd: 1` | unsure pixels: a query whose mask lies mostly inside takes no "no object" loss, and validation drops detections there (single-photo training already skips these annotations) |
514
+
515
+ Partly annotated photos are what pseudo-labelling gives: labels that list some instances per
516
+ photo, or say which photos show an instance but not where. The loss then trains on what is
517
+ known and leaves the rest out, instead of teaching it as background.
518
+
519
+ Real sets join the post-training through the `real` section of the multiview config. A share
520
+ `p` of the sets are real, the rest synthetic sets from the run's own train data:
521
+
522
+ ```yaml
523
+ # in the multiview config (a copy of configs/xview.yaml), next to its other keys
524
+ real:
525
+ json: datasets/my_subjects/annotations/train.json # default: the run's train data
526
+ images: datasets/my_subjects/images
527
+ val_json: datasets/my_subjects/annotations/val.json # real validation sets; best.pt is chosen on them
528
+ val_images: datasets/my_subjects/images # default: images
529
+ p: 0.5 # share of the training sets that are real (1 = real only)
530
+ sets: # eomt.data.subjects.SubjectSetConfig
531
+ max_views: 4
532
+ sizes: {2: 0.2, 3: 0.2, 4: 0.6} # set sizes (capped by the subject's photos)
533
+ p_single: 0.0 # sets of the anchor photo alone
534
+ p_shared: 0.5 # companions sharing a linked instance with the anchor first
535
+ ```
536
+
537
+ Every photo of a subject that trains is the first photo of one set per epoch, with companions
538
+ from the same subject. Each photo is augmented on its own, but the horizontal flip is drawn
539
+ once per set, so left and right never mix within a subject. With real validation sets
540
+ (`val_json`; without `json`, the run's val data when its images have a `subject_id`),
541
+ `best.pt` is chosen on `val/real/segm/mAP_set`: every fully annotated photo of each fixed set,
542
+ unaugmented (fitted to the input) and predicted with its set (`_alone` next to it), and the
543
+ links are scored against the annotated instance ids (`val/real/match/*`; a detection that is no
544
+ annotated instance in a photo not fully annotated, or lies in a crowd region, has no known link
545
+ and is left out). The synthetic sets can also take other photos of the same
546
+ subject as companions (`sets.fill: {subject: 1.0}`, `p_subject`); their instances are then not
547
+ linked. `eomt.data.subjects_from_file_names` sets `subject_id` from file names that start with
548
+ the subject (`<subject>_...`).
549
+
486
550
  ---
487
551
 
488
552
  ## Install
@@ -443,6 +443,70 @@ them one by one); `"partition"` groups similar photos (mean patch token of a sma
443
443
  other photos of the subject, not a particular one. `scripts/predict.py --subject [MODE]` and
444
444
  `predict(subject=MODE)` take the mode (`--subject` alone is `"order"`).
445
445
 
446
+ ### Real multi-photo datasets
447
+
448
+ Synthetic sets need no multi-photo annotations, but they show no real viewpoint change. With
449
+ annotated photos of the same subjects, the post-training also draws **real sets**: several
450
+ photos of one subject, each predicted with the others, the instances linked across them. The
451
+ data is a COCO instance-segmentation file like any other, with four optional additions
452
+ ([`eomt/data/subjects.py`](eomt/data/subjects.py)):
453
+
454
+ ```jsonc
455
+ "images": [
456
+ {"id": 1, "file_name": "subject_42/front.jpg", "subject_id": "subject_42"}, // a photo of subject_42
457
+ {"id": 2, "file_name": "subject_42/closeup.jpg", "subject_id": "subject_42", "supervision": "positives"},
458
+ {"id": 3, "file_name": "subject_42/side.jpg", "subject_id": "subject_42", "supervision": "none"}
459
+ ],
460
+ "annotations": [
461
+ {"id": 10, "image_id": 1, "category_id": 3, "instance_id": 7, ...}, // the same physical instance ...
462
+ {"id": 11, "image_id": 2, "category_id": 3, "instance_id": 7, ...}, // ... in another photo of subject_42
463
+ {"id": 12, "image_id": 1, "category_id": 5, ...}, // not linked to the other photos
464
+ {"id": 13, "image_id": 3, "category_id": 3, "iscrowd": 1, ...} // a region to leave out of the loss
465
+ ]
466
+ ```
467
+
468
+ | key | meaning |
469
+ |-----|---------|
470
+ | image `subject_id` | photos with the same id show the same subject; photos without one take no part in the real sets |
471
+ | image `supervision` | `full` (default): every instance is annotated, the rest is background. `positives`: only some are; nothing unannotated is taught as background (the photo's unmatched queries take no "no object" loss). `none`: input only for the other photos of its set |
472
+ | annotation `instance_id` | the same physical instance in every photo of the subject that shows it (a number or string); the matching head learns those links. Absent: linked to nothing |
473
+ | annotation `iscrowd: 1` | unsure pixels: a query whose mask lies mostly inside takes no "no object" loss, and validation drops detections there (single-photo training already skips these annotations) |
474
+
475
+ Partly annotated photos are what pseudo-labelling gives: labels that list some instances per
476
+ photo, or say which photos show an instance but not where. The loss then trains on what is
477
+ known and leaves the rest out, instead of teaching it as background.
478
+
479
+ Real sets join the post-training through the `real` section of the multiview config. A share
480
+ `p` of the sets are real, the rest synthetic sets from the run's own train data:
481
+
482
+ ```yaml
483
+ # in the multiview config (a copy of configs/xview.yaml), next to its other keys
484
+ real:
485
+ json: datasets/my_subjects/annotations/train.json # default: the run's train data
486
+ images: datasets/my_subjects/images
487
+ val_json: datasets/my_subjects/annotations/val.json # real validation sets; best.pt is chosen on them
488
+ val_images: datasets/my_subjects/images # default: images
489
+ p: 0.5 # share of the training sets that are real (1 = real only)
490
+ sets: # eomt.data.subjects.SubjectSetConfig
491
+ max_views: 4
492
+ sizes: {2: 0.2, 3: 0.2, 4: 0.6} # set sizes (capped by the subject's photos)
493
+ p_single: 0.0 # sets of the anchor photo alone
494
+ p_shared: 0.5 # companions sharing a linked instance with the anchor first
495
+ ```
496
+
497
+ Every photo of a subject that trains is the first photo of one set per epoch, with companions
498
+ from the same subject. Each photo is augmented on its own, but the horizontal flip is drawn
499
+ once per set, so left and right never mix within a subject. With real validation sets
500
+ (`val_json`; without `json`, the run's val data when its images have a `subject_id`),
501
+ `best.pt` is chosen on `val/real/segm/mAP_set`: every fully annotated photo of each fixed set,
502
+ unaugmented (fitted to the input) and predicted with its set (`_alone` next to it), and the
503
+ links are scored against the annotated instance ids (`val/real/match/*`; a detection that is no
504
+ annotated instance in a photo not fully annotated, or lies in a crowd region, has no known link
505
+ and is left out). The synthetic sets can also take other photos of the same
506
+ subject as companions (`sets.fill: {subject: 1.0}`, `p_subject`); their instances are then not
507
+ linked. `eomt.data.subjects_from_file_names` sets `subject_id` from file names that start with
508
+ the subject (`<subject>_...`).
509
+
446
510
  ---
447
511
 
448
512
  ## Install
@@ -195,6 +195,8 @@ def match_loss(out: dict, indices, inst_ids: list[torch.Tensor], set_ids: torch.
195
195
  every other matched query of the set (in any of its photos) is a negative. Each query with a positive is an anchor:
196
196
  ``-log`` of the softmax mass (temperature ``tau``) its positives take among all its candidates (supervised InfoNCE).
197
197
  ``indices`` is the query->target matching (gated as for the attribute heads); returns 0 when nothing pairs up.
198
+ Targets with a negative id (another photo of the subject, which of its instances are which unknown,
199
+ :data:`eomt.data.sets.UNKNOWN_IDS`) are neither anchors nor candidates.
198
200
  """
199
201
  emb = out["match_embed"]
200
202
  feats, ids, photo, sets = [], [], [], []
@@ -207,6 +209,10 @@ def match_loss(out: dict, indices, inst_ids: list[torch.Tensor], set_ids: torch.
207
209
  if not feats:
208
210
  return emb.sum() * 0.0
209
211
  f, ids, photo, sets = torch.cat(feats), torch.cat(ids), torch.cat(photo), torch.cat(sets)
212
+ known = ids >= 0
213
+ if not known.any():
214
+ return emb.sum() * 0.0
215
+ f, ids, photo, sets = f[known], ids[known], photo[known], sets[known]
210
216
  sim = (f @ f.T) / tau
211
217
  cand = (sets[:, None] == sets[None]) & ~torch.eye(len(f), dtype=torch.bool, device=f.device)
212
218
  pos = cand & (ids[:, None] == ids[None]) & (photo[:, None] != photo[None])
@@ -218,6 +224,29 @@ def match_loss(out: dict, indices, inst_ids: list[torch.Tensor], set_ids: torch.
218
224
  return (sim.masked_fill(~cand, neg_inf).logsumexp(1) - sim.masked_fill(~pos, neg_inf).logsumexp(1)).mean()
219
225
 
220
226
 
227
+ def harm_loss(out: dict, alone: dict, indices, class_labels: list[torch.Tensor], set_ids: torch.Tensor):
228
+ """Do-no-harm loss of the cross-view post-training: how much predicting a photo with the other photos of its set
229
+ lowers the probability of a true instance's class below predicting it alone, hinged at 0 (the others may raise it,
230
+ never lower it). ``alone`` is the forward of the same photos each in its own set (with the checkpoint frozen, its
231
+ own prediction); ``indices`` the query->target matching of ``out``. Mean over the matched queries of the photos in
232
+ sets of several; 0 when there are none.
233
+
234
+ NOTE: what is lost to a lowered true instance downstream (an FP filter can drop false detections, not bring back a
235
+ true one) is not what is gained by a lowered false one, so only the true instances are held to their score alone.
236
+ """
237
+ sizes = torch.bincount(set_ids.cpu())
238
+ drops = []
239
+ for b, (src, tgt) in enumerate(indices):
240
+ if src.numel() and sizes[int(set_ids[b])] > 1:
241
+ cls = class_labels[b][tgt.to(class_labels[b].device)].to(out["class_queries_logits"].device)[:, None]
242
+ p = out["class_queries_logits"][b, src].float().softmax(-1).gather(1, cls)[:, 0]
243
+ p_alone = alone["class_queries_logits"][b, src].float().softmax(-1).gather(1, cls)[:, 0]
244
+ drops.append((p_alone - p).clamp(min=0))
245
+ if not drops:
246
+ return out["class_queries_logits"].sum() * 0.0
247
+ return torch.cat(drops).mean()
248
+
249
+
221
250
  @torch.no_grad()
222
251
  def aux_accuracy(
223
252
  model,
@@ -10,6 +10,7 @@ from .coco import (
10
10
  from .config import load_data_config
11
11
  from .download import ensure_coco
12
12
  from .sets import CocoViewSets, SetConfig, collate_sets
13
+ from .subjects import CocoSubjectSets, MixedSets, SubjectSetConfig, subjects_from_file_names
13
14
  from .transforms import AugConfig, TrainAugment, build_train_transform, build_val_transform
14
15
 
15
16
  __all__ = [
@@ -19,7 +20,11 @@ __all__ = [
19
20
  "CocoInstanceSeg",
20
21
  "CocoValImages",
21
22
  "CocoViewSets",
23
+ "CocoSubjectSets",
24
+ "MixedSets",
22
25
  "SetConfig",
26
+ "SubjectSetConfig",
27
+ "subjects_from_file_names",
23
28
  "collate_sets",
24
29
  "collate_train",
25
30
  "collate_val",
@@ -18,13 +18,13 @@ optional::
18
18
  attributes: # the per-instance heads to train (an attribute of the data left out is not) and how
19
19
  laterality: {flip_aware: {left: right}} # each one learns (eomt.data.coco.BEHAVIOR_KEYS); without the
20
20
  area: {log: true, range: [0, 50000], crop: scale} # section, every attribute as the data declares it
21
- typology:
22
- aug: # AugConfig fields (``train_aug``, the older name, is the same)
21
+ pose:
22
+ aug: # AugConfig fields (``train_aug``, the older name, is the same)
23
23
  min_scale: 0.6
24
24
  instance_crop_prob: 0.8
25
25
  train: # train() keywords: epochs, imgsz, lr0, init_weights, project, name, hires_epochs...
26
26
  epochs: 20
27
- init_weights: ../runs/parts/weights/best.pt
27
+ init_weights: ../runs/base/weights/best.pt
28
28
  inference: # saved in every checkpoint; the defaults of predict() / track() with that model
29
29
  conf_thres: 0.25
30
30
 
@@ -27,6 +27,16 @@ are other instances (ids offset by :data:`DISTRACTOR_IDS` / :data:`FLIPPED_IDS`)
27
27
  on the other side are not the same instance. The horizontal flip is drawn once per set and applied to every view of
28
28
  the photo (the mirrored copy takes the other one), with the flip-aware attributes (e.g. left/right) swapped as in
29
29
  single-photo training. A share of the sets are single photos, so the single-photo behaviour is kept in training.
30
+
31
+ With ``SetConfig.sizes`` a set's size is drawn instead, and the views after A and B **fill** it (``SetConfig.fill``):
32
+ another view of the photo's instances (**positive**), another part of the photo without them (**elsewhere**), another
33
+ annotated photo of the same **subject** (the images' ``subject_id``, :mod:`eomt.data.subjects`: in a product every
34
+ photo of a set shows the same subject, often other parts of it), the mirrored copy or a distractor. The instances of
35
+ another photo of the subject are each annotated in that photo, but which of them are A's is not known here: their ids
36
+ are negative (:data:`UNKNOWN_IDS`), so they train every head but stay out of the matching head's loss and links.
37
+ ``p_subject`` draws the set's photo among those whose subject has other annotated photos. Real sets, several photos of
38
+ a subject each predicted with the others and with the instances linked across them, are
39
+ :class:`eomt.data.subjects.CocoSubjectSets`.
30
40
  """
31
41
 
32
42
  from __future__ import annotations
@@ -43,6 +53,11 @@ from .transforms import _MEAN, _STD, AugConfig, TrainAugment, _coin, _fraction,
43
53
 
44
54
  #: Instance-id offsets of the views that do not show the set's photo: their instances are other instances.
45
55
  DISTRACTOR_IDS, FLIPPED_IDS = 10_000, 20_000
56
+ #: Instance-id offset of a view whose instances are not linked to the set's others (another photo of the subject):
57
+ #: its ids are negative and the matching head leaves them out (each such view takes its own block of ids below it).
58
+ UNKNOWN_IDS = -100_000
59
+ #: The views that can fill a set beyond A and B (``SetConfig.fill``).
60
+ FILLS = ("positive", "elsewhere", "subject", "flipped", "distractor")
46
61
 
47
62
  #: View role -> :class:`~eomt.data.transforms.AugConfig` overrides of the base recipe. The scales are relative to the
48
63
  #: photo fitted to the input, i.e. 1.0 is what inference sees.
@@ -69,6 +84,13 @@ CASES: dict[str, tuple[str, str]] = {
69
84
  }
70
85
 
71
86
 
87
+ def _draw(weights: dict):
88
+ """A key of ``weights`` drawn in proportion to its weight."""
89
+ keys = list(weights)
90
+ cdf = np.cumsum([weights[k] for k in keys]) / sum(weights.values())
91
+ return keys[min(int(np.searchsorted(cdf, _rand())), len(keys) - 1)]
92
+
93
+
72
94
  @dataclass
73
95
  class SetConfig:
74
96
  """How the sets are drawn: at most ``max_views`` photos; ``p_single`` single photos; the cases' relative weights;
@@ -78,7 +100,13 @@ class SetConfig:
78
100
  ``focus`` names the instances of a **locate** case (a class and attribute categories, e.g. ``{"class": "bird",
79
101
  "pose": "flying"}``): with probability ``p_focus`` a set of
80
102
  several photos is drawn from a photo with such an instance, A being the photo shrunk (the instance small) and B a
81
- close-up of that instance, so that A learns to find and place what only B shows clearly."""
103
+ close-up of that instance, so that A learns to find and place what only B shows clearly.
104
+
105
+ ``sizes`` (``{photos: weight}``, 2 to ``max_views``) draws the size of each set of several photos, filled beyond A
106
+ and B by the views of ``fill`` (``{kind: weight}``, kinds :data:`FILLS`; a ``subject`` view falls back to
107
+ ``elsewhere`` when the subject has no other photo); ``p_distractor`` and ``p_flipped_copy`` then play no part.
108
+ Without ``sizes`` the sets grow by those two coins as before. ``p_subject`` draws the photo of a set of several
109
+ among those whose subject (the images' ``subject_id``) has other annotated photos."""
82
110
 
83
111
  max_views: int = 4
84
112
  p_single: float = 0.3
@@ -89,6 +117,9 @@ class SetConfig:
89
117
  occluder_cover: tuple[float, float] = (0.3, 0.7)
90
118
  focus: dict | None = None
91
119
  p_focus: float = 0.0
120
+ sizes: dict | None = None
121
+ fill: dict[str, float] = field(default_factory=lambda: {"positive": 1.0, "elsewhere": 1.0, "subject": 1.0})
122
+ p_subject: float = 0.0
92
123
 
93
124
  def __post_init__(self) -> None:
94
125
  unknown = set(self.cases) - set(CASES)
@@ -97,6 +128,15 @@ class SetConfig:
97
128
  if self.p_focus > 0 and not (self.focus and "class" in self.focus):
98
129
  raise ValueError("SetConfig: p_focus > 0 needs focus with a 'class'")
99
130
  self.occluder_cover = tuple(self.occluder_cover)
131
+ if self.sizes is not None:
132
+ self.sizes = {int(n): float(w) for n, w in self.sizes.items()}
133
+ if not self.sizes or any(not 2 <= n <= self.max_views for n in self.sizes) or sum(self.sizes.values()) <= 0:
134
+ raise ValueError(f"SetConfig: sizes {self.sizes} must weigh set sizes from 2 to max_views")
135
+ bad = set(self.fill) - set(FILLS)
136
+ if bad or sum(self.fill.values()) <= 0:
137
+ raise ValueError(f"SetConfig: fill kinds {sorted(bad)} not in {FILLS}, or no positive weight"
138
+ + (" (the 'case' fill is now 'subject', read from the images' subject_id)"
139
+ if "case" in bad else ""))
100
140
 
101
141
 
102
142
  class CocoViewSets(CocoInstanceSeg):
@@ -124,6 +164,16 @@ class CocoViewSets(CocoInstanceSeg):
124
164
  self._focus_idx = [i for i, img_id in enumerate(self.ids) if self._has_focus(img_id)]
125
165
  if not self._focus_idx:
126
166
  raise ValueError(f"SetConfig.focus {self.sets.focus}: no photo has such an instance")
167
+ # The photos of each subject (the images' subject_id), for the `subject` views and p_subject
168
+ self._subject_of: dict[int, list[int]] = {}
169
+ if self.sets.p_subject > 0 or (self.sets.sizes and self.sets.fill.get("subject")):
170
+ members: dict = {}
171
+ for i, img_id in enumerate(self.ids):
172
+ subject = self.coco.loadImgs(img_id)[0].get("subject_id")
173
+ if subject is not None:
174
+ members.setdefault(subject, []).append(i)
175
+ self._subject_of = {i: m for m in members.values() if len(m) > 1 for i in m}
176
+ self._subject_idx = sorted(self._subject_of)
127
177
 
128
178
  def _focus_rule(self, focus: dict) -> tuple[int, dict[str, int]]:
129
179
  """``focus`` as (contiguous class, {attribute: contiguous category})."""
@@ -172,15 +222,20 @@ class CocoViewSets(CocoInstanceSeg):
172
222
  case = "locate"
173
223
  views = [self._view(raw, "small", flip, need=True), self._view(raw, "zoom_focus", flip, focus=True)]
174
224
  else:
225
+ if self._subject_idx and _coin(c.p_subject):
226
+ idx = self._subject_idx[_randint(0, len(self._subject_idx) - 1)]
175
227
  raw = self._load_raw(idx)
176
- names = list(c.cases)
177
- cdf = np.cumsum([c.cases[n] for n in names]) / sum(c.cases.values())
178
- case = names[min(int(np.searchsorted(cdf, _rand())), len(names) - 1)]
228
+ case = _draw(c.cases)
179
229
  role_a, role_b = CASES[case]
180
230
  views = [
181
231
  self._view(raw, role_a, flip, need=True, occlude=case == "occluded"),
182
232
  self._view(raw, "elsewhere" if _coin(c.p_elsewhere) else role_b, flip),
183
233
  ]
234
+ if c.sizes:
235
+ size = _draw(c.sizes)
236
+ while len(views) < size:
237
+ views.append(self._fill(raw, idx, flip, len(views)))
238
+ return {"views": views, "case": case}
184
239
  if len(views) < c.max_views and len(self.ids) > 1 and _coin(c.p_distractor):
185
240
  views.append(self._view(self._load_raw(self._other(idx)), "context", _coin(self.aug.flip_prob), DISTRACTOR_IDS))
186
241
  if len(views) < c.max_views and _coin(c.p_flipped_copy):
@@ -191,6 +246,27 @@ class CocoViewSets(CocoInstanceSeg):
191
246
  j = _randint(0, len(self.ids) - 2)
192
247
  return j + (j >= idx)
193
248
 
249
+ def _fill(self, raw, idx: int, flip: bool, slot: int):
250
+ """The view in position ``slot`` of a set filled to its drawn size (``SetConfig.fill``): another view of the
251
+ photo's instances, another part of the photo without them, another photo of its subject (flipped with the set:
252
+ left and right of one subject never mix), the mirrored copy or a distractor (each distractor its own block of
253
+ ids: two distractors are two other subjects)."""
254
+ kind = _draw(self.sets.fill)
255
+ if kind == "subject":
256
+ others = [j for j in self._subject_of.get(idx, ()) if j != idx]
257
+ if others:
258
+ j = others[_randint(0, len(others) - 1)]
259
+ return self._view(self._load_raw(j), "context", flip, UNKNOWN_IDS * slot)
260
+ kind = "elsewhere"
261
+ if kind == "positive":
262
+ return self._view(raw, "zoom" if _coin(0.5) else "context", flip)
263
+ if kind == "elsewhere":
264
+ return self._view(raw, "elsewhere", flip)
265
+ if kind == "flipped":
266
+ return self._view(raw, "context", not flip, FLIPPED_IDS)
267
+ return self._view(self._load_raw(self._other(idx)), "context", _coin(self.aug.flip_prob),
268
+ DISTRACTOR_IDS + 1000 * slot)
269
+
194
270
  def _view(self, raw, role: str, flip: bool, offset: int = 0, *, need: bool = False, occlude: bool = False,
195
271
  focus: bool = False):
196
272
  """One view of a raw sample: ``(image, masks, classes, attrs, inst_ids)`` of the instances it shows. ``need``
@@ -258,8 +334,11 @@ class CocoViewSets(CocoInstanceSeg):
258
334
 
259
335
  def collate_sets(batch: list[dict]):
260
336
  """Flatten a batch of sets into one batch of photos: ``(pixel_values, mask_labels, class_labels, aux_labels,
261
- set_ids, inst_ids)``, where ``set_ids[b]`` is the set of photo ``b`` and ``inst_ids[b]`` the instance ids of its
262
- targets."""
337
+ set_ids, inst_ids, extras)``, where ``set_ids[b]`` is the set of photo ``b``, ``inst_ids[b]`` the instance ids of
338
+ its targets and ``extras`` the partial-label inputs of the real sets (:func:`eomt.data.subjects.collate_extras`:
339
+ ignore maps and "no object" weights), None when no set of the batch has any."""
340
+ from .subjects import collate_extras
341
+
263
342
  views = [(s, v) for s, item in enumerate(batch) for v in item["views"]]
264
343
  names = list(views[0][1][3])
265
344
  return (
@@ -269,4 +348,5 @@ def collate_sets(batch: list[dict]):
269
348
  {n: [v[3][n] for _, v in views] for n in names},
270
349
  torch.tensor([s for s, _ in views]),
271
350
  [v[4] for _, v in views],
351
+ collate_extras(batch),
272
352
  )