├── external └── .DS_Store ├── assets ├── primaps_examples.png └── demo_examples │ ├── coco_example.jpg │ ├── potsdam_example.png │ └── cityscapes_example.png ├── datasets ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── __init__.cpython-37.pyc │ ├── __init__.cpython-38.pyc │ ├── __init__.cpython-39.pyc │ ├── potsdam.cpython-310.pyc │ ├── potsdam.cpython-311.pyc │ ├── potsdam.cpython-36.pyc │ ├── potsdam.cpython-37.pyc │ ├── potsdam.cpython-38.pyc │ ├── potsdam.cpython-39.pyc │ ├── __init__.cpython-310.pyc │ ├── __init__.cpython-311.pyc │ ├── cityscapes.cpython-36.pyc │ ├── cityscapes.cpython-37.pyc │ ├── cityscapes.cpython-38.pyc │ ├── cityscapes.cpython-39.pyc │ ├── cocostuff.cpython-310.pyc │ ├── cocostuff.cpython-311.pyc │ ├── cocostuff.cpython-36.pyc │ ├── cocostuff.cpython-37.pyc │ ├── cocostuff.cpython-38.pyc │ ├── cocostuff.cpython-39.pyc │ ├── cityscapes.cpython-310.pyc │ ├── cityscapes.cpython-311.pyc │ ├── precomputed.cpython-310.pyc │ ├── precomputed.cpython-311.pyc │ ├── precomputed.cpython-36.pyc │ ├── precomputed.cpython-37.pyc │ ├── precomputed.cpython-38.pyc │ └── precomputed.cpython-39.pyc ├── __init__.py ├── precomputed.py ├── cityscapes.py ├── potsdam.py └── cocostuff.py ├── primaps_modules ├── __pycache__ │ ├── crf.cpython-36.pyc │ ├── crf.cpython-37.pyc │ ├── crf.cpython-38.pyc │ ├── crf.cpython-39.pyc │ ├── ema.cpython-36.pyc │ ├── ema.cpython-38.pyc │ ├── ema.cpython-39.pyc │ ├── crf.cpython-310.pyc │ ├── crf.cpython-311.pyc │ ├── ema.cpython-311.pyc │ ├── pamr.cpython-36.pyc │ ├── parser.cpython-36.pyc │ ├── maskprop.cpython-36.pyc │ ├── maskprop.cpython-38.pyc │ ├── maskprop.cpython-39.pyc │ ├── metrics.cpython-311.pyc │ ├── metrics.cpython-36.pyc │ ├── parser.cpython-311.pyc │ ├── primaps.cpython-310.pyc │ ├── primaps.cpython-311.pyc │ ├── primaps.cpython-36.pyc │ ├── primaps.cpython-37.pyc │ ├── clustering.cpython-310.pyc │ ├── clustering.cpython-311.pyc │ ├── clustering.cpython-36.pyc │ ├── clustering.cpython-38.pyc │ ├── clustering.cpython-39.pyc │ ├── maskprop.cpython-310.pyc │ ├── median_pool.cpython-36.pyc │ ├── median_pool.cpython-37.pyc │ ├── median_pool.cpython-39.pyc │ ├── transforms.cpython-310.pyc │ ├── transforms.cpython-311.pyc │ ├── transforms.cpython-36.pyc │ ├── transforms.cpython-37.pyc │ ├── median_pool.cpython-310.pyc │ ├── median_pool.cpython-311.pyc │ ├── visualization.cpython-36.pyc │ ├── visualization.cpython-37.pyc │ ├── visualization.cpython-310.pyc │ ├── visualization.cpython-311.pyc │ └── gansbeke_batched_crf.cpython-36.pyc ├── backbone │ ├── __pycache__ │ │ ├── dinovit.cpython-36.pyc │ │ ├── resnet.cpython-36.pyc │ │ └── __init__.cpython-36.pyc │ └── dino │ │ ├── __pycache__ │ │ ├── dinovit.cpython-36.pyc │ │ ├── dinovit.cpython-37.pyc │ │ ├── dinovit.cpython-38.pyc │ │ ├── dinovit.cpython-39.pyc │ │ ├── utils.cpython-310.pyc │ │ ├── utils.cpython-311.pyc │ │ ├── utils.cpython-36.pyc │ │ ├── utils.cpython-37.pyc │ │ ├── utils.cpython-38.pyc │ │ ├── utils.cpython-39.pyc │ │ ├── dinovit.cpython-310.pyc │ │ ├── dinovit.cpython-311.pyc │ │ ├── vision_transformer.cpython-310.pyc │ │ ├── vision_transformer.cpython-311.pyc │ │ ├── vision_transformer.cpython-36.pyc │ │ ├── vision_transformer.cpython-37.pyc │ │ ├── vision_transformer.cpython-38.pyc │ │ └── vision_transformer.cpython-39.pyc │ │ ├── dinovit.py │ │ ├── vision_transformer.py │ │ └── utils.py ├── clustering.py ├── crf.py ├── median_pool.py ├── primaps.py ├── metrics.py ├── parser.py ├── ema.py ├── transforms.py └── visualization.py ├── requirements.txt ├── experiments.sh ├── demo.py ├── test.py ├── README.md ├── LICENSE └── train.py /external/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/external/.DS_Store -------------------------------------------------------------------------------- /assets/primaps_examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/assets/primaps_examples.png -------------------------------------------------------------------------------- /assets/demo_examples/coco_example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/assets/demo_examples/coco_example.jpg -------------------------------------------------------------------------------- /assets/demo_examples/potsdam_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/assets/demo_examples/potsdam_example.png -------------------------------------------------------------------------------- /assets/demo_examples/cityscapes_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/assets/demo_examples/cityscapes_example.png -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-310.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-311.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-36.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-38.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/potsdam.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/potsdam.cpython-39.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/__init__.cpython-311.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-36.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-38.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-39.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-310.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-311.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-36.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-38.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cocostuff.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cocostuff.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/ema.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/ema.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/ema.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/ema.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/ema.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/ema.cpython-39.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-310.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/cityscapes.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/cityscapes.cpython-311.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-310.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-311.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-36.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-38.pyc -------------------------------------------------------------------------------- /datasets/__pycache__/precomputed.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/datasets/__pycache__/precomputed.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/crf.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/crf.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/ema.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/ema.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/pamr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/pamr.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/parser.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/parser.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/maskprop.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/maskprop.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/maskprop.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/maskprop.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/maskprop.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/maskprop.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/metrics.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/metrics.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/metrics.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/metrics.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/parser.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/parser.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/primaps.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/primaps.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/primaps.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/primaps.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/primaps.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/primaps.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/primaps.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/primaps.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/clustering.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/clustering.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/clustering.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/clustering.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/clustering.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/clustering.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/clustering.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/clustering.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/clustering.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/clustering.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/maskprop.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/maskprop.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/median_pool.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/median_pool.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/median_pool.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/median_pool.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/median_pool.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/median_pool.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/transforms.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/transforms.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/transforms.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/transforms.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/transforms.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/transforms.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/transforms.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/transforms.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/median_pool.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/median_pool.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/median_pool.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/median_pool.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/visualization.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/visualization.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/visualization.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/visualization.cpython-37.pyc -------------------------------------------------------------------------------- /datasets/__init__.py: -------------------------------------------------------------------------------- 1 | from datasets.cityscapes import * 2 | from datasets.cocostuff import * 3 | from datasets.potsdam import * 4 | from datasets.precomputed import * -------------------------------------------------------------------------------- /primaps_modules/__pycache__/visualization.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/visualization.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/visualization.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/visualization.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/__pycache__/dinovit.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/__pycache__/dinovit.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/__pycache__/resnet.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/__pycache__/resnet.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/__pycache__/gansbeke_batched_crf.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/__pycache__/gansbeke_batched_crf.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/utils.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/utils.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/dinovit.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/dinovit.cpython-311.pyc -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cityscapesScripts==2.2.1 2 | matplotlib==3.3.4 3 | numpy==1.19.5 4 | pytorch-lightning==1.5.10 5 | scipy==1.5.4 6 | tqdm==4.59.0 7 | wget 8 | hydra-core 9 | seaborn -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-310.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-311.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-36.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-37.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-38.pyc -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/visinf/primaps/HEAD/primaps_modules/backbone/dino/__pycache__/vision_transformer.cpython-39.pyc -------------------------------------------------------------------------------- /primaps_modules/clustering.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | 6 | # k-means clustering loss 7 | class ClusterLoss(nn.Module): 8 | def __init__(self): 9 | super(ClusterLoss, self).__init__() 10 | 11 | def forward(self, inner_products): 12 | cluster_probs = F.one_hot(torch.argmax(inner_products, dim=1), inner_products.shape[1]).permute(0, 3, 1, 2).to(torch.float64) 13 | cluster_loss = -(cluster_probs * inner_products).sum(1).mean() 14 | return cluster_loss, cluster_probs 15 | 16 | 17 | # cosine similarity clustering layer 18 | class ConvClusterProbe(nn.Module): 19 | def __init__(self, in_channels, out_channels, not_norm=False): 20 | super(ConvClusterProbe, self).__init__() 21 | print('-- Clusterer init') 22 | self.not_norm = not_norm 23 | self.cluster_centers = nn.utils.weight_norm(nn.Conv2d(in_channels, out_channels, (1, 1), bias=False), name='weight', dim=0) 24 | 25 | def forward(self, x): 26 | if not self.not_norm: 27 | x = F.normalize(x, dim=1) 28 | self.cluster_centers.weight_g = torch.nn.Parameter(torch.ones_like(self.cluster_centers.weight_g)) 29 | return self.cluster_centers(x) -------------------------------------------------------------------------------- /experiments.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | 4 | name='reproduce_main_results' 5 | 6 | # Precompute PriMaPs pseudo labels 7 | python train.py --precomp-primaps --threshold 0.4 --dataset-root /path/to/dataset --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 8 --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --log-name $name --gpu-ids 0 8 | 9 | # Get initialization checkpoint 10 | python train.py --pcainit --dataset-root /path/to/dataset --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --train-state baseline --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 2 --linear-lr 5e-3 --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --log-name $name --gpu-ids 0 11 | 12 | # Optimize class prototypes with PriMaPs pseudo labels 13 | primaps='/path/to/pseudo/labels/' 14 | init_checkpoint='/path/to/checkpoint/last.ckpt' 15 | 16 | python train.py --log-name $name --cluster-ckpt-path $init_checkpoint --student-augs --dataset-root /path/to/dataset --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 50 --linear-lr 5e-3 --ema-update-step 10 --ema-decay 0.98 --precomp-primaps-root $primaps --seghead-lr 5e-3 --seghead-arch 'linear' --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --gpu-ids 0 -------------------------------------------------------------------------------- /datasets/precomputed.py: -------------------------------------------------------------------------------- 1 | import os 2 | from PIL import Image 3 | from torch.utils.data import Dataset 4 | 5 | 6 | class PrecomputedDataset(Dataset): 7 | def __init__(self, 8 | root, 9 | transforms, 10 | student_augs, 11 | ): 12 | super(PrecomputedDataset, self).__init__() 13 | self.root = root 14 | self.transforms = transforms 15 | self.student_augs = student_augs 16 | 17 | self.image_files = [] 18 | self.label_files = [] 19 | self.pseudo_files = [] 20 | for file in os.listdir(os.path.join(self.root, 'imgs')): 21 | self.image_files.append(os.path.join(self.root, 'imgs', file)) 22 | self.label_files.append(os.path.join(self.root, 'gts', file)) 23 | self.pseudo_files.append(os.path.join(self.root, 'pseudos', file)) 24 | 25 | 26 | def __getitem__(self, index): 27 | image_path = self.image_files[index] 28 | label_path = self.label_files[index] 29 | pseudo_path = self.pseudo_files[index] 30 | 31 | img = Image.open(image_path).convert("RGB") 32 | label = Image.open(label_path) 33 | pseudo = Image.open(pseudo_path) 34 | 35 | if self.student_augs: 36 | img, label, aimg, pseudo = self.transforms(img, label, pseudo) 37 | return img, label.long(), aimg, pseudo.long() 38 | else: 39 | img, label, pseudo = self.transforms(img, label, pseudo) 40 | return img, label.long(), pseudo.long() 41 | 42 | def __len__(self): 43 | return len(self.image_files) -------------------------------------------------------------------------------- /primaps_modules/crf.py: -------------------------------------------------------------------------------- 1 | # 2 | # Authors: Wouter Van Gansbeke & Simon Vandenhende 3 | # Licensed under the CC BY-NC 4.0 license (https://creativecommons.org/licenses/by-nc/4.0/) 4 | 5 | import sys 6 | import os 7 | import numpy as np 8 | import pydensecrf.densecrf as dcrf 9 | import pydensecrf.utils as utils 10 | import torch 11 | import torch.nn.functional as F 12 | import torchvision.transforms.functional as VF 13 | sys.path.append(os.getcwd()) 14 | from primaps_modules.transforms import UnNormalize as unnorm 15 | 16 | 17 | MAX_ITER = 10 18 | POS_W = 3 19 | POS_XY_STD = 1 20 | Bi_W = 4 21 | Bi_XY_STD = 67 22 | Bi_RGB_STD = 3 23 | BGR_MEAN = np.array([104.008, 116.669, 122.675]) 24 | 25 | 26 | def dense_crf(image_tensor: torch.FloatTensor, output_logits: torch.FloatTensor): 27 | image = np.array(VF.to_pil_image(unnorm()(image_tensor)))[:, :, ::-1] 28 | H, W = image.shape[:2] 29 | image = np.ascontiguousarray(image) 30 | 31 | output_logits = F.interpolate(output_logits.unsqueeze(0), size=(H, W), mode="bilinear", 32 | align_corners=False).squeeze() 33 | output_probs = F.softmax(output_logits, dim=0).cpu().numpy() 34 | 35 | c = output_probs.shape[0] 36 | h = output_probs.shape[1] 37 | w = output_probs.shape[2] 38 | 39 | U = utils.unary_from_softmax(output_probs) 40 | U = np.ascontiguousarray(U) 41 | 42 | d = dcrf.DenseCRF2D(w, h, c) 43 | d.setUnaryEnergy(U) 44 | d.addPairwiseGaussian(sxy=POS_XY_STD, compat=POS_W) 45 | d.addPairwiseBilateral(sxy=Bi_XY_STD, srgb=Bi_RGB_STD, rgbim=image, compat=Bi_W) 46 | 47 | Q = d.inference(MAX_ITER) 48 | Q = np.array(Q).reshape((c, h, w)) 49 | return Q 50 | 51 | 52 | 53 | def _apply_crf(tup): 54 | return dense_crf(tup[0], tup[1]) 55 | 56 | 57 | def batched_crf(pool, img_tensor, prob_tensor): 58 | outputs = pool.map(_apply_crf, zip(img_tensor.detach().cpu(), prob_tensor.detach().cpu())) 59 | return torch.cat([torch.from_numpy(arr).unsqueeze(0) for arr in outputs], dim=0) 60 | 61 | -------------------------------------------------------------------------------- /primaps_modules/median_pool.py: -------------------------------------------------------------------------------- 1 | # Original implementation: https://gist.github.com/rwightman/f2d3849281624be7c0f11c85c87c1598 2 | 3 | import math 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from torch.nn.modules.utils import _pair, _quadruple 8 | 9 | 10 | class MedianPool2d(nn.Module): 11 | """ Median pool (usable as median filter when stride=1) module. 12 | 13 | Args: 14 | kernel_size: size of pooling kernel, int or 2-tuple 15 | stride: pool stride, int or 2-tuple 16 | padding: pool padding, int or 4-tuple (l, r, t, b) as in pytorch F.pad 17 | same: override padding and enforce same padding, boolean 18 | """ 19 | def __init__(self, kernel_size=3, stride=1, padding=0, same=False): 20 | super(MedianPool2d, self).__init__() 21 | self.k = _pair(kernel_size) 22 | self.stride = _pair(stride) 23 | self.padding = _quadruple(padding) # convert to l, r, t, b 24 | self.same = same 25 | 26 | def _padding(self, x): 27 | if self.same: 28 | ih, iw = x.size()[2:] 29 | if ih % self.stride[0] == 0: 30 | ph = max(self.k[0] - self.stride[0], 0) 31 | else: 32 | ph = max(self.k[0] - (ih % self.stride[0]), 0) 33 | if iw % self.stride[1] == 0: 34 | pw = max(self.k[1] - self.stride[1], 0) 35 | else: 36 | pw = max(self.k[1] - (iw % self.stride[1]), 0) 37 | pl = pw // 2 38 | pr = pw - pl 39 | pt = ph // 2 40 | pb = ph - pt 41 | padding = (pl, pr, pt, pb) 42 | else: 43 | padding = self.padding 44 | return padding 45 | 46 | def forward(self, x): 47 | # using existing pytorch functions and tensor ops so that we get autograd, 48 | # would likely be more efficient to implement from scratch at C/Cuda level 49 | x = F.pad(x, self._padding(x), mode='reflect') 50 | x = x.unfold(2, self.k[0], self.stride[0]).unfold(3, self.k[1], self.stride[1]) 51 | x = x.contiguous().view(x.size()[:4] + (-1,)).median(dim=-1)[0] 52 | return x -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | from argparse import ArgumentParser 2 | from typing import Dict 3 | import torch 4 | from PIL import Image 5 | import primaps_modules.transforms as transforms 6 | from primaps_modules.primaps import PriMaPs 7 | from primaps_modules.backbone.dino.dinovit import DinoFeaturizerv2 8 | from primaps_modules.visualization import visualize_demo 9 | # set seeds 10 | torch.manual_seed(0) 11 | torch.cuda.manual_seed(0) 12 | 13 | 14 | 15 | def main(opts: Dict): 16 | ''' 17 | Demo to visualize PriMaPs for a single image. 18 | ''' 19 | # get SLL image encoder and primaps module 20 | net = DinoFeaturizerv2(opts.backbone_arch, opts.backbone_patch) 21 | net.to(opts.device) 22 | primaps_module = PriMaPs(threshold=opts.threshold, 23 | ignore_id=255) 24 | 25 | # get transforms 26 | demo_transforms = transforms.Compose([transforms.ToTensor(), 27 | transforms.Resize(opts.validation_resize), 28 | transforms.CenterCrop([opts.validation_resize[0], opts.validation_resize[0]]), 29 | transforms.Normalize()]) 30 | 31 | 32 | # load image and apply transforms 33 | img = Image.open(opts.image_path) 34 | img, _ = demo_transforms(img, torch.zeros(img.size)) 35 | img.to(opts.device) 36 | # get SSL features 37 | feats = net(img.unsqueeze(0).to(opts.device), n=1).squeeze() 38 | # get primaps pseudo labels 39 | primaps = primaps_module._get_pseudo(img, feats, torch.zeros(img.shape[1:])) 40 | # visualize overlay 41 | Image.fromarray(visualize_demo(img, primaps)).save('demo.png') 42 | print('Image saved as demo.png') 43 | 44 | 45 | if __name__ == '__main__': 46 | parser = ArgumentParser() 47 | parser.add_argument("--backbone-arch", 48 | type=str, 49 | default=['dino_vits', 'dino_vitb', 'dinov2_vits', 'dinov2_vitb'][1], 50 | help='backbone architecture') 51 | parser.add_argument("--backbone-patch", 52 | type=int, 53 | default=[8, 14, 16][0], 54 | help='patch size of the vit backbone') 55 | parser.add_argument("--validation-resize", 56 | nargs='+', 57 | type=int, 58 | default=[[320], [322]][0], 59 | help='resize images to this size') 60 | parser.add_argument("--threshold", 61 | type=float, 62 | default=0.35, 63 | help='primaps threshold') 64 | parser.add_argument("--device", 65 | type=str, 66 | default='cuda:0', 67 | help='device to use') 68 | parser.add_argument("--image-path", 69 | type=str, 70 | default=['assets/demo_examples/IMG_0709.jpg', 'assets/demo_examples/cityscapes_example.png', 'assets/demo_examples/coco_example.jpg', 'assets/demo_examples/potsdam_example.png'][0], 71 | help='path to images') 72 | args = parser.parse_args() 73 | print(args) 74 | main(args) 75 | -------------------------------------------------------------------------------- /primaps_modules/primaps.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import sys 3 | import os 4 | import torch.nn.functional as F 5 | 6 | sys.path.append(os.getcwd()) 7 | from primaps_modules.crf import dense_crf 8 | from primaps_modules.median_pool import MedianPool2d 9 | 10 | 11 | class PriMaPs(): 12 | def __init__(self, 13 | threshold=0.4, 14 | ignore_id=27): 15 | super(PriMaPs, self).__init__() 16 | self.threshold = threshold 17 | self.ignore_id = ignore_id 18 | self.medianfilter = MedianPool2d(kernel_size=3, stride=1, padding=1) 19 | 20 | def _get_pseudo(self, img, feat, cls_prior): 21 | # initialize used pixel mask 22 | mask = torch.ones(feat.shape[-2:]).bool().to(feat.device) 23 | mask_memory = [] 24 | pseudo_masks = [] 25 | # get masks until 95% of features are masked or mask does not change 26 | while ((mask!=1).sum()/mask.numel() < 0.95): 27 | _, _, v = torch.pca_lowrank(feat[:, mask].permute(1, 0), q=3, niter=100) 28 | # cos similarity to to c 29 | sim = torch.einsum("c,cij->ij", v[:, 0], F.normalize(feat, dim=0)) 30 | # refine direction with NN 31 | sim[~mask] = 0 32 | v = F.normalize(feat, dim=0)[:, sim==sim.max()][:, 0] 33 | sim = torch.einsum("c,cij->ij", v, F.normalize(feat, dim=0)) 34 | sim[~mask] = 0 35 | # apply threshhold and norm 36 | sim[sim0]=0 41 | mask_memory.insert(0, mask.clone()) 42 | if mask_memory.__len__() > 3: 43 | mask_memory.pop() 44 | if torch.Tensor([(mask_memory[0]==i).all() for i in mask_memory]).all(): 45 | break 46 | # insert bg mask and stack 47 | pseudo_masks = (self.medianfilter(torch.stack(pseudo_masks, dim=0).unsqueeze(0)).squeeze()*10).clamp(0, 1) 48 | bg = (torch.mean(pseudo_masks[pseudo_masks!=0])*torch.ones(feat.shape[-2:], device=feat.device)-pseudo_masks.sum(dim=0)).unsqueeze(0).clamp(0, 1) 49 | 50 | if (pseudo_masks.shape).__len__() == 2: 51 | pseudo_masks = pseudo_masks.unsqueeze(0) 52 | pseudo_masks = torch.cat([bg, pseudo_masks], dim=0) 53 | pseudo_masks = F.log_softmax(pseudo_masks, dim=0) 54 | # apply crf to refine masks 55 | pseudo_masks = dense_crf(img.squeeze(), pseudo_masks).argmax(0) 56 | pseudo_masks = torch.Tensor(pseudo_masks).to(feat.device) 57 | 58 | if (cls_prior == 0).all(): 59 | pseudolabel = pseudo_masks 60 | pseudolabel[pseudolabel==0] = self.ignore_id 61 | else: 62 | pseudolabel = torch.ones(img.shape[-2:]).to(feat.device)*self.ignore_id 63 | for i in pseudo_masks.unique()[pseudo_masks.unique()!=0]: 64 | # only look at not assigned and attended pixels 65 | mask = (pseudolabel==self.ignore_id)*(pseudo_masks==i) 66 | pseudolabel[mask] = int(torch.mode(cls_prior[mask])[0]) 67 | return pseudolabel 68 | 69 | # multiprocessing wrapper 70 | def _apply_batched_decompose(self, tup): 71 | return self._get_pseudo(tup[0], tup[1], tup[2]) 72 | 73 | def __call__(self, pool, imgs, features, cls_prior): 74 | outs = pool.map(self._apply_batched_decompose, zip(imgs, features, cls_prior)) 75 | return torch.stack(outs, dim=0) -------------------------------------------------------------------------------- /primaps_modules/metrics.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch.multiprocessing 3 | from scipy.optimize import linear_sum_assignment 4 | from torchmetrics import Metric 5 | 6 | 7 | class UnsupervisedMetrics(Metric): 8 | def __init__(self, prefix: str, n_classes: int, extra_clusters: int, compute_hungarian: bool, 9 | dist_sync_on_step=True): 10 | # call `self.add_state`for every internal state that is needed for the metrics computations 11 | # dist_reduce_fx indicates the function that should be used to reduce 12 | # state from multiple processes 13 | super().__init__(dist_sync_on_step=dist_sync_on_step) 14 | 15 | self.n_classes = n_classes 16 | self.extra_clusters = extra_clusters 17 | self.compute_hungarian = compute_hungarian 18 | self.prefix = prefix 19 | self.add_state("stats", 20 | default=torch.zeros(n_classes + self.extra_clusters, n_classes, dtype=torch.int64), 21 | dist_reduce_fx="sum") 22 | 23 | def update(self, preds: torch.Tensor, target: torch.Tensor): 24 | with torch.no_grad(): 25 | actual = target.reshape(-1) 26 | preds = preds.reshape(-1) 27 | mask = (actual >= 0) & (actual < self.n_classes) 28 | actual = actual[mask] 29 | preds = preds[mask] 30 | self.stats += torch.bincount( 31 | (self.n_classes + self.extra_clusters) * actual + preds, 32 | minlength=self.n_classes * (self.n_classes + self.extra_clusters)) \ 33 | .reshape(self.n_classes, self.n_classes + self.extra_clusters).t().to(self.stats.device) 34 | 35 | def map_clusters(self, clusters): 36 | if self.extra_clusters == 0: 37 | return torch.tensor(self.assignments[1])[clusters] 38 | else: 39 | missing = sorted(list(set(range(self.n_classes + self.extra_clusters)) - set(self.assignments[0]))) 40 | cluster_to_class = self.assignments[1] 41 | for missing_entry in missing: 42 | if missing_entry == cluster_to_class.shape[0]: 43 | cluster_to_class = np.append(cluster_to_class, -1) 44 | else: 45 | cluster_to_class = np.insert(cluster_to_class, missing_entry + 1, -1) 46 | cluster_to_class = torch.tensor(cluster_to_class) 47 | return cluster_to_class[clusters] 48 | 49 | def compute(self): 50 | if self.compute_hungarian: 51 | self.assignments = linear_sum_assignment(self.stats.detach().cpu(), maximize=True) 52 | # print(self.assignments) 53 | if self.extra_clusters == 0: 54 | self.histogram = self.stats[np.argsort(self.assignments[1]), :] 55 | if self.extra_clusters > 0: 56 | self.assignments_t = linear_sum_assignment(self.stats.detach().cpu().t(), maximize=True) 57 | histogram = self.stats[self.assignments_t[1], :] 58 | missing = list(set(range(self.n_classes + self.extra_clusters)) - set(self.assignments_t[1])) 59 | 60 | for i in missing: 61 | overlap_class = self.stats[i, :].argmax() 62 | histogram[overlap_class] = histogram[overlap_class] + self.stats[i, :] 63 | self.histogram = histogram 64 | 65 | else: 66 | self.assignments = (torch.arange(self.n_classes).unsqueeze(1), 67 | torch.arange(self.n_classes).unsqueeze(1)) 68 | self.histogram = self.stats 69 | 70 | tp = torch.diag(self.histogram) 71 | fp = torch.sum(self.histogram, dim=0) - tp 72 | fn = torch.sum(self.histogram, dim=1) - tp 73 | 74 | iou = tp / (tp + fp + fn) 75 | prc = tp / (tp + fn) 76 | opc = torch.sum(tp) / torch.sum(self.histogram) 77 | 78 | metric_dict = {self.prefix + "mIoU": iou[~torch.isnan(iou)].mean().item(), 79 | self.prefix + "Class IoUs": np.array(iou.cpu()), 80 | self.prefix + "Accuracy": opc.item()} 81 | return {k: 100 * v for k, v in metric_dict.items()} 82 | -------------------------------------------------------------------------------- /datasets/cityscapes.py: -------------------------------------------------------------------------------- 1 | import torchvision 2 | import numpy as np 3 | from PIL import Image 4 | from typing import List, Any, Callable, Tuple 5 | from collections import namedtuple 6 | 7 | def get_cs_labeldata(): 8 | cls_names = ['road', 'sidewalk', 'parking', 'rail track', 'building', 9 | 'wall', 'fence', 'guard rail', 'bridge', 'tunnel', 10 | 'pole', 'polegroup', 'traffic light', 'traffic sign', 'vegetation', 11 | 'terrain', 'sky', 'person', 'rider', 'car', 12 | 'truck', 'bus', 'caravan', 'trailer', 'train', 13 | 'motorcycle', 'bicycle'] 14 | colormap = np.array([ 15 | [128, 64, 128], 16 | [244, 35, 232], 17 | [250, 170, 160], 18 | [230, 150, 140], 19 | [70, 70, 70], 20 | [102, 102, 156], 21 | [190, 153, 153], 22 | [180, 165, 180], 23 | [150, 100, 100], 24 | [150, 120, 90], 25 | [153, 153, 153], 26 | [153, 153, 153], 27 | [250, 170, 30], 28 | [220, 220, 0], 29 | [107, 142, 35], 30 | [152, 251, 152], 31 | [70, 130, 180], 32 | [220, 20, 60], 33 | [255, 0, 0], 34 | [0, 0, 142], 35 | [0, 0, 70], 36 | [0, 60, 100], 37 | [0, 0, 90], 38 | [0, 0, 110], 39 | [0, 80, 100], 40 | [0, 0, 230], 41 | [119, 11, 32], 42 | [0, 0, 0], 43 | [220, 220, 220]]) 44 | return cls_names, colormap 45 | 46 | class CityscapesDataset(torchvision.datasets.Cityscapes): 47 | 48 | def __init__(self, 49 | transforms: List[Callable], 50 | *args: Any, 51 | **kwargs: Any): 52 | 53 | super(CityscapesDataset, self).__init__(*args, 54 | **kwargs, 55 | target_type="semantic") 56 | self.transforms = transforms 57 | self.classes = ['road', 'sidewalk', 'parking', 'rail track', 'building', 58 | 'wall', 'fence', 'guard rail', 'bridge', 'tunnel', 59 | 'pole', 'polegroup', 'traffic light', 'traffic sign', 'vegetation', 60 | 'terrain', 'sky', 'person', 'rider', 'car', 61 | 'truck', 'bus', 'caravan', 'trailer', 'train', 62 | 'motorcycle', 'bicycle'] 63 | 64 | def __getitem__(self, index: int) -> Tuple[Any, Any]: 65 | """ 66 | Args: 67 | index (int): Index 68 | Returns: 69 | tuple: (image, target) where target is a tuple of all target types if target_type is a list with more 70 | than one item. Otherwise target is a json object if target_type="polygon", else the image segmentation. 71 | """ 72 | img_pth = self.images[index] 73 | image = Image.open(self.images[index]).convert('RGB') 74 | 75 | targets: Any = [] 76 | for i, t in enumerate(self.target_type): 77 | if t == 'polygon': 78 | target = self._load_json(self.targets[index][i]) 79 | else: 80 | target = Image.open(self.targets[index][i]) 81 | 82 | targets.append(target) 83 | 84 | target = tuple(targets) if len(targets) > 1 else targets[0] 85 | 86 | if self.transforms is not None: 87 | image, target = self.transforms(image, target) 88 | 89 | return image, target, img_pth 90 | 91 | def cityscapes(root: str, 92 | split: str, 93 | transforms: List[Callable]): 94 | return CityscapesDataset(root=root, 95 | split=split, 96 | transforms=transforms) 97 | 98 | CityscapesClass = namedtuple('CityscapesClass', ['name', 'id', 'train_id', 'category', 'category_id', 99 | 'has_instances', 'ignore_in_eval', 'color']) 100 | 101 | classes = ['road', 'sidewalk', 'parking', 'rail track', 'building', 102 | 'wall', 'fence', 'guard rail', 'bridge', 'tunnel', 103 | 'pole', 'polegroup', 'traffic light', 'traffic sign', 'vegetation', 104 | 'terrain', 'sky', 'person', 'rider', 'car', 105 | 'truck', 'bus', 'caravan', 'trailer', 'train', 106 | 'motorcycle', 'bicycle'] 107 | -------------------------------------------------------------------------------- /datasets/potsdam.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | from os.path import join 4 | import numpy as np 5 | import torch.multiprocessing 6 | from scipy.io import loadmat 7 | from torchvision.transforms.functional import to_pil_image 8 | from torch.utils.data import Dataset 9 | 10 | def get_pd_labeldata(): 11 | cls_names = ['road', 'building', 'vegetation'] 12 | colormap = np.array([ 13 | [58, 0, 68], #[158, 0, 0],[58, 0, 68], 14 | [0, 130, 122], #[107, 130, 148], 15 | [255, 230, 0], #[101, 192, 0],[0, 130, 122], 16 | [0, 0, 0]]) 17 | return cls_names, colormap 18 | 19 | class potsdam(Dataset): 20 | def __init__(self, transforms, split, root): 21 | super(potsdam, self).__init__() 22 | self.split = split 23 | self.root = root 24 | self.transform = transforms 25 | split_files = { 26 | "train": ["labelled_train.txt"], 27 | "unlabelled_train": ["unlabelled_train.txt"], 28 | # "train": ["unlabelled_train.txt"], 29 | "val": ["labelled_test.txt"], 30 | "train+val": ["labelled_train.txt", "labelled_test.txt"], 31 | "all": ["all.txt"] 32 | } 33 | assert self.split in split_files.keys() 34 | 35 | self.files = [] 36 | for split_file in split_files[self.split]: 37 | with open(join(self.root, split_file), "r") as f: 38 | self.files.extend(fn.rstrip() for fn in f.readlines()) 39 | 40 | self.coarse_labels = True 41 | self.fine_to_coarse = {0: 0, 4: 0, # roads and cars 42 | 1: 1, 5: 1, # buildings and clutter 43 | 2: 2, 3: 2, # vegetation and trees 44 | } 45 | 46 | def __getitem__(self, index): 47 | image_id = self.files[index] 48 | img = loadmat(join(self.root, "imgs", image_id + ".mat"))["img"] 49 | img = to_pil_image(torch.from_numpy(img).permute(2, 0, 1)[:3]) # TODO add ir channel back 50 | try: 51 | label = loadmat(join(self.root, "gt", image_id + ".mat"))["gt"] 52 | label = to_pil_image(torch.from_numpy(label).unsqueeze(-1).permute(2, 0, 1)) 53 | except FileNotFoundError: 54 | label = to_pil_image(torch.ones(1, img.height, img.width)) 55 | 56 | img, label = self.transform(img, label) 57 | 58 | if self.coarse_labels: 59 | new_label_map = torch.ones_like(label)*255 60 | for fine, coarse in self.fine_to_coarse.items(): 61 | new_label_map[label == fine] = coarse 62 | label = new_label_map 63 | 64 | # mask = (label > 0).to(torch.float32) 65 | return img, label, image_id 66 | 67 | def __len__(self): 68 | return len(self.files) 69 | 70 | classes = ['road', 'building', 'vegetation'] 71 | 72 | 73 | class PotsdamRaw(Dataset): 74 | def __init__(self, root, image_set, transform, target_transform, coarse_labels): 75 | super(PotsdamRaw, self).__init__() 76 | self.split = image_set 77 | self.root = os.path.join(root, "potsdamraw", "processed") 78 | self.transform = transform 79 | self.target_transform = target_transform 80 | self.files = [] 81 | for im_num in range(38): 82 | for i_h in range(15): 83 | for i_w in range(15): 84 | self.files.append("{}_{}_{}.mat".format(im_num, i_h, i_w)) 85 | 86 | self.coarse_labels = coarse_labels 87 | self.fine_to_coarse = {0: 0, 4: 0, # roads and cars 88 | 1: 1, 5: 1, # buildings and clutter 89 | 2: 2, 3: 2, # vegetation and trees 90 | 255: -1 91 | } 92 | 93 | def __getitem__(self, index): 94 | image_id = self.files[index] 95 | img = loadmat(join(self.root, "imgs", image_id))["img"] 96 | img = to_pil_image(torch.from_numpy(img).permute(2, 0, 1)[:3]) # TODO add ir channel back 97 | try: 98 | label = loadmat(join(self.root, "gt", image_id))["gt"] 99 | label = to_pil_image(torch.from_numpy(label).unsqueeze(-1).permute(2, 0, 1)) 100 | except FileNotFoundError: 101 | label = to_pil_image(torch.ones(1, img.height, img.width)) 102 | 103 | seed = np.random.randint(2147483647) 104 | random.seed(seed) 105 | torch.manual_seed(seed) 106 | img = self.transform(img) 107 | 108 | random.seed(seed) 109 | torch.manual_seed(seed) 110 | label = self.target_transform(label).squeeze(0) 111 | if self.coarse_labels: 112 | new_label_map = torch.zeros_like(label) 113 | for fine, coarse in self.fine_to_coarse.items(): 114 | new_label_map[label == fine] = coarse 115 | label = new_label_map 116 | 117 | mask = (label > 0).to(torch.float32) 118 | return img, label, mask 119 | 120 | def __len__(self): 121 | return len(self.files) -------------------------------------------------------------------------------- /primaps_modules/parser.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | 5 | def check_parser(args): 6 | if os.path.basename(args.dataset_root) == 'cityscapes': 7 | args.num_classes = 27 8 | dataname = 'CS' 9 | elif os.path.basename(args.dataset_root) == 'cocostuff': 10 | args.num_classes = 27 11 | dataname = 'COCO' 12 | elif os.path.basename(args.dataset_root) == 'potsdam': 13 | args.num_classes = 3 14 | dataname = 'PD' 15 | else: 16 | raise NotImplementedError 17 | if 'vits' in args.backbone_arch: 18 | args.backbone_dim = 384 19 | elif 'vitb' in args.backbone_arch: 20 | args.backbone_dim = 768 21 | else: 22 | raise NotImplementedError 23 | 24 | args.log_name = dataname+'_'+str(args.backbone_arch)+str(args.backbone_patch)+'_'+args.log_name 25 | 26 | if args.cluster_ckpt_path != '': 27 | if args.cluster_ckpt_path[-4:] != 'ckpt': 28 | args.cluster_ckpt_path = os.path.join(args.cluster_ckpt_path, dataname+'_'+str(args.backbone_arch)+str(args.backbone_patch)+'_init', 'last.ckpt') 29 | 30 | return args 31 | 32 | 33 | # parser train.py 34 | def base_parser(): 35 | parser = argparse.ArgumentParser() 36 | ### Dataset and Backbone 37 | parser.add_argument("--dataset-root", type=str, default=['/fastdata/ohahn/datasets/cityscapes', '/fastdata/ohahn/datasets/cocostuff', '/fastdata/ohahn/datasets/potsdam'][0]) 38 | parser.add_argument("--num-classes", type=int, default=[27, 3][0]) 39 | parser.add_argument("--ignore-label", type=int, default=255) 40 | parser.add_argument("--checkpoints-root", type=str, default='/visinf/projects/ohahn/checkpoints/') 41 | parser.add_argument("--logg-root", type=str, default='/visinf/projects/ohahn/checkpoints/') 42 | parser.add_argument("--backbone-dim", type=int, default=[384, 768][0]) 43 | parser.add_argument("--backbone-arch", type=str, default=['dino_vits', 'dino_vitb', 'dinov2_vits', 'dinov2_vitb'][1]) 44 | parser.add_argument("--backbone-patch", type=int, default=[8, 14, 16][0]) 45 | parser.add_argument("--dino-block", type=int, default=1, help='block outputing the used feature') 46 | parser.add_argument("--batch-size", type=int, default=32) 47 | parser.add_argument("--eval-batch-size", type=int, default=16) 48 | parser.add_argument("--validation-resize", nargs='+', type=int, default=[[320], [322]][0]) 49 | parser.add_argument("--crop-size", nargs='+', type=int, default=[[224], [320], [322]][1]) 50 | parser.add_argument("--num-workers", type=int, default=4) 51 | parser.add_argument("--num-epochs", type=int, default=50) 52 | parser.add_argument("--num-steps", type=int, default=7000) 53 | parser.add_argument("--cluster-ckpt-path", type=str, default='') 54 | parser.add_argument('--stop-criterion', type=float, default=0.95) 55 | parser.add_argument("--seed", type=int, default=0) 56 | parser.add_argument("--gpu-ids", nargs='+', type=int, default=([0])) 57 | return parser 58 | 59 | 60 | def train_parser(): 61 | parser = base_parser() 62 | ### Augmentations 63 | parser.add_argument("--student-augs", action='store_true', default=False) 64 | parser.add_argument("--augs-photometric", action='store_true', default=False) 65 | parser.add_argument("--augs-randcrop-scale", nargs='+', type=float, default=[[0.25, 1.], [0.8, 1.0], [1., 1.]][-1]) 66 | parser.add_argument("--augs-randcrop-ratio", nargs='+', type=float, default=[[4/5, 5/4], [1., 1.]][-1]) 67 | ### Linear Probing 68 | parser.add_argument("--linear-lr", type=float, default=5e-3) 69 | ### Mask Proposals 70 | parser.add_argument("--train-state", type=str, default=['baseline', 'method'][-1]) 71 | parser.add_argument('--pca-iter', type=int, default=100) 72 | parser.add_argument('--pca-q', type=int, default=1) 73 | parser.add_argument('--threshold', type=float, default=0.4) 74 | parser.add_argument('--gain', type=float, default=10.0) 75 | # Pre-computed masks 76 | parser.add_argument("--precomp-primaps", action='store_true', default=False) 77 | parser.add_argument("--precomp-primaps-root", type=str, default='') 78 | ### Cluster Head 79 | parser.add_argument("--ema-update-step", type=int, default=-1) 80 | parser.add_argument("--ema-decay", type=float, default=0.98) 81 | parser.add_argument("--cluster-lr", type=float, default=5e-3) 82 | parser.add_argument("--num-batch-pcainit", type=int, default=92) 83 | parser.add_argument("--cluster-train", action='store_true', default=False) 84 | parser.add_argument("--stego-ckpt", type=str, default='') 85 | parser.add_argument("--hp-ckpt", type=str, default='') 86 | parser.add_argument("--hp-opt", type=str, default='/visinf/home/ohahn/code/HP/json/server/cocostuff_eval.json') 87 | ### Segmentation Head 88 | parser.add_argument("--seghead-lr", type=float, default=5e-3) 89 | parser.add_argument("--seghead-arch", type=str, default=['linear', 'mlp'][0]) 90 | parser.add_argument("--seghead-focalloss", type=float, default=2.0) 91 | ### PCA Init 92 | parser.add_argument("--pcainit", action='store_true', default=False) 93 | ### Training misc 94 | parser.add_argument("--log-name", type=str, default='Experiment') 95 | parser.add_argument("--validation-freq", type= int, default=1) 96 | args = check_parser(parser.parse_args()) 97 | return args 98 | 99 | 100 | # parser test.py 101 | def test_parser(): 102 | parser = base_parser() 103 | parser.add_argument("--checkpoint-path", type=str, default='') 104 | return parser.parse_args() 105 | -------------------------------------------------------------------------------- /datasets/cocostuff.py: -------------------------------------------------------------------------------- 1 | from os.path import join 2 | import numpy as np 3 | import torch.multiprocessing 4 | from PIL import Image 5 | from torch.utils.data import Dataset 6 | 7 | def bit_get(val, idx): 8 | """Gets the bit value. 9 | Args: 10 | val: Input value, int or numpy int array. 11 | idx: Which bit of the input val. 12 | Returns: 13 | The "idx"-th bit of input val. 14 | """ 15 | return (val >> idx) & 1 16 | 17 | 18 | def create_pascal_label_colormap(): 19 | """Creates a label colormap used in PASCAL VOC segmentation benchmark. 20 | Returns: 21 | A colormap for visualizing segmentation results. 22 | """ 23 | colormap = np.zeros((512, 3), dtype=int) 24 | ind = np.arange(512, dtype=int) 25 | 26 | for shift in reversed(list(range(8))): 27 | for channel in range(3): 28 | colormap[:, channel] |= bit_get(ind, channel) << shift 29 | ind >>= 3 30 | 31 | return colormap 32 | 33 | def get_coco_labeldata(): 34 | cls_names = ["electronic", "appliance", "food", "furniture", "indoor", "kitchen", "accessory", "animal", "outdoor", "person", "sports", "vehicle", "ceiling", "floor", "food", "furniture", "rawmaterial", "textile", "wall", "window", "building", "ground", "plant", "sky", "solid", "structural", "water"] 35 | colormap = create_pascal_label_colormap() 36 | colormap[27] = np.array([0, 0, 0]) 37 | return cls_names, colormap 38 | 39 | class cocostuff(Dataset): 40 | def __init__(self, root, split, transforms, #target_transform, 41 | coarse_labels=None, exclude_things=None, subset=7): #None): 42 | super(cocostuff, self).__init__() 43 | self.split = split 44 | self.root = root 45 | self.coarse_labels = coarse_labels 46 | self.transforms = transforms 47 | #self.label_transform = target_transform 48 | self.subset = subset 49 | self.exclude_things = exclude_things 50 | 51 | if self.subset is None: 52 | self.image_list = "Coco164kFull_Stuff_Coarse.txt" 53 | elif self.subset == 6: # IIC Coarse 54 | self.image_list = "Coco164kFew_Stuff_6.txt" 55 | elif self.subset == 7: # IIC Fine 56 | self.image_list = "Coco164kFull_Stuff_Coarse_7.txt" 57 | 58 | assert self.split in ["train", "val", "train+val"] 59 | split_dirs = { 60 | "train": ["train2017"], 61 | "val": ["val2017"], 62 | "train+val": ["train2017", "val2017"] 63 | } 64 | 65 | self.image_files = [] 66 | self.label_files = [] 67 | for split_dir in split_dirs[self.split]: 68 | with open(join(self.root, "curated", split_dir, self.image_list), "r") as f: 69 | img_ids = [fn.rstrip() for fn in f.readlines()] 70 | for img_id in img_ids: 71 | self.image_files.append(join(self.root, "images", split_dir, img_id + ".jpg")) 72 | self.label_files.append(join(self.root, "annotations", split_dir, img_id + ".png")) 73 | 74 | self.fine_to_coarse = {0: 9, 1: 11, 2: 11, 3: 11, 4: 11, 5: 11, 6: 11, 7: 11, 8: 11, 9: 8, 10: 8, 11: 8, 12: 8, 75 | 13: 8, 14: 8, 15: 7, 16: 7, 17: 7, 18: 7, 19: 7, 20: 7, 21: 7, 22: 7, 23: 7, 24: 7, 76 | 25: 6, 26: 6, 27: 6, 28: 6, 29: 6, 30: 6, 31: 6, 32: 6, 33: 10, 34: 10, 35: 10, 36: 10, 77 | 37: 10, 38: 10, 39: 10, 40: 10, 41: 10, 42: 10, 43: 5, 44: 5, 45: 5, 46: 5, 47: 5, 48: 5, 78 | 49: 5, 50: 5, 51: 2, 52: 2, 53: 2, 54: 2, 55: 2, 56: 2, 57: 2, 58: 2, 59: 2, 60: 2, 79 | 61: 3, 62: 3, 63: 3, 64: 3, 65: 3, 66: 3, 67: 3, 68: 3, 69: 3, 70: 3, 71: 0, 72: 0, 80 | 73: 0, 74: 0, 75: 0, 76: 0, 77: 1, 78: 1, 79: 1, 80: 1, 81: 1, 82: 1, 83: 4, 84: 4, 81 | 85: 4, 86: 4, 87: 4, 88: 4, 89: 4, 90: 4, 91: 17, 92: 17, 93: 22, 94: 20, 95: 20, 96: 22, 82 | 97: 15, 98: 25, 99: 16, 100: 13, 101: 12, 102: 12, 103: 17, 104: 17, 105: 23, 106: 15, 83 | 107: 15, 108: 17, 109: 15, 110: 21, 111: 15, 112: 25, 113: 13, 114: 13, 115: 13, 116: 13, 84 | 117: 13, 118: 22, 119: 26, 120: 14, 121: 14, 122: 15, 123: 22, 124: 21, 125: 21, 126: 24, 85 | 127: 20, 128: 22, 129: 15, 130: 17, 131: 16, 132: 15, 133: 22, 134: 24, 135: 21, 136: 17, 86 | 137: 25, 138: 16, 139: 21, 140: 17, 141: 22, 142: 16, 143: 21, 144: 21, 145: 25, 146: 21, 87 | 147: 26, 148: 21, 149: 24, 150: 20, 151: 17, 152: 14, 153: 21, 154: 26, 155: 15, 156: 23, 88 | 157: 20, 158: 21, 159: 24, 160: 15, 161: 24, 162: 22, 163: 25, 164: 15, 165: 20, 166: 17, 89 | 167: 17, 168: 22, 169: 14, 170: 18, 171: 18, 172: 18, 173: 18, 174: 18, 175: 18, 176: 18, 90 | 177: 26, 178: 26, 179: 19, 180: 19, 181: 24} 91 | 92 | self._label_names = [ 93 | "ground-stuff", 94 | "plant-stuff", 95 | "sky-stuff", 96 | ] 97 | self.cocostuff3_coarse_classes = [23, 22, 21] 98 | self.first_stuff_index = 12 99 | 100 | def __getitem__(self, index): 101 | image_path = self.image_files[index] 102 | label_path = self.label_files[index] 103 | seed = np.random.randint(2147483647) 104 | 105 | img, label = self.transforms(Image.open(image_path).convert("RGB"), Image.open(label_path)) 106 | 107 | label[label == 255] = -1 # to be consistent with 10k 108 | coarse_label = torch.zeros_like(label) 109 | for fine, coarse in self.fine_to_coarse.items(): 110 | coarse_label[label == fine] = coarse 111 | coarse_label[label == -1] = 255 #-1 112 | 113 | if self.coarse_labels: 114 | coarser_labels = -torch.ones_like(label) 115 | for i, c in enumerate(self.cocostuff3_coarse_classes): 116 | coarser_labels[coarse_label == c] = i 117 | return img, coarser_labels, coarser_labels >= 0 118 | else: 119 | if self.exclude_things: 120 | return img, coarse_label - self.first_stuff_index, (coarse_label >= self.first_stuff_index) 121 | else: 122 | return img, coarse_label, image_path 123 | 124 | def __len__(self): 125 | return len(self.image_files) -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/dinovit.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | # import primaps_modules.backbone.dino.vision_transformer as vits 4 | 5 | 6 | # class DinoFeaturizer(nn.Module): 7 | 8 | # def __init__(self, arch, patch_size, totrain): 9 | # super().__init__() 10 | # self.patch_size = patch_size 11 | # self.feat_type = "feat" 12 | 13 | # self.model = vits.__dict__[arch]( 14 | # patch_size=patch_size, 15 | # num_classes=0) 16 | # for p in self.model.parameters(): 17 | # p.requires_grad = False 18 | # self.model.eval() #.cuda() 19 | # if totrain: 20 | # for p in self.model.parameters(): 21 | # p.requires_grad = True 22 | # self.model.train() 23 | # self.dropout = torch.nn.Dropout2d(p=.1) 24 | 25 | # if arch == "vit_small" and patch_size == 16: 26 | # url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth" 27 | # elif arch == "vit_small" and patch_size == 8: 28 | # url = "dino_deitsmall8_300ep_pretrain/dino_deitsmall8_300ep_pretrain.pth" 29 | # elif arch == "vit_base" and patch_size == 16: 30 | # url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth" 31 | # elif arch == "vit_base" and patch_size == 8: 32 | # url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth" 33 | # else: 34 | # raise ValueError("Unknown arch and patch size") 35 | 36 | # # if pretrained_weights is not None: 37 | # # state_dict = torch.load(cfg.pretrained_weights, map_location="cpu") 38 | # # state_dict = state_dict["teacher"] 39 | # # # remove `module.` prefix 40 | # # state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} 41 | # # # remove `backbone.` prefix induced by multicrop wrapper 42 | # # state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} 43 | 44 | # # # state_dict = {k.replace("projection_head", "mlp"): v for k, v in state_dict.items()} 45 | # # # state_dict = {k.replace("prototypes", "last_layer"): v for k, v in state_dict.items()} 46 | 47 | # # msg = self.model.load_state_dict(state_dict, strict=False) 48 | # # print('Pretrained weights found at {} and loaded with msg: {}'.format(cfg.pretrained_weights, msg)) 49 | # # else: 50 | # print("Since no pretrained weights have been provided, we load the reference pretrained DINO weights.") 51 | # state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url) 52 | # self.model.load_state_dict(state_dict, strict=True) 53 | 54 | # # if arch == "vit_small": 55 | # # self.n_feats = 384 56 | # # else: 57 | # # self.n_feats = 768 58 | # # self.cluster1 = self.make_clusterer(self.n_feats) 59 | # # self.proj_type = cfg.projection_type 60 | # # if self.proj_type == "nonlinear": 61 | # # self.cluster2 = self.make_nonlinear_clusterer(self.n_feats) 62 | 63 | # # def make_clusterer(self, in_channels): 64 | # # return torch.nn.Sequential( 65 | # # torch.nn.Conv2d(in_channels, self.dim, (1, 1))) # , 66 | 67 | # # def make_nonlinear_clusterer(self, in_channels): 68 | # # return torch.nn.Sequential( 69 | # # torch.nn.Conv2d(in_channels, in_channels, (1, 1)), 70 | # # torch.nn.ReLU(), 71 | # # torch.nn.Conv2d(in_channels, self.dim, (1, 1))) 72 | 73 | # def forward(self, img, n=1, return_class_feat=False): 74 | # # self.model.eval() 75 | # with torch.no_grad(): 76 | # assert (img.shape[2] % self.patch_size == 0) 77 | # assert (img.shape[3] % self.patch_size == 0) 78 | 79 | # # get selected layer activations 80 | # feat, attn, qkv = self.model.get_intermediate_feat(img, n=n) 81 | # if n == 1: 82 | # feat, attn, qkv = feat[0], attn[0], qkv[0] 83 | # else: 84 | # feat, attn, qkv = feat[-n], attn[-n], qkv[-n] 85 | 86 | 87 | 88 | # feat_h = img.shape[2] // self.patch_size 89 | # feat_w = img.shape[3] // self.patch_size 90 | 91 | # if self.feat_type == "feat": 92 | # image_feat = feat[:, 1:, :].reshape(feat.shape[0], feat_h, feat_w, -1).permute(0, 3, 1, 2) 93 | # elif self.feat_type == "KK": 94 | # image_k = qkv[1, :, :, 1:, :].reshape(feat.shape[0], 6, feat_h, feat_w, -1) 95 | # B, H, I, J, D = image_k.shape 96 | # image_feat = image_k.permute(0, 1, 4, 2, 3).reshape(B, H * D, I, J) 97 | # else: 98 | # raise ValueError("Unknown feat type:{}".format(self.feat_type)) 99 | 100 | # if return_class_feat: 101 | # return image_feat, feat[:, :1, :].reshape(feat.shape[0], 1, 1, -1).permute(0, 3, 1, 2) 102 | # else: 103 | # return image_feat 104 | 105 | # # if self.proj_type is not None: 106 | # # code = self.cluster1(self.dropout(image_feat)) 107 | # # if self.proj_type == "nonlinear": 108 | # # code += self.cluster2(self.dropout(image_feat)) 109 | # # else: 110 | # # code = image_feat 111 | 112 | # # if self.cfg.dropout: 113 | # # return self.dropout(image_feat), code 114 | # # else: 115 | # # return image_feat, code 116 | 117 | class DinoFeaturizerv2(nn.Module): 118 | 119 | def __init__(self, arch, patch_size): 120 | super().__init__() 121 | self.patch_size = patch_size 122 | self.arch = arch 123 | if 'v2' in arch: 124 | self.model = torch.hub.load('facebookresearch/dinov2', arch+str(patch_size)) 125 | elif 'resnet' in arch: 126 | rn_dino = torch.hub.load('facebookresearch/dino:main', 'dino_resnet50') 127 | from torchvision.models.feature_extraction import create_feature_extractor 128 | return_nodes = {'layer4.2.relu_2': 'out'} 129 | self.model = create_feature_extractor(rn_dino, return_nodes=return_nodes) 130 | else: 131 | self.model = torch.hub.load('facebookresearch/dino:main', arch+str(patch_size)) 132 | for p in self.model.parameters(): 133 | p.requires_grad = False 134 | self.model.eval() 135 | 136 | 137 | def forward(self, img, n=1): 138 | with torch.no_grad(): 139 | assert (img.shape[2] % self.patch_size == 0) 140 | assert (img.shape[3] % self.patch_size == 0) 141 | 142 | if 'v2' in self.arch: 143 | image_feat = self.model.get_intermediate_layers(img, n, reshape=True)[n-1] 144 | elif 'resnet' in self.arch: 145 | image_feat = self.model(img)['out'] 146 | else: 147 | image_feat = self.model.get_intermediate_layers(img, n)[-n][:, 1:, :].transpose(1, 2).contiguous() 148 | image_feat = image_feat.view(image_feat.size(0), image_feat.size(1), img.size(-1)//self.patch_size, img.size(-1)//self.patch_size) 149 | 150 | return image_feat 151 | -------------------------------------------------------------------------------- /primaps_modules/ema.py: -------------------------------------------------------------------------------- 1 | # Original implementation: https://github.com/lucidrains/ema-pytorch 2 | 3 | 4 | import copy 5 | import torch 6 | from torch import nn 7 | 8 | def exists(val): 9 | return val is not None 10 | 11 | def clamp(value, min_value = None, max_value = None): 12 | assert exists(min_value) or exists(max_value) 13 | if exists(min_value): 14 | value = max(value, min_value) 15 | 16 | if exists(max_value): 17 | value = min(value, max_value) 18 | 19 | return value 20 | 21 | class EMA(nn.Module): 22 | """ 23 | Implements exponential moving average shadowing for your model. 24 | 25 | Utilizes an inverse decay schedule to manage longer term training runs. 26 | By adjusting the power, you can control how fast EMA will ramp up to your specified beta. 27 | 28 | @crowsonkb's notes on EMA Warmup: 29 | 30 | If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are 31 | good values for models you plan to train for a million or more steps (reaches decay 32 | factor 0.999 at 31.6K steps, 0.9999 at 1M steps), gamma=1, power=3/4 for models 33 | you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at 34 | 215.4k steps). 35 | 36 | Args: 37 | inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1. 38 | power (float): Exponential factor of EMA warmup. Default: 1. 39 | min_value (float): The minimum EMA decay rate. Default: 0. 40 | """ 41 | def __init__( 42 | self, 43 | model, 44 | ema_model = None, # if your model has lazylinears or other types of non-deepcopyable modules, you can pass in your own ema model 45 | beta = 0.9999, 46 | update_after_step = 100, 47 | update_every = 10, 48 | inv_gamma = 1.0, 49 | power = 1.0, #2 / 3, 50 | min_value = 0.0, 51 | param_or_buffer_names_no_ema = set(), 52 | ignore_names = set(), 53 | ignore_startswith_names = set(), 54 | include_online_model = True # set this to False if you do not wish for the online model to be saved along with the ema model (managed externally) 55 | ): 56 | super().__init__() 57 | self.beta = beta 58 | 59 | # whether to include the online model within the module tree, so that state_dict also saves it 60 | 61 | self.include_online_model = include_online_model 62 | 63 | if include_online_model: 64 | self.online_model = model 65 | else: 66 | self.online_model = [model] # hack 67 | 68 | # ema model 69 | 70 | self.ema_model = ema_model 71 | 72 | if not exists(self.ema_model): 73 | try: 74 | self.ema_model = copy.deepcopy(model) 75 | except: 76 | print('Your model was not copyable. Please make sure you are not using any LazyLinear') 77 | exit() 78 | 79 | self.ema_model.requires_grad_(False) 80 | 81 | self.parameter_names = {name for name, param in self.ema_model.named_parameters() if param.dtype in [torch.float, torch.float16]} 82 | self.buffer_names = {name for name, buffer in self.ema_model.named_buffers() if buffer.dtype in [torch.float, torch.float16]} 83 | 84 | self.update_every = update_every 85 | self.update_after_step = update_after_step 86 | 87 | self.inv_gamma = inv_gamma 88 | self.power = power 89 | self.min_value = min_value 90 | 91 | assert isinstance(param_or_buffer_names_no_ema, (set, list)) 92 | self.param_or_buffer_names_no_ema = param_or_buffer_names_no_ema # parameter or buffer 93 | 94 | self.ignore_names = ignore_names 95 | self.ignore_startswith_names = ignore_startswith_names 96 | 97 | self.register_buffer('initted', torch.Tensor([False])) 98 | self.register_buffer('step', torch.tensor([0])) 99 | 100 | @property 101 | def model(self): 102 | return self.online_model if self.include_online_model else self.online_model[0] 103 | 104 | def restore_ema_model_device(self): 105 | device = self.initted.device 106 | self.ema_model.to(device) 107 | 108 | def get_params_iter(self, model): 109 | for name, param in model.named_parameters(): 110 | if name not in self.parameter_names: 111 | continue 112 | yield name, param 113 | 114 | def get_buffers_iter(self, model): 115 | for name, buffer in model.named_buffers(): 116 | if name not in self.buffer_names: 117 | continue 118 | yield name, buffer 119 | 120 | def copy_params_from_model_to_ema(self): 121 | for (_, ma_params), (_, current_params) in zip(self.get_params_iter(self.ema_model), self.get_params_iter(self.model)): 122 | ma_params.data.copy_(current_params.data) 123 | 124 | for (_, ma_buffers), (_, current_buffers) in zip(self.get_buffers_iter(self.ema_model), self.get_buffers_iter(self.model)): 125 | ma_buffers.data.copy_(current_buffers.data) 126 | 127 | def get_current_decay(self): 128 | epoch = clamp(self.step.item() - self.update_after_step - 1, min_value = 0.) 129 | value = 1 - (1 + epoch / self.inv_gamma) ** - self.power 130 | 131 | if epoch <= 0: 132 | return 0. 133 | 134 | return clamp(value, min_value = self.min_value, max_value = self.beta) 135 | 136 | def update(self): 137 | step = self.step.item() 138 | self.step += 1 139 | 140 | if (step % self.update_every) != 0: 141 | return 142 | 143 | if step <= self.update_after_step: 144 | self.copy_params_from_model_to_ema() 145 | return 146 | 147 | if not self.initted.item(): 148 | self.copy_params_from_model_to_ema() 149 | self.initted.data.copy_(torch.Tensor([True])) 150 | 151 | self.update_moving_average(self.ema_model, self.model) 152 | 153 | @torch.no_grad() 154 | def update_moving_average(self, ma_model, current_model): 155 | if (self.beta == 0.0 or self.beta == 1.0): 156 | current_decay = self.beta 157 | else: 158 | current_decay = self.get_current_decay() 159 | print('-- EMA decay: %s' % current_decay) 160 | 161 | for (name, current_params), (_, ma_params) in zip(self.get_params_iter(current_model), self.get_params_iter(ma_model)): 162 | if name in self.ignore_names: 163 | continue 164 | 165 | if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): 166 | continue 167 | 168 | if name in self.param_or_buffer_names_no_ema: 169 | ma_params.data.copy_(current_params.data) 170 | continue 171 | 172 | ma_params.data.lerp_(current_params.data, 1. - current_decay) 173 | 174 | for (name, current_buffer), (_, ma_buffer) in zip(self.get_buffers_iter(current_model), self.get_buffers_iter(ma_model)): 175 | if name in self.ignore_names: 176 | continue 177 | 178 | if any([name.startswith(prefix) for prefix in self.ignore_startswith_names]): 179 | continue 180 | 181 | if name in self.param_or_buffer_names_no_ema: 182 | ma_buffer.data.copy_(current_buffer.data) 183 | continue 184 | 185 | ma_buffer.data.lerp_(current_buffer.data, 1. - current_decay) 186 | 187 | def __call__(self, *args, **kwargs): 188 | return self.ema_model(*args, **kwargs) -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torch.nn.functional as F 4 | from torch.utils.data import DataLoader 5 | from pytorch_lightning.utilities.seed import seed_everything 6 | from pytorch_lightning import Trainer 7 | from multiprocessing import get_context 8 | 9 | import datasets 10 | from primaps_modules.metrics import UnsupervisedMetrics 11 | import primaps_modules.transforms as transforms 12 | from primaps_modules.parser import test_parser 13 | from primaps_modules.crf import * 14 | from train import UnsupervisedSegmenter 15 | 16 | 17 | class UnsupervisedSegmenter_test(UnsupervisedSegmenter): 18 | def __init__(self, opts): 19 | super(UnsupervisedSegmenter_test, self).__init__(opts) 20 | self.meter_theta_m = UnsupervisedMetrics("test/cluster/", self.opts.num_classes, 0, True) 21 | self.meter_theta_r = UnsupervisedMetrics("test/seghead/", self.opts.num_classes, 0, True) 22 | self.meter_linear = UnsupervisedMetrics("test/linear/", self.opts.num_classes, 0, False) 23 | self.meter_theta_r_crf = UnsupervisedMetrics("test/segheadcrf/", self.opts.num_classes, 0, True) 24 | self.meter_theta_m_crf = UnsupervisedMetrics("test/clustercrf/", self.opts.num_classes, 0, True) 25 | self.vis_test = [] 26 | 27 | 28 | def on_test_start(self) -> None: 29 | super().on_test_start() 30 | self.meter_theta_m.to(self.device) 31 | self.meter_linear.to(self.device) 32 | self.meter_theta_r.to(self.device) 33 | self.meter_theta_r_crf.to(self.device) 34 | self.meter_theta_m_crf.to(self.device) 35 | 36 | self.meter_theta_m.reset() 37 | self.meter_linear.reset() 38 | self.meter_theta_r.reset() 39 | self.meter_theta_r_crf.reset() 40 | self.meter_theta_m_crf.reset() 41 | 42 | 43 | def test_step(self, batch, batch_idx): 44 | with torch.no_grad(): 45 | # get image and label 46 | img, label = batch[0], batch[1] 47 | label[label>=self.opts.num_classes] = self.opts.ignore_label 48 | # backbone forwards pass with image and hfliped image 49 | feats = self.net(img, n=self.opts.dino_block) 50 | feats_flip = self.net(img.flip(dims=[3]), n=self.opts.dino_block) 51 | feats = (feats + feats_flip.flip(dims=[3])) / 2 52 | # interpolate features to label size 53 | feats = F.interpolate(feats, label.shape[-2:], mode='bilinear', align_corners=False) 54 | # get predictions 55 | pred = torch.log_softmax(self.linear_probe(feats.detach().clone()), dim=1) 56 | pred = pred.argmax(1) 57 | self.meter_linear.update(pred, label) 58 | 59 | theta_r_logits = self.seghead(feats.detach().clone()) 60 | theta_r_prob = torch.log_softmax(theta_r_logits, dim=1) 61 | pred = theta_r_prob.argmax(1) 62 | self.meter_theta_r.update(pred, label) 63 | 64 | theta_m_prob = self.cluster_probe(feats.detach().clone()) 65 | pred = theta_m_prob.argmax(1) 66 | self.meter_theta_m.update(pred, label) 67 | # apply crf 68 | with get_context('spawn').Pool(5) as pool: 69 | soft = F.log_softmax(theta_m_prob, dim=1) 70 | out_clstrcrf = batched_crf(pool, img, soft).argmax(1).to(self.device) 71 | out_shcrf = batched_crf(pool, img, theta_r_prob).argmax(1).to(self.device) 72 | 73 | self.meter_theta_m_crf.update(out_clstrcrf, label) 74 | self.meter_theta_r_crf.update(out_shcrf, label) 75 | 76 | 77 | def test_epoch_end(self, outputs) -> None: 78 | super().test_epoch_end(outputs) 79 | 80 | tb_metrics = {**self.meter_theta_m.compute(), 81 | **self.meter_linear.compute(), 82 | **self.meter_theta_r.compute(), 83 | **self.meter_theta_m_crf.compute(), 84 | **self.meter_theta_r_crf.compute()} 85 | 86 | # print results 87 | print('--------------------------------------------------') 88 | print('THETA_M mIoU:'+ str(round(tb_metrics['test/cluster/mIoU'], 4))+' THETA_M Acc: '+ str(round(tb_metrics['test/cluster/Accuracy'], 4))) 89 | print('THETA_M CRF mIoU:'+ str(round(tb_metrics['test/clustercrf/mIoU'], 4))+ ' THETA_M CRF Acc: '+ str(round(tb_metrics['test/clustercrf/Accuracy'], 4))) 90 | print('THETA_R mIoU:'+ str(round(tb_metrics['test/seghead/mIoU'], 4))+' THETA_R Acc: '+ str(round(tb_metrics['test/seghead/Accuracy'], 4))) 91 | print('THETA_R CRF mIoU:'+ str(round(tb_metrics['test/segheadcrf/mIoU'], 4))+' THETA_R CRF Acc: '+ str(round(tb_metrics['test/segheadcrf/Accuracy'], 4))) 92 | print('Linear mIoU:'+ str(round(tb_metrics['test/linear/mIoU'], 4))+' Linear Acc: '+ str(round(tb_metrics['test/linear/Accuracy'], 4))) 93 | print('--------------------------------------------------') 94 | 95 | print('Linear - THETA_M - THETA_R - THETA_M CRF - THETA_R CRF - Class Name' ) 96 | for cls, ln, cl, sh, cltcr, shcrf in zip(self.dataset_info, tb_metrics['test/linear/Class IoUs'], tb_metrics['test/cluster/Class IoUs'], tb_metrics['test/seghead/Class IoUs'], tb_metrics['test/clustercrf/Class IoUs'], tb_metrics['test/segheadcrf/Class IoUs']): 97 | print(str(round(ln,2))+"; "+str(round(cl, 2))+"; "+str(round(sh, 2))+"; "+str(round(cltcr, 2))+"; "+str(round(shcrf, 2))+"; -- "+str(cls)) 98 | 99 | 100 | 101 | 102 | def main(opts): 103 | # set seeds 104 | seed_everything(seed=opts.seed, workers=True) 105 | # override opts in checkpoint 106 | dataset_root = opts.dataset_root 107 | checkpoint_path = opts.checkpoint_path 108 | print('-- Checkpoint: %s' %opts.checkpoint_path) 109 | opts = torch.load(opts.checkpoint_path, map_location="cpu")['hyper_parameters']['opts'] 110 | opts.cluster_ckpt_path = "" 111 | opts.dataset_root = dataset_root 112 | opts.checkpoint_path = checkpoint_path 113 | opts.num_workers = 4 114 | opts.gpu_ids = [0] 115 | # load model from ckeckpoint 116 | model = UnsupervisedSegmenter_test(opts) 117 | state_dict = torch.load(checkpoint_path, map_location=model.device)['state_dict'] 118 | if 'cluster_probe.ema_model.weight_g' in state_dict.keys(): 119 | print('-- update state dict with ema') 120 | import torch.nn as nn 121 | model.cluster_probe = nn.utils.weight_norm(nn.Conv2d(opts.backbone_dim, opts.num_classes, (1, 1), bias=False), name='weight', dim=0) 122 | state_dict['cluster_probe.weight_g'] = state_dict['cluster_probe.ema_model.weight_g'] 123 | state_dict['cluster_probe.weight_v'] = state_dict['cluster_probe.ema_model.weight_v'] 124 | model.load_state_dict(state_dict, strict=False) 125 | model.eval() 126 | 127 | 128 | # Setup dataset 129 | dataset_name = os.path.split(opts.dataset_root)[-1] 130 | val_transforms = transforms.Compose([transforms.ToTensor(), 131 | transforms.IdsToTrainIds(source=dataset_name), 132 | transforms.Resize(opts.validation_resize), #transforms.ImgResize(opts.validation_resize), 133 | transforms.CenterCrop([opts.validation_resize[0], opts.validation_resize[0]]), 134 | transforms.Normalize()]) 135 | val_dataset = datasets.__dict__[dataset_name](root=opts.dataset_root, 136 | split="val", 137 | transforms=val_transforms) 138 | val_loader = DataLoader(val_dataset, 139 | batch_size=16, 140 | num_workers=4, 141 | sampler=None, 142 | shuffle=False, 143 | pin_memory=True if torch.cuda.is_available() else False) 144 | 145 | trainer = Trainer(benchmark = True, 146 | logger=False, 147 | gpus=opts.gpu_ids) 148 | # run test loop 149 | trainer.test(model, val_loader) 150 | 151 | 152 | 153 | 154 | if __name__ == '__main__': 155 | opts = test_parser() 156 | main(opts) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Boosting Unsupervised Semantic Segmentation with Principal Mask Proposals 2 | 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![Framework](https://img.shields.io/badge/PyTorch-%23EE4C2C.svg?&logo=PyTorch&logoColor=white)](https://pytorch.org/) 5 | 6 | This is the official repository of our paper: 7 | 8 | **Boosting Unsupervised Semantic Segmentation with Principal Mask Proposals**
9 | [Oliver Hahn](https://olvrhhn.github.io), 10 | [Nikita Araslanov](https://arnike.github.io), 11 | [Simone Schaub-Meyer](https://schaubsi.github.io), 12 | and [Stefan Roth](https://www.visinf.tu-darmstadt.de/visual_inference/people_vi/stefan_roth.en.jsp)
13 | **TMLR Sep. 2024** 14 | 15 | [[OpenReview](https://openreview.net/forum?id=UawaTQzfwy)] [[ArXiv](https://arxiv.org/abs/2404.16818)] [[Project Page](https://visinf.github.io/primaps/)] [[Demo](https://huggingface.co/spaces/olvrhhn/PriMaPs)] 16 | 17 | **Abstract:** Unsupervised semantic segmentation aims to automatically partition images into semantically meaningful regions by identifying global categories within an image corpus without any form of annotation. Building upon recent advances in self-supervised representation learning, we focus on how to leverage these large pre-trained models for the downstream task of unsupervised segmentation. We present PriMaPs - Principal Mask Proposals - decomposing images into semantically meaningful masks based on their feature representation. This allows us to realize unsupervised semantic segmentation by fitting class prototypes to PriMaPs with a stochastic expectation-maximization algorithm, PriMaPs-EM. Despite its conceptual simplicity, PriMaPs-EM leads to competitive results across various pre-trained backbone models, including DINO and DINOv2, and across datasets, such as Cityscapes, COCO-Stuff, and Potsdam-3. Importantly, PriMaPs-EM is able to boost results when applied orthogonally to current state-of-the-art unsupervised semantic segmentation pipelines. 18 | 19 | ![PriMaPsExamples](./assets/primaps_examples.png) 20 | 21 | Figure 1: Principal mask proposals (PriMaPs) are iteratively extracted 22 | from an image (dashed arrows). Each mask is assigned a semantic class resulting in a pseudo label. 23 | 24 | 25 | ## News 26 | - `27/11/2024`: Code, checkpoints, and gradio demo released. 27 | - `10/09/2024`: Paper has been accepted to [TMLR](https://openreview.net/forum?id=UawaTQzfwy)! 🎉 28 | - `25/04/2024`: [ArXiv](https://arxiv.org/abs/2404.16818) preprint released. 29 | 30 | ## Installation 31 | This project was originally developed with Python 3.6.9, PyTorch 1.10, and CUDA 11.0. We used a single NVIDIA A6000 (49GB). Create the conda environment as follows: 32 | 33 | ``` 34 | conda create --name primaps python==3.6.9 torchmetrics=0.10.3 -c conda-forge 35 | 36 | source activate primaps 37 | 38 | python -m pip install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio==0.10.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html 39 | 40 | pip install -r requirements.txt 41 | 42 | pip install git+https://github.com/lucasb-eyer/pydensecrf.git 43 | ``` 44 | 45 | We have observed that the metric performance can vary when library dependencies are not properly taken into account and different hardware is used. 46 | 47 | ## Demo 48 | We provide a simple demo to obtain and visualize PriMaPs from a given image in ```demo.py```. 49 | 50 | 51 | ## Datasets 52 | Download the datasets from their original source ([Cityscapes](https://www.cityscapes-dataset.com), [COCO-Stuff](https://download.visinf.tu-darmstadt.de/data/from_games/), [Potsdam-3](https://www.isprs.org/education/benchmarks/UrbanSemLab/2d-sem-label-potsdam.aspx)). Alternatively, follow the [STEGO](https://github.com/mhamilton723/STEGO) dataset preperation. 53 | 54 | ## Generate PriMaPs Pseudo Labels 55 | Before the actual training the PriMaPs pseudo labels are pre-computed and stored. Run the following command and adjust to the desired dataset and backbone architecture. 56 | ``` 57 | python train.py --precomp-primaps --threshold 0.4 --dataset-root /path/to/datasets/cityscapes --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 8 --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --log-name my_experiment --gpu-ids 0 58 | ``` 59 | 60 | ## Train 61 | For initialization we train for two epochs minimizing the cosine 62 | distance batch-wise K-means. If the number of epochs is increased accordingly, this command corresponds to the baseline training. 63 | ``` 64 | python train.py --pcainit --dataset-root /path/to/datasets/cityscapes --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --train-state baseline --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 2 --linear-lr 5e-3 --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --gpu-ids 0 --log-name my_experiment 65 | ``` 66 | 67 | This is followed by the actual training using the pre-computed PriMaPs pseudo labels and the initialization checkpoint. 68 | 69 | ``` 70 | python train.py --cluster-ckpt-path /path/to/init/checkpoints/checkpoint/last.ckpt --student-augs --dataset-root /path/to/datasets/cityscapes --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 50 --linear-lr 5e-3 --ema-update-step 10 --ema-decay 0.98 --precomp-primaps-root /path/to/datasets/cached_datasets/primaps_cityscapes/ --seghead-lr 5e-3 --seghead-arch 'linear' --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --gpu-ids 0 --log-name my_experiment 71 | ``` 72 | 73 | 74 | ### Train with STEGO or HP 75 | Add the original code to the ```external``` folder. The used STEGO checkpoints are provided in the original [STEGO repository](https://github.com/mhamilton723/STEGO). For [HP](https://github.com/hynnsk/HP) we reproduced the paper results and provide the used checkpoints for download [here](https://drive.google.com/drive/folders/13nAIRNxYewQ7wNLAtoV9bXGHaaOcrg_5?usp=drive_link). The pre-computed pseudo-labels of the respective DINO backbone are used and no initialization checkpoint is needed. For training with STEGO run: 76 | 77 | ``` 78 | 79 | dataroot='/fastdata/ohahn/datasets/cityscapes' 80 | stegockpt='/visinf/home/ohahn/code/STEGO/saved_models/cityscapes_vit_base_1.ckpt' 81 | pseudo='/fastdata/ohahn/datasets/cached_datasets/minimal320_04low/CS_dino_vitb8_cached-320-04lowminimal_105234' 82 | decay=0.98 83 | lr=5e-3 84 | python train_clean.py --log-name my_experiment --student-augs --seghead-focalloss 2.0 --dataset-root $dataroot --stego-ckpt $stegockpt --backbone-arch dino_vitb --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 50 --linear-lr 5e-3 --ema-update-step 10 --ema-decay $decay --precomp-pseudos-root $pseudo --seghead-lr $lr --seghead-arch 'linear' --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --gpu-ids 0 85 | ``` 86 | 87 | For HP: 88 | ``` 89 | dataroot='/fastdata/ohahn/datasets/cityscapes' 90 | pseudo='/fastdata/ohahn/datasets/cached_datasets/minimal320_04low/CS_dino_vits8_cached-320-04lowminimal_103313' 91 | hp_ckpt='/visinf/home/ohahn/code/HP/checkpoints/hp_vits8_cs/experiment_name/' 92 | hp_opt='/visinf/home/ohahn/code/HP/checkpoints/hp_vits8_cs/option.json' 93 | decay=0.98 94 | lr=5e-3 95 | python train_clean.py --seghead-focalloss 2.0 --log-name $name --student-augs --dataset-root $dataroot --hp-ckpt $hp_ckpt --hp-opt $hp_opt --backbone-arch dino_vits --backbone-patch 8 --dino-block 1 --batch-size 32 --validation-resize 320 --crop-size 320 --num-workers 4 --num-epochs 50 --linear-lr 5e-3 --ema-update-step 10 --ema-decay $decay --precomp-pseudos-root $pseudo --seghead-lr $lr --seghead-arch 'linear' --augs-randcrop-scale 1. 1. --augs-randcrop-ratio 1. 1. --gpu-ids 0 96 | 97 | ``` 98 | 99 | ## Test 100 | To evaluate the trained checkpoint, run the following command. The config is stored in the checkpoint. 101 | ``` 102 | python test.py --checkpoint-path /path/to/checkpoint.ckpt --dataset-root /path/to/dataset 103 | ``` 104 | 105 | 106 | ## Main Results 107 | We provide a script to reproduce the main results on the Cityscapes dataset in `experiments.sh`. 108 | 109 | 110 | ## Downloads 111 | [Here](https://drive.google.com/drive/folders/1TG_bvdYzLCzIH5DsX2X_lhdpLgI9wfzm?usp=drive_link) we provide all checkpoints used in the main table. 112 | 113 | ``` 114 | gdown https://drive.google.com/drive/folders/1TG_bvdYzLCzIH5DsX2X_lhdpLgI9wfzm?usp=drive_link -O /save/here/ --folder 115 | ``` 116 | 117 | ## Results 118 | 119 | PriMaPs-EM provides modest but consistent benefits over a wide range of baselines and datasets and reaches competitive segmentation accuracy w.r.t. the state-of-the-art constituting a straightforward, entirely orthogonal tool for boosting unsupervised semantic segmentation. 120 | 121 | | Method | Backbone | Cityscapes (Acc / mIoU) | COCO-Stuff ( Acc / mIoU) | Potsdam-3 (Acc / mIoU) | 122 | |--------------|:---------------:|:------------:|:------------:|:-----------:| 123 | | Baseline | DINO ViT-S/8 | 61.4 / 15.8 | 34.2 / 9.5 | 56.6 / 33.6 | 124 | | +PriMaPs | DINO ViT-S/8 | 81.2 / 19.4 | 46.5 / 16.4 | 62.5 / 38.9 | 125 | | +SotA+PriMaPs| DINO ViT-S/8 | 76.6 / 19.2 | 57.8 / 25.1 | 78.4 / 64.2 | 126 | | Baseline | DINO ViT-B/8 | 49.2 / 15.5 | 38.8 / 15.7 | 66.1 / 49.4 | 127 | | +PriMaPs | DINO ViT-B/8 | 59.6 / 17.6 | 48.5 / 21.9 | 80.5 / 67.0 | 128 | | +SotA+PriMaPs| DINO ViT-B/8 | 78.6 / 21.6 | 57.9 / 29.7 | 83.3 / 71.0 | 129 | | Baseline | DINOv2 ViT-S/14 | 49.5 / 15.3 | 44.5 / 22.9 | 75.9 / 61.0 | 130 | | +PriMaPs | DINOv2 ViT-S/14 | 71.5 / 19.0 | 46.5 / 23.8 | 78.5 / 64.3 | 131 | | Baseline | DINOv2 ViT-B/14 | 36.1 / 14.9 | 35.0 / 17.9 | 82.4 / 69.9 | 132 | | +PriMaPs | DINOv2 ViT-B/14 | 82.9 / 21.3 | 52.8 / 23.6 | 83.2 / 71.1 | 133 | | | | | | | 134 | 135 | ## Citation 136 | If you find our work helpful, please consider citing the following paper and ⭐ the repo. 137 | 138 | ``` 139 | @article{Hahn:2024:BUS, 140 | title={Boosting Unsupervised Semantic Segmentation with Principal Mask Proposals}, 141 | author={Oliver Hahn and Nikita Araslanov and Simone Schaub-Meyer and Stefan Roth}, 142 | journal={Transactions on Machine Learning Research (TMLR)}, 143 | year={2024} 144 | } 145 | ``` -------------------------------------------------------------------------------- /primaps_modules/transforms.py: -------------------------------------------------------------------------------- 1 | import torch, random 2 | import torchvision.transforms.functional as F 3 | import torchvision.transforms as tf 4 | import numpy as np 5 | from PIL import Image 6 | from typing import Tuple, List, Callable 7 | 8 | 9 | class Compose: 10 | 11 | def __init__(self, 12 | transforms: List[Callable], 13 | student_augs: bool = False): 14 | self.transforms = transforms 15 | self.student_augs = student_augs 16 | 17 | def __call__(self, 18 | img: Image.Image, 19 | gt: Image.Image, 20 | pseudo = None) -> Tuple[torch.Tensor, torch.Tensor]: 21 | 22 | for transform in self.transforms: 23 | if pseudo is None: 24 | img, gt = transform(img, gt) 25 | else: 26 | img, gt, pseudo = transform(img, gt, pseudo) 27 | 28 | if self.student_augs: 29 | aimg = img.clone() 30 | aimg, _ = RandGaussianBlur()(aimg, gt) 31 | if 0.5 > random.random(): 32 | aimg, _ = ColorJitter()(aimg, gt) 33 | else: 34 | aimg, _ = MaskGrayscale()(aimg, gt) 35 | 36 | 37 | if pseudo is None and not self.student_augs: 38 | return img, gt 39 | elif pseudo is None and self.student_augs: 40 | return img, gt, aimg 41 | elif pseudo is not None and not self.student_augs: 42 | return img, gt, pseudo 43 | else: 44 | return img, gt, aimg, pseudo 45 | 46 | class ToTensor: 47 | 48 | def __call__(self, 49 | img: Image.Image, 50 | gt: Image.Image, 51 | pseudo = None) -> Tuple[torch.Tensor, torch.Tensor]: 52 | 53 | img = F.to_tensor(np.array(img)) 54 | gt = torch.from_numpy(np.array(gt)).unsqueeze(0) 55 | if pseudo is not None: 56 | pseudo = torch.from_numpy(np.array(pseudo)).unsqueeze(0) 57 | 58 | if pseudo is None: 59 | return img, gt 60 | else: 61 | return img, gt, pseudo 62 | 63 | class Resize: 64 | 65 | def __init__(self, 66 | resize: Tuple[int]): 67 | 68 | self.img_resize = tf.Resize(size=resize, 69 | interpolation=tf.InterpolationMode.BILINEAR) 70 | self.gt_resize = tf.Resize(size=resize, 71 | interpolation=tf.InterpolationMode.NEAREST) 72 | 73 | def __call__(self, 74 | img: Image.Image, 75 | gt: Image.Image, 76 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 77 | 78 | img = self.img_resize(img) 79 | gt = self.gt_resize(gt) 80 | 81 | if pseudo is None: 82 | return img, gt 83 | else: 84 | return img, gt, self.gt_resize(pseudo) 85 | 86 | class ImgResize: 87 | 88 | def __init__(self, 89 | resize: Tuple[int, int]): 90 | self.resize = resize 91 | self.num_pixels = self.resize[0]*self.resize[1] 92 | 93 | def __call__(self, 94 | img: torch.Tensor, 95 | gt: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: 96 | if torch.prod(torch.tensor(img.shape[-2:])) > self.num_pixels: 97 | img = torch.nn.functional.interpolate(img.unsqueeze(0), size=self.resize, mode='bilinear').squeeze(0) 98 | return img, gt 99 | 100 | class ImgResizePIL: 101 | 102 | def __init__(self, 103 | resize: Tuple[int]): 104 | self.resize = resize 105 | self.num_pixels = self.resize[0]*self.resize[1] 106 | 107 | def __call__(self, 108 | img: Image) -> Image: 109 | if img.height*img.width > self.num_pixels: 110 | img = img.resize((self.resize[1], self.resize[0]), tf.InterpolationMode.BILINEAR) 111 | return img 112 | 113 | class Normalize: 114 | 115 | def __init__(self, 116 | mean: List[float] = [0.485, 0.456, 0.406], 117 | std: List[float] = [0.229, 0.224, 0.225]): 118 | 119 | self.norm = tf.Normalize(mean=mean, 120 | std=std) 121 | 122 | def __call__(self, 123 | img: torch.Tensor, 124 | gt: torch.Tensor, 125 | pseudo = None) -> Tuple[torch.Tensor, torch.Tensor]: 126 | 127 | img = self.norm(img) 128 | 129 | if pseudo is None: 130 | return img, gt 131 | else: 132 | return img, gt, pseudo 133 | 134 | class UnNormalize(object): 135 | def __init__(self, 136 | mean: List[float] = [0.485, 0.456, 0.406], 137 | std: List[float] = [0.229, 0.224, 0.225]): 138 | self.mean = mean 139 | self.std = std 140 | 141 | def __call__(self, image): 142 | image2 = torch.clone(image) 143 | for t, m, s in zip(image2, self.mean, self.std): 144 | t.mul_(s).add_(m) 145 | return image2 146 | 147 | 148 | 149 | class RandomHFlip: 150 | 151 | def __init__(self, 152 | percentage: float = 0.5): 153 | 154 | self.percentage = percentage 155 | 156 | def __call__(self, 157 | img: Image.Image, 158 | gt: Image.Image, 159 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 160 | 161 | if random.random() < self.percentage: 162 | img = F.hflip(img) 163 | gt = F.hflip(gt) 164 | if pseudo is not None: 165 | pseudo = F.hflip(pseudo) 166 | 167 | if pseudo is None: 168 | return img, gt 169 | else: 170 | return img, gt, pseudo 171 | 172 | 173 | class RandomResizedCrop: 174 | 175 | def __init__(self, 176 | crop_size: List[int], 177 | crop_scale: List[float], 178 | crop_ratio: List[float]): 179 | print('RandomResizedCrop ratio modified!!!') 180 | self.crop_scale = tuple(crop_scale) 181 | self.crop_ratio = tuple(crop_ratio) 182 | self.crop = tf.RandomResizedCrop(size=tuple(crop_size), 183 | scale=self.crop_scale, 184 | ratio=self.crop_ratio,) 185 | 186 | def __call__(self, 187 | img: Image.Image, 188 | gt: Image.Image, 189 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 190 | 191 | i, j, h, w = self.crop.get_params(img=img, 192 | scale=self.crop.scale, 193 | ratio=self.crop.ratio) 194 | img = F.resized_crop(img, i, j, h, w, self.crop.size, tf.InterpolationMode.BILINEAR) 195 | gt = F.resized_crop(gt, i, j, h, w, self.crop.size, tf.InterpolationMode.NEAREST) 196 | if pseudo is not None: 197 | pseudo = F.resized_crop(pseudo, i, j, h, w, self.crop.size, tf.InterpolationMode.NEAREST) 198 | 199 | if pseudo is None: 200 | return img, gt 201 | else: 202 | return img, gt, pseudo 203 | 204 | class CenterCrop: 205 | 206 | def __init__(self, 207 | crop_size: int): 208 | 209 | self.crop = tf.CenterCrop(size=crop_size) 210 | 211 | def __call__(self, 212 | img: Image.Image, 213 | gt: Image.Image, 214 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 215 | 216 | img = self.crop(img) 217 | gt = self.crop(gt) 218 | 219 | if pseudo is None: 220 | return img, gt 221 | else: 222 | return img, gt, self.crop(pseudo) 223 | 224 | class PyramidCenterCrop: 225 | 226 | def __init__(self, 227 | crop_size: List[int], 228 | scales: List[float]): 229 | 230 | self.crop_size = crop_size 231 | self.scales = scales 232 | self.crop = tf.CenterCrop(size=crop_size) 233 | 234 | 235 | def __call__(self, 236 | img: Image.Image, 237 | gt: Image.Image) -> Tuple[Image.Image, Image.Image]: 238 | 239 | imgs = [] 240 | gts = [] 241 | for s in self.scales: 242 | new_size = (int(self.crop_size*1/s), int(self.crop_size*1/s*(img.shape[2]/img.shape[1]))) 243 | img = tf.Resize(size=new_size, interpolation=tf.InterpolationMode.BILINEAR)(img) 244 | gt = tf.Resize(size=new_size, interpolation=tf.InterpolationMode.NEAREST)(gt) 245 | imgs.append(self.crop(img)) 246 | gts.append(self.crop(gt)) 247 | 248 | return torch.stack(imgs), torch.stack(gts) 249 | 250 | 251 | 252 | 253 | 254 | 255 | class IdsToTrainIds: 256 | 257 | def __init__(self, 258 | source: str): 259 | 260 | self.source = source 261 | self.first_nonvoid = 7 262 | 263 | 264 | def __call__(self, 265 | img: torch.Tensor, 266 | gt: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: 267 | 268 | if self.source == 'cityscapes': 269 | gt = gt.to(dtype=torch.int64) - self.first_nonvoid 270 | gt[gt>26] = 255 271 | gt[gt<0] = 255 272 | elif self.source == 'cocostuff': 273 | gt = gt.to(dtype=torch.int64) 274 | elif self.source == 'potsdam': 275 | gt = gt.to(dtype=torch.int64) 276 | return img, gt 277 | 278 | 279 | class ColorJitter: 280 | def __init__(self, percentage: float = 0.3, brightness: float = 0.1, 281 | contrast: float = 0.1, saturation: float = 0.1, hue: float = 0.1): 282 | 283 | self.percentage = percentage 284 | self.jitter = tf.ColorJitter(brightness=brightness, 285 | contrast=contrast, 286 | saturation=saturation, 287 | hue=hue) 288 | 289 | def __call__(self, 290 | img: Image.Image, 291 | gt: Image.Image, 292 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 293 | if random.random() < self.percentage: 294 | img = self.jitter(img) 295 | 296 | if pseudo is None: 297 | return img, gt 298 | else: 299 | return img, gt, pseudo 300 | 301 | class MaskGrayscale: 302 | 303 | def __init__(self, percentage: float = 0.1): 304 | self.percentage = percentage 305 | 306 | def __call__(self, 307 | img: Image.Image, 308 | gt: Image.Image, 309 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 310 | if self.percentage > random.random(): 311 | img = tf.Grayscale(num_output_channels=3)(img) 312 | if pseudo is None: 313 | return img, gt 314 | else: 315 | return img, gt, pseudo 316 | 317 | class RandGaussianBlur: 318 | 319 | def __init__(self, radius: List[float] = [.1, 2.]): 320 | self.radius = radius 321 | 322 | def __call__(self, 323 | img: Image.Image, 324 | gt: Image.Image, 325 | pseudo = None) -> Tuple[Image.Image, Image.Image]: 326 | 327 | radius = random.uniform(self.radius[0], self.radius[1]) 328 | img = tf.GaussianBlur(kernel_size=21, sigma=radius)(img) 329 | 330 | if pseudo is None: 331 | return img, gt 332 | else: 333 | return img, gt, pseudo 334 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/vision_transformer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """ 15 | Mostly copy-paste from timm library. 16 | https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py 17 | """ 18 | import math 19 | from functools import partial 20 | 21 | import torch 22 | import torch.nn as nn 23 | from primaps_modules.backbone.dino.utils import trunc_normal_ 24 | 25 | def drop_path(x, drop_prob: float = 0., training: bool = False): 26 | if drop_prob == 0. or not training: 27 | return x 28 | keep_prob = 1 - drop_prob 29 | shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets 30 | random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) 31 | random_tensor.floor_() # binarize 32 | output = x.div(keep_prob) * random_tensor 33 | return output 34 | 35 | 36 | class DropPath(nn.Module): 37 | """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). 38 | """ 39 | def __init__(self, drop_prob=None): 40 | super(DropPath, self).__init__() 41 | self.drop_prob = drop_prob 42 | 43 | def forward(self, x): 44 | return drop_path(x, self.drop_prob, self.training) 45 | 46 | 47 | class Mlp(nn.Module): 48 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 49 | super().__init__() 50 | out_features = out_features or in_features 51 | hidden_features = hidden_features or in_features 52 | self.fc1 = nn.Linear(in_features, hidden_features) 53 | self.act = act_layer() 54 | self.fc2 = nn.Linear(hidden_features, out_features) 55 | self.drop = nn.Dropout(drop) 56 | 57 | def forward(self, x): 58 | x = self.fc1(x) 59 | x = self.act(x) 60 | x = self.drop(x) 61 | x = self.fc2(x) 62 | x = self.drop(x) 63 | return x 64 | 65 | 66 | class Attention(nn.Module): 67 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): 68 | super().__init__() 69 | self.num_heads = num_heads 70 | head_dim = dim // num_heads 71 | self.scale = qk_scale or head_dim ** -0.5 72 | 73 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 74 | self.attn_drop = nn.Dropout(attn_drop) 75 | self.proj = nn.Linear(dim, dim) 76 | self.proj_drop = nn.Dropout(proj_drop) 77 | 78 | def forward(self, x, return_qkv=False): 79 | B, N, C = x.shape 80 | qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 81 | q, k, v = qkv[0], qkv[1], qkv[2] 82 | 83 | attn = (q @ k.transpose(-2, -1)) * self.scale 84 | attn = attn.softmax(dim=-1) 85 | attn = self.attn_drop(attn) 86 | 87 | x = (attn @ v).transpose(1, 2).reshape(B, N, C) 88 | x = self.proj(x) 89 | x = self.proj_drop(x) 90 | return x,attn, qkv 91 | 92 | 93 | 94 | class Block(nn.Module): 95 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., 96 | drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): 97 | super().__init__() 98 | self.norm1 = norm_layer(dim) 99 | self.attn = Attention( 100 | dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 101 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 102 | self.norm2 = norm_layer(dim) 103 | mlp_hidden_dim = int(dim * mlp_ratio) 104 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 105 | 106 | def forward(self, x, return_attention=False, return_qkv = False): 107 | y, attn, qkv = self.attn(self.norm1(x)) 108 | if return_attention: 109 | return attn 110 | x = x + self.drop_path(y) 111 | x = x + self.drop_path(self.mlp(self.norm2(x))) 112 | if return_qkv: 113 | return x,attn, qkv 114 | return x 115 | 116 | 117 | class PatchEmbed(nn.Module): 118 | """ Image to Patch Embedding 119 | """ 120 | def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): 121 | super().__init__() 122 | num_patches = (img_size // patch_size) * (img_size // patch_size) 123 | self.img_size = img_size 124 | self.patch_size = patch_size 125 | self.num_patches = num_patches 126 | 127 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) 128 | 129 | def forward(self, x): 130 | B, C, H, W = x.shape 131 | x = self.proj(x).flatten(2).transpose(1, 2) 132 | return x 133 | 134 | 135 | class VisionTransformer(nn.Module): 136 | """ Vision Transformer """ 137 | def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12, 138 | num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., 139 | drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs): 140 | super().__init__() 141 | 142 | self.num_features = self.embed_dim = embed_dim 143 | 144 | self.patch_embed = PatchEmbed( 145 | img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) 146 | num_patches = self.patch_embed.num_patches 147 | 148 | self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) 149 | self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) 150 | self.pos_drop = nn.Dropout(p=drop_rate) 151 | 152 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule 153 | self.blocks = nn.ModuleList([ 154 | Block( 155 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 156 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) 157 | for i in range(depth)]) 158 | self.norm = norm_layer(embed_dim) 159 | 160 | # Classifier head 161 | self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() 162 | 163 | trunc_normal_(self.pos_embed, std=.02) 164 | trunc_normal_(self.cls_token, std=.02) 165 | self.apply(self._init_weights) 166 | 167 | def _init_weights(self, m): 168 | if isinstance(m, nn.Linear): 169 | trunc_normal_(m.weight, std=.02) 170 | if isinstance(m, nn.Linear) and m.bias is not None: 171 | nn.init.constant_(m.bias, 0) 172 | elif isinstance(m, nn.LayerNorm): 173 | nn.init.constant_(m.bias, 0) 174 | nn.init.constant_(m.weight, 1.0) 175 | 176 | def interpolate_pos_encoding(self, x, w, h): 177 | npatch = x.shape[1] - 1 178 | N = self.pos_embed.shape[1] - 1 179 | if npatch == N and w == h: 180 | return self.pos_embed 181 | class_pos_embed = self.pos_embed[:, 0] 182 | patch_pos_embed = self.pos_embed[:, 1:] 183 | dim = x.shape[-1] 184 | w0 = w // self.patch_embed.patch_size 185 | h0 = h // self.patch_embed.patch_size 186 | # we add a small number to avoid floating point error in the interpolation 187 | # see discussion at https://github.com/facebookresearch/dino/issues/8 188 | w0, h0 = w0 + 0.1, h0 + 0.1 189 | patch_pos_embed = nn.functional.interpolate( 190 | patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), 191 | scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), 192 | mode='bicubic', 193 | ) 194 | assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1] 195 | patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) 196 | return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) 197 | 198 | def prepare_tokens(self, x): 199 | B, nc, w, h = x.shape 200 | x = self.patch_embed(x) # patch linear embedding 201 | 202 | # add the [CLS] token to the embed patch tokens 203 | cls_tokens = self.cls_token.expand(B, -1, -1) 204 | x = torch.cat((cls_tokens, x), dim=1) 205 | 206 | # add positional encoding to each token 207 | x = x + self.interpolate_pos_encoding(x, w, h) 208 | 209 | return self.pos_drop(x) 210 | 211 | def forward(self, x): 212 | x = self.prepare_tokens(x) 213 | for blk in self.blocks: 214 | x = blk(x) 215 | x = self.norm(x) 216 | return x[:, 0] 217 | 218 | def forward_feats(self, x): 219 | x = self.prepare_tokens(x) 220 | for blk in self.blocks: 221 | x = blk(x) 222 | x = self.norm(x) 223 | return x 224 | 225 | def get_intermediate_feat(self, x, n=1): 226 | x = self.prepare_tokens(x) 227 | # we return the output tokens from the `n` last blocks 228 | feat = [] 229 | attns = [] 230 | qkvs = [] 231 | for i, blk in enumerate(self.blocks): 232 | x,attn,qkv = blk(x, return_qkv=True) 233 | if len(self.blocks) - i <= n: 234 | feat.append(self.norm(x)) 235 | qkvs.append(qkv) 236 | attns.append(attn) 237 | return feat, attns, qkvs 238 | 239 | def get_last_selfattention(self, x): 240 | x = self.prepare_tokens(x) 241 | for i, blk in enumerate(self.blocks): 242 | if i < len(self.blocks) - 1: 243 | x = blk(x) 244 | else: 245 | # return attention of the last block 246 | return blk(x, return_attention=True) 247 | 248 | def get_intermediate_layers(self, x, n=1): 249 | x = self.prepare_tokens(x) 250 | # we return the output tokens from the `n` last blocks 251 | output = [] 252 | for i, blk in enumerate(self.blocks): 253 | x = blk(x) 254 | if len(self.blocks) - i <= n: 255 | output.append(self.norm(x)) 256 | return output 257 | 258 | 259 | def vit_tiny(patch_size=16, **kwargs): 260 | model = VisionTransformer( 261 | patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4, 262 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 263 | return model 264 | 265 | 266 | def vit_small(patch_size=16, **kwargs): 267 | model = VisionTransformer( 268 | patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, 269 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 270 | return model 271 | 272 | 273 | def vit_base(patch_size=16, **kwargs): 274 | model = VisionTransformer( 275 | patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, 276 | qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 277 | return model 278 | 279 | 280 | class DINOHead(nn.Module): 281 | def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256): 282 | super().__init__() 283 | nlayers = max(nlayers, 1) 284 | if nlayers == 1: 285 | self.mlp = nn.Linear(in_dim, bottleneck_dim) 286 | else: 287 | layers = [nn.Linear(in_dim, hidden_dim)] 288 | if use_bn: 289 | layers.append(nn.BatchNorm1d(hidden_dim)) 290 | layers.append(nn.GELU()) 291 | for _ in range(nlayers - 2): 292 | layers.append(nn.Linear(hidden_dim, hidden_dim)) 293 | if use_bn: 294 | layers.append(nn.BatchNorm1d(hidden_dim)) 295 | layers.append(nn.GELU()) 296 | layers.append(nn.Linear(hidden_dim, bottleneck_dim)) 297 | self.mlp = nn.Sequential(*layers) 298 | self.apply(self._init_weights) 299 | self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False)) 300 | self.last_layer.weight_g.data.fill_(1) 301 | if norm_last_layer: 302 | self.last_layer.weight_g.requires_grad = False 303 | 304 | def _init_weights(self, m): 305 | if isinstance(m, nn.Linear): 306 | trunc_normal_(m.weight, std=.02) 307 | if isinstance(m, nn.Linear) and m.bias is not None: 308 | nn.init.constant_(m.bias, 0) 309 | 310 | def forward(self, x): 311 | x = self.mlp(x) 312 | x = nn.functional.normalize(x, dim=-1, p=2) 313 | x = self.last_layer(x) 314 | return x 315 | -------------------------------------------------------------------------------- /primaps_modules/visualization.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import numpy as np 4 | import torch 5 | import matplotlib.pyplot as plt 6 | from cityscapesscripts.helpers.labels import labels as cs_labels 7 | from datasets.cityscapes import get_cs_labeldata 8 | from datasets.cocostuff import get_coco_labeldata 9 | from datasets.potsdam import get_pd_labeldata 10 | 11 | sys.path.append(os.getcwd()) 12 | import primaps_modules.transforms as transforms 13 | 14 | 15 | def visualize_segmentation(img = None, 16 | label = None, 17 | linear = None, 18 | mlp = None, 19 | cluster = None, 20 | dataset_name = None, 21 | additional = None, 22 | additional_name = None, 23 | additional2 = None, 24 | additional_name2 = None, 25 | legend = None, 26 | name = None): 27 | 28 | 29 | if dataset_name == "cityscapes": 30 | colormap = np.array([ 31 | [128, 64, 128], 32 | [244, 35, 232], 33 | [250, 170, 160], 34 | [230, 150, 140], 35 | [70, 70, 70], 36 | [102, 102, 156], 37 | [190, 153, 153], 38 | [180, 165, 180], 39 | [150, 100, 100], 40 | [150, 120, 90], 41 | [153, 153, 153], 42 | [153, 153, 153], 43 | [250, 170, 30], 44 | [220, 220, 0], 45 | [107, 142, 35], 46 | [152, 251, 152], 47 | [70, 130, 180], 48 | [220, 20, 60], 49 | [255, 0, 0], 50 | [0, 0, 142], 51 | [0, 0, 70], 52 | [0, 60, 100], 53 | [0, 0, 90], 54 | [0, 0, 110], 55 | [0, 80, 100], 56 | [0, 0, 230], 57 | [119, 11, 32], 58 | [0, 0, 0], 59 | [220, 220, 220]]) 60 | elif dataset_name == "cocostuff": 61 | colormap = get_coco_labeldata()[-1] 62 | 63 | 64 | orig_h, orig_w = label.cpu().shape[-2:] 65 | img = img.cpu().squeeze(0).numpy().transpose(1, 2, 0) 66 | img = (img-img.min())/(img-img.min()).max() 67 | label = label.cpu().squeeze(0).numpy().transpose(1, 2, 0) 68 | #transforms.labelIdsToTrainIds(source="cityscapes", target="cityscapes") 69 | 70 | label[label == 255] = 27 71 | colored_label = colormap[label.flatten()] 72 | colored_label = colored_label.reshape(orig_h, orig_w, 3) 73 | 74 | num_subplots = 3 75 | if linear != None: num_subplots += 1 76 | if mlp != None: num_subplots += 1 77 | if additional != None: num_subplots += 1 78 | if additional2 != None: num_subplots += 1 79 | 80 | 81 | fig = plt.figure(figsize=(8, 2), dpi=200) 82 | fig.tight_layout() 83 | plt.axis('off') 84 | plt.subplot(1, num_subplots, 1) 85 | plt.gca().set_title('Image') 86 | plt.imshow(img) 87 | plt.axis("off") 88 | plt.subplot(1, num_subplots, 2) 89 | plt.gca().set_title('Ground Truth') 90 | plt.imshow(colored_label) 91 | plt.axis("off") 92 | i = 3 93 | if linear != None: 94 | linear = linear.cpu().numpy().transpose(1, 2, 0).astype('uint8') 95 | linear = colormap[linear.flatten()].reshape(linear.shape[0], linear.shape[1], 3) 96 | plt.axis("off") 97 | plt.subplot(1, num_subplots, i) 98 | plt.gca().set_title('Linear') 99 | plt.imshow(linear) 100 | i+=1 101 | 102 | if mlp != None: 103 | mlp = mlp.cpu().numpy().transpose(1, 2, 0).astype('uint8') 104 | mlp = colormap[mlp.flatten()].reshape(mlp.shape[0], mlp.shape[1], 3) 105 | plt.axis("off") 106 | plt.subplot(1, num_subplots, i) 107 | plt.gca().set_title('MLP') 108 | plt.imshow(mlp) 109 | plt.axis("off") 110 | i+=1 111 | 112 | if cluster != None: 113 | cluster = cluster.cpu().numpy().transpose(1, 2, 0).astype('uint8') 114 | cluster = colormap[cluster.flatten()].reshape(cluster.shape[0], cluster.shape[1], 3) 115 | plt.axis("off") 116 | plt.subplot(1, num_subplots, i) 117 | plt.gca().set_title('Cluster') 118 | plt.imshow(cluster) 119 | plt.axis("off") 120 | i+=1 121 | 122 | if additional != None: 123 | #additional = additional.cpu().numpy() 124 | additional = additional.cpu().numpy().transpose(1, 2, 0).astype('uint8') 125 | additional = colormap[additional.flatten()].reshape(additional.shape[0], additional.shape[1], 3) 126 | plt.axis("off") 127 | plt.subplot(1, num_subplots, i) 128 | plt.gca().set_title(additional_name) 129 | plt.imshow(additional) 130 | plt.axis("off") 131 | i+=1 132 | 133 | if additional2 != None: 134 | additional2 = additional2.cpu().numpy() 135 | plt.axis("off") 136 | plt.subplot(1, num_subplots, i) 137 | plt.gca().set_title(additional_name2) 138 | plt.imshow(additional2) 139 | plt.axis("off") 140 | i+=1 141 | 142 | 143 | # if legend != None: 144 | # from matplotlib.lines import Line2D 145 | 146 | # legend_elements = [Line2D([0], [0], color=np.array(cls[7])/255, lw=4, label=cls[0]) for cls in cs_labels[7:-1]] 147 | 148 | # # Create the figure 149 | # #fig, ax = plt.subplots() 150 | # plt.legend(handles=legend_elements, loc='right') 151 | 152 | 153 | 154 | if name != None: plt.savefig(name) 155 | fig.canvas.draw() 156 | # Now we can save it to a numpy array. 157 | data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) 158 | data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) 159 | plt.close('all') 160 | 161 | return data 162 | 163 | 164 | 165 | def visualize_confusion_matrix(cls_names, meter, name=None): 166 | # plot of confusion matrix 167 | conf_matrix = (meter.histogram/meter.histogram.sum(dim=0)) 168 | conf_matrix = np.array(conf_matrix.cpu(), dtype=np.float16) 169 | fig, ax = plt.subplots(figsize=(15, 15)) 170 | ax.matshow(torch.Tensor(conf_matrix).fill_diagonal_(0), cmap=plt.cm.Blues, alpha=0.8) 171 | for i in range(conf_matrix.shape[0]): 172 | for j in range(conf_matrix.shape[1]): 173 | ax.text(x=j, y=i,s=(conf_matrix[i, j]*100).round(1), va='center', ha='center', size='large') 174 | ax.set_xticks(list(range(cls_names.__len__()))) 175 | ax.set_xticklabels(cls_names, rotation=90, ha='center', fontsize=12) 176 | ax.set_yticks(list(range(cls_names.__len__()))) 177 | ax.set_yticklabels(cls_names, fontsize=12) 178 | plt.xlabel('Predictions', fontsize=18) 179 | plt.ylabel('Actuals', fontsize=18) 180 | plt.title('Confusion Matrix', fontsize=18) 181 | 182 | if name != None: plt.savefig(name) 183 | fig.canvas.draw() 184 | # Now we can save it to a numpy array. 185 | data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) 186 | data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) 187 | plt.close('all') 188 | return data 189 | 190 | 191 | 192 | 193 | 194 | def batch_visualize_segmentation(img = None, 195 | label = None, 196 | in1 = None, 197 | in2 = None, 198 | in3 = None, 199 | in4 = None, 200 | dataset_name = None): 201 | 202 | 203 | if dataset_name == "cityscapes": 204 | colormap = get_cs_labeldata()[-1] 205 | elif dataset_name == "cocostuff": 206 | colormap = get_coco_labeldata()[-1] 207 | elif dataset_name == "potsdam": 208 | colormap = get_pd_labeldata()[-1] 209 | 210 | def _vis_one_img(idx, img, label, ins): 211 | 212 | orig_h, orig_w = label.cpu().shape[-2:] 213 | img = img.cpu().numpy().transpose(1, 2, 0) 214 | img = (img-img.min())/(img-img.min()).max() 215 | label = label.cpu().numpy().transpose(1, 2, 0) 216 | label[label > 27] = 27 217 | colored_label = colormap[label.flatten()].reshape(orig_h, orig_w, 3) 218 | 219 | num_subplots = sum([1 for x in [in1, in2, in3, in4] if x != None]) + 2 220 | 221 | fig = plt.figure(figsize=(10, 2), dpi=150) 222 | fig.tight_layout() 223 | plt.axis('off') 224 | plt.subplot(1, num_subplots, 1) 225 | if idx == 0: plt.gca().set_title('Image') 226 | plt.imshow(img) 227 | plt.axis("off") 228 | plt.subplot(1, num_subplots, 2) 229 | if idx == 0: plt.gca().set_title('Ground Truth') 230 | plt.imshow(colored_label) 231 | plt.axis("off") 232 | if ins != None: 233 | i = 3 234 | for input in ins: 235 | vis = input[1].cpu().numpy().transpose(1, 2, 0).astype('uint8') 236 | vis = colormap[vis.flatten()].reshape(vis.shape[0], vis.shape[1], 3) 237 | plt.axis("off") 238 | plt.subplot(1, num_subplots, i) 239 | if idx == 0: plt.gca().set_title(input[0]) 240 | plt.imshow(vis) 241 | plt.axis("off") 242 | i+=1 243 | 244 | fig.canvas.draw() 245 | plt.close('all') 246 | one_vis = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) 247 | one_vis = one_vis.reshape(fig.canvas.get_width_height()[::-1] + (3,)) 248 | plt.close('all') 249 | return one_vis 250 | 251 | imgs = [] 252 | for idx, (data) in enumerate(zip(img, label)): 253 | imgs.append(_vis_one_img(idx, data[0], data[1], [[i[0], i[1][idx].unsqueeze(0)] for i in [in1, in2, in3, in4] if i!=None])) 254 | 255 | return np.vstack(imgs) 256 | 257 | 258 | 259 | def visualize_single_masks(img, 260 | label, 261 | data, 262 | dataset_name = None): 263 | 264 | 265 | if dataset_name == "cityscapes": 266 | colormap = get_cs_labeldata()[-1] 267 | elif dataset_name == "cocostuff": 268 | colormap = get_coco_labeldata()[-1] 269 | elif dataset_name == "potsdam": 270 | colormap = get_pd_labeldata()[-1] 271 | 272 | 273 | fig = plt.figure(figsize=(data['sim'].__len__()*2, 7*2), dpi=150) 274 | fig.tight_layout() 275 | for indx, (sim, nnsim, nnsim_thresh, crf, pamr, mask) in enumerate(zip(data['sim'], data['nnsim'], data['nnsim_tresh'], data['crf'], data['pamr'], data['outmask'])): 276 | rows = data['sim'].__len__() 277 | cols = 8 278 | plotlabel=colormap[label.squeeze(0).squeeze(0).int().cpu()] 279 | plt.subplot(rows, cols, 1+(indx*cols)) 280 | img = (img-img.min())/(img.max()-img.min()) 281 | if indx == 0: plt.title('Image') 282 | plt.imshow(img.squeeze(0).permute(1, 2, 0).cpu()) 283 | plt.axis('off') 284 | plt.subplot(rows, cols, 2+(indx*cols)) 285 | if indx == 0: plt.title('GT') 286 | plt.imshow(plotlabel) 287 | plt.axis('off') 288 | plt.subplot(rows, cols, 3+(indx*cols)) 289 | if indx == 0: plt.title('1.Eig') 290 | plt.imshow(sim.cpu().numpy()) 291 | plt.axis('off') 292 | plt.subplot(rows, cols, 4+(indx*cols)) 293 | if indx == 0: plt.title('1.EigNN') 294 | plt.imshow(nnsim.cpu().numpy()) 295 | plt.axis('off') 296 | plt.subplot(rows, cols, 5+(indx*cols)) 297 | if indx == 0: plt.title('+Thresh') 298 | plt.imshow(nnsim_thresh) 299 | plt.axis('off') 300 | plt.subplot(rows, cols, 6+(indx*cols)) 301 | if indx == 0: plt.title('+CRF') 302 | plt.imshow(crf) 303 | plt.axis('off') 304 | plt.subplot(rows, cols, 7+(indx*cols)) 305 | if indx == 0: plt.title('PAMR') 306 | plt.imshow(pamr.squeeze().cpu().numpy()) 307 | plt.axis('off') 308 | plt.subplot(rows, cols, 8+(indx*cols)) 309 | if indx == 0: plt.title('Mask') 310 | mask[0, 0] = 0 311 | plt.imshow(mask.numpy(), cmap='Greys') 312 | plt.axis('off') 313 | # plt.savefig(str(idx)+'.png', tight_layout=True) 314 | 315 | 316 | fig.canvas.draw() 317 | plt.close('all') 318 | one_vis = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) 319 | one_vis = one_vis.reshape(fig.canvas.get_width_height()[::-1] + (3,)) 320 | plt.close('all') 321 | return one_vis 322 | 323 | 324 | 325 | 326 | 327 | def visualize_pseudo_paper(img, 328 | label, 329 | pseudo_gt, 330 | pseudo_plain, 331 | dataset_name = None, 332 | save_name = None): 333 | 334 | 335 | if dataset_name == "cityscapes": 336 | colormap = get_cs_labeldata()[-1] 337 | elif dataset_name == "cocostuff": 338 | colormap = get_coco_labeldata()[-1] 339 | elif dataset_name == "potsdam": 340 | colormap = get_pd_labeldata()[-1] 341 | 342 | 343 | np.random.seed(0) 344 | cb_colomap = np.array([list(np.random.randint(0, 255, size=(1,3))[0]) for _ in range(400)]+[[0, 0, 0]]) 345 | pseudo_plain = pseudo_plain.int().cpu() 346 | pseudo_plain[pseudo_plain==255] = 400 347 | pseudo_plain = cb_colomap[pseudo_plain.int().cpu()].squeeze() 348 | 349 | 350 | 351 | 352 | fig = plt.figure(figsize=(8, 2), dpi=150) 353 | fig.subplots_adjust(left=0.1, 354 | bottom=0.1, 355 | right=0.5, 356 | top=0.5, 357 | wspace=0.05, 358 | hspace=0.0) 359 | 360 | plt.subplot(1, 4, 1) 361 | img = (img-img.min())/(img.max()-img.min()) 362 | img = img.squeeze(0).permute(1, 2, 0).cpu() 363 | plt.imshow(img) 364 | plt.axis('off') 365 | 366 | plt.subplot(1, 4, 2) 367 | plotlabel=colormap[label.squeeze(0).squeeze(0).int().cpu()] 368 | plt.imshow(plotlabel) 369 | plt.axis('off') 370 | 371 | plt.subplot(1, 4, 3) 372 | plotpseudo=colormap[pseudo_gt.squeeze(0).squeeze(0).int().cpu()] 373 | # pseudo_plain = np.array(pseudo_plain.cpu(), dtype=np.int16).squeeze() 374 | # plotpseudo = mark_boundaries(plotlabel/255, pseudo_plain, color=(1, 1, 1)) 375 | plt.imshow(plotpseudo) 376 | plt.axis('off') 377 | 378 | plt.subplot(1, 4, 4) 379 | plt.imshow(pseudo_plain) 380 | plt.axis('off') 381 | plt.savefig(save_name+'.pdf', bbox_inches='tight', pad_inches=0.0) 382 | 383 | 384 | save_name_single = os.path.join(os.path.dirname(save_name), 'singleimgs/') 385 | os.makedirs(os.path.dirname(save_name_single), exist_ok=True) 386 | for i, n in zip([img, plotlabel, plotpseudo, pseudo_plain], ['img', 'gt', 'pseudo', 'pseudoc']): 387 | fig = plt.figure(figsize=(2, 2), dpi=300) 388 | plt.imshow(i) 389 | plt.axis('off') 390 | plt.savefig(os.path.join(save_name_single, os.path.split(save_name)[-1]+'_'+n+'.png'), bbox_inches='tight', pad_inches=0.0) 391 | 392 | 393 | 394 | 395 | 396 | def logits_to_image(logits = None, 397 | img = None, 398 | label = None, 399 | dataset_name = None, 400 | save_path = None, 401 | save_imggt = False): 402 | 403 | 404 | if dataset_name == "cityscapes": 405 | colormap = get_cs_labeldata()[-1] 406 | elif dataset_name == "cocostuff": 407 | colormap = get_coco_labeldata()[-1] 408 | elif dataset_name == "potsdam": 409 | colormap = get_pd_labeldata()[-1] 410 | 411 | vis = logits.cpu().numpy().transpose(1, 2, 0).astype('uint8') 412 | vis = colormap[vis.flatten()].reshape(vis.shape[0], vis.shape[1], 3) 413 | 414 | fig = plt.figure(figsize=(2, 2), dpi=400) 415 | fig.tight_layout() 416 | plt.subplot(1, 1, 1) 417 | plt.imshow(vis) 418 | plt.axis("off") 419 | plt.savefig(save_path+'_pred.png', bbox_inches='tight', pad_inches=0.0) 420 | plt.close('all') 421 | 422 | if save_imggt: 423 | orig_h, orig_w = label.cpu().shape[-2:] 424 | img = img.cpu().numpy().transpose(1, 2, 0) 425 | img = (img-img.min())/(img-img.min()).max() 426 | label = label.cpu().numpy().transpose(1, 2, 0) 427 | label[label > 27] = 27 428 | colored_label = colormap[label.flatten()].reshape(orig_h, orig_w, 3) 429 | 430 | fig = plt.figure(figsize=(2, 2), dpi=400) 431 | fig.tight_layout() 432 | plt.subplot(1, 1, 1) 433 | plt.imshow(img) 434 | plt.axis("off") 435 | plt.savefig(save_path+'_img.png', bbox_inches='tight', pad_inches=0.0) 436 | plt.close('all') 437 | 438 | fig = plt.figure(figsize=(2, 2), dpi=400) 439 | fig.tight_layout() 440 | plt.subplot(1, 1, 1) 441 | plt.imshow(colored_label) 442 | plt.axis("off") 443 | plt.savefig(save_path+'_gt.png', bbox_inches='tight', pad_inches=0.0) 444 | plt.close('all') 445 | 446 | 447 | 448 | 449 | class Vis_Demo(): 450 | def __init__(self): 451 | super(Vis_Demo, self).__init__() 452 | self.colormap = get_coco_labeldata()[-1] 453 | 454 | def apply_colors(self, logits): 455 | vis = logits.cpu().numpy().transpose(1, 2, 0).astype('uint8') 456 | vis = self.colormap[vis.flatten()].reshape(vis.shape[0], vis.shape[1], 3) 457 | return vis 458 | 459 | 460 | 461 | def visualize_demo(img, pseudo, alpha = 0.5): 462 | np.random.seed(0) 463 | cb_colomap = np.array([list(np.random.randint(0, 255, size=(1,3))[0]) for _ in range(400)]+[[0, 0, 0]]) 464 | pseudo_plain = pseudo.long().cpu().numpy() 465 | pseudo_plain[pseudo_plain==255] = 400 466 | pseudo_plain = cb_colomap[pseudo_plain].squeeze() 467 | 468 | img = transforms.UnNormalize()(img)*255 469 | img = img.permute(1, 2, 0).long().cpu().numpy() 470 | out = alpha*img + (1-alpha)*pseudo_plain 471 | 472 | return np.array(out, dtype=np.uint8) 473 | 474 | -------------------------------------------------------------------------------- /primaps_modules/backbone/dino/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """ 15 | Misc functions. 16 | 17 | Mostly copy-paste from torchvision references or other public repos like DETR: 18 | https://github.com/facebookresearch/detr/blob/master/util/misc.py 19 | """ 20 | import os 21 | import sys 22 | import time 23 | import math 24 | import random 25 | import datetime 26 | import subprocess 27 | from collections import defaultdict, deque 28 | 29 | import numpy as np 30 | import torch 31 | from torch import nn 32 | import torch.distributed as dist 33 | from PIL import ImageFilter, ImageOps 34 | 35 | 36 | class GaussianBlur(object): 37 | """ 38 | Apply Gaussian Blur to the PIL image. 39 | """ 40 | def __init__(self, p=0.5, radius_min=0.1, radius_max=2.): 41 | self.prob = p 42 | self.radius_min = radius_min 43 | self.radius_max = radius_max 44 | 45 | def __call__(self, img): 46 | do_it = random.random() <= self.prob 47 | if not do_it: 48 | return img 49 | 50 | return img.filter( 51 | ImageFilter.GaussianBlur( 52 | radius=random.uniform(self.radius_min, self.radius_max) 53 | ) 54 | ) 55 | 56 | 57 | class Solarization(object): 58 | """ 59 | Apply Solarization to the PIL image. 60 | """ 61 | def __init__(self, p): 62 | self.p = p 63 | 64 | def __call__(self, img): 65 | if random.random() < self.p: 66 | return ImageOps.solarize(img) 67 | else: 68 | return img 69 | 70 | 71 | def load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size): 72 | if os.path.isfile(pretrained_weights): 73 | state_dict = torch.load(pretrained_weights, map_location="cpu") 74 | if checkpoint_key is not None and checkpoint_key in state_dict: 75 | print(f"Take key {checkpoint_key} in provided checkpoint dict") 76 | state_dict = state_dict[checkpoint_key] 77 | # remove `module.` prefix 78 | state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} 79 | # remove `backbone.` prefix induced by multicrop wrapper 80 | state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} 81 | msg = model.load_state_dict(state_dict, strict=False) 82 | print('Pretrained weights found at {} and loaded with msg: {}'.format(pretrained_weights, msg)) 83 | else: 84 | print("Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.") 85 | url = None 86 | if model_name == "vit_small" and patch_size == 16: 87 | url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth" 88 | elif model_name == "vit_small" and patch_size == 8: 89 | url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth" 90 | elif model_name == "vit_base" and patch_size == 16: 91 | url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth" 92 | elif model_name == "vit_base" and patch_size == 8: 93 | url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth" 94 | if url is not None: 95 | print("Since no pretrained weights have been provided, we load the reference pretrained DINO weights.") 96 | state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url) 97 | model.load_state_dict(state_dict, strict=True) 98 | else: 99 | print("There is no reference weights available for this model => We use random weights.") 100 | 101 | 102 | def clip_gradients(model, clip): 103 | norms = [] 104 | for name, p in model.named_parameters(): 105 | if p.grad is not None: 106 | param_norm = p.grad.data.norm(2) 107 | norms.append(param_norm.item()) 108 | clip_coef = clip / (param_norm + 1e-6) 109 | if clip_coef < 1: 110 | p.grad.data.mul_(clip_coef) 111 | return norms 112 | 113 | 114 | def cancel_gradients_last_layer(epoch, model, freeze_last_layer): 115 | if epoch >= freeze_last_layer: 116 | return 117 | for n, p in model.named_parameters(): 118 | if "last_layer" in n: 119 | p.grad = None 120 | 121 | 122 | def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs): 123 | """ 124 | Re-start from checkpoint 125 | """ 126 | if not os.path.isfile(ckp_path): 127 | return 128 | print("Found checkpoint at {}".format(ckp_path)) 129 | 130 | # open checkpoint file 131 | checkpoint = torch.load(ckp_path, map_location="cpu") 132 | 133 | # key is what to look for in the checkpoint file 134 | # value is the object to load 135 | # example: {'state_dict': model} 136 | for key, value in kwargs.items(): 137 | if key in checkpoint and value is not None: 138 | try: 139 | msg = value.load_state_dict(checkpoint[key], strict=False) 140 | print("=> loaded {} from checkpoint '{}' with msg {}".format(key, ckp_path, msg)) 141 | except TypeError: 142 | try: 143 | msg = value.load_state_dict(checkpoint[key]) 144 | print("=> loaded {} from checkpoint '{}'".format(key, ckp_path)) 145 | except ValueError: 146 | print("=> failed to load {} from checkpoint '{}'".format(key, ckp_path)) 147 | else: 148 | print("=> failed to load {} from checkpoint '{}'".format(key, ckp_path)) 149 | 150 | # re load variable important for the run 151 | if run_variables is not None: 152 | for var_name in run_variables: 153 | if var_name in checkpoint: 154 | run_variables[var_name] = checkpoint[var_name] 155 | 156 | 157 | def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0): 158 | warmup_schedule = np.array([]) 159 | warmup_iters = warmup_epochs * niter_per_ep 160 | if warmup_epochs > 0: 161 | warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) 162 | 163 | iters = np.arange(epochs * niter_per_ep - warmup_iters) 164 | schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) 165 | 166 | schedule = np.concatenate((warmup_schedule, schedule)) 167 | assert len(schedule) == epochs * niter_per_ep 168 | return schedule 169 | 170 | 171 | def bool_flag(s): 172 | """ 173 | Parse boolean arguments from the command line. 174 | """ 175 | FALSY_STRINGS = {"off", "false", "0"} 176 | TRUTHY_STRINGS = {"on", "true", "1"} 177 | if s.lower() in FALSY_STRINGS: 178 | return False 179 | elif s.lower() in TRUTHY_STRINGS: 180 | return True 181 | else: 182 | raise argparse.ArgumentTypeError("invalid value for a boolean flag") 183 | 184 | 185 | def fix_random_seeds(seed=31): 186 | """ 187 | Fix random seeds. 188 | """ 189 | torch.manual_seed(seed) 190 | torch.cuda.manual_seed_all(seed) 191 | np.random.seed(seed) 192 | 193 | 194 | class SmoothedValue(object): 195 | """Track a series of values and provide access to smoothed values over a 196 | window or the global series average. 197 | """ 198 | 199 | def __init__(self, window_size=20, fmt=None): 200 | if fmt is None: 201 | fmt = "{median:.6f} ({global_avg:.6f})" 202 | self.deque = deque(maxlen=window_size) 203 | self.total = 0.0 204 | self.count = 0 205 | self.fmt = fmt 206 | 207 | def update(self, value, n=1): 208 | self.deque.append(value) 209 | self.count += n 210 | self.total += value * n 211 | 212 | def synchronize_between_processes(self): 213 | """ 214 | Warning: does not synchronize the deque! 215 | """ 216 | if not is_dist_avail_and_initialized(): 217 | return 218 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 219 | dist.barrier() 220 | dist.all_reduce(t) 221 | t = t.tolist() 222 | self.count = int(t[0]) 223 | self.total = t[1] 224 | 225 | @property 226 | def median(self): 227 | d = torch.tensor(list(self.deque)) 228 | return d.median().item() 229 | 230 | @property 231 | def avg(self): 232 | d = torch.tensor(list(self.deque), dtype=torch.float32) 233 | return d.mean().item() 234 | 235 | @property 236 | def global_avg(self): 237 | return self.total / self.count 238 | 239 | @property 240 | def max(self): 241 | return max(self.deque) 242 | 243 | @property 244 | def value(self): 245 | return self.deque[-1] 246 | 247 | def __str__(self): 248 | return self.fmt.format( 249 | median=self.median, 250 | avg=self.avg, 251 | global_avg=self.global_avg, 252 | max=self.max, 253 | value=self.value) 254 | 255 | 256 | def reduce_dict(input_dict, average=True): 257 | """ 258 | Args: 259 | input_dict (dict): all the values will be reduced 260 | average (bool): whether to do average or sum 261 | Reduce the values in the dictionary from all processes so that all processes 262 | have the averaged results. Returns a dict with the same fields as 263 | input_dict, after reduction. 264 | """ 265 | world_size = get_world_size() 266 | if world_size < 2: 267 | return input_dict 268 | with torch.no_grad(): 269 | names = [] 270 | values = [] 271 | # sort the keys so that they are consistent across processes 272 | for k in sorted(input_dict.keys()): 273 | names.append(k) 274 | values.append(input_dict[k]) 275 | values = torch.stack(values, dim=0) 276 | dist.all_reduce(values) 277 | if average: 278 | values /= world_size 279 | reduced_dict = {k: v for k, v in zip(names, values)} 280 | return reduced_dict 281 | 282 | 283 | class MetricLogger(object): 284 | def __init__(self, delimiter="\t"): 285 | self.meters = defaultdict(SmoothedValue) 286 | self.delimiter = delimiter 287 | 288 | def update(self, **kwargs): 289 | for k, v in kwargs.items(): 290 | if isinstance(v, torch.Tensor): 291 | v = v.item() 292 | assert isinstance(v, (float, int)) 293 | self.meters[k].update(v) 294 | 295 | def __getattr__(self, attr): 296 | if attr in self.meters: 297 | return self.meters[attr] 298 | if attr in self.__dict__: 299 | return self.__dict__[attr] 300 | raise AttributeError("'{}' object has no attribute '{}'".format( 301 | type(self).__name__, attr)) 302 | 303 | def __str__(self): 304 | loss_str = [] 305 | for name, meter in self.meters.items(): 306 | loss_str.append( 307 | "{}: {}".format(name, str(meter)) 308 | ) 309 | return self.delimiter.join(loss_str) 310 | 311 | def synchronize_between_processes(self): 312 | for meter in self.meters.values(): 313 | meter.synchronize_between_processes() 314 | 315 | def add_meter(self, name, meter): 316 | self.meters[name] = meter 317 | 318 | def log_every(self, iterable, print_freq, header=None): 319 | i = 0 320 | if not header: 321 | header = '' 322 | start_time = time.time() 323 | end = time.time() 324 | iter_time = SmoothedValue(fmt='{avg:.6f}') 325 | data_time = SmoothedValue(fmt='{avg:.6f}') 326 | space_fmt = ':' + str(len(str(len(iterable)))) + 'd' 327 | if torch.cuda.is_available(): 328 | log_msg = self.delimiter.join([ 329 | header, 330 | '[{0' + space_fmt + '}/{1}]', 331 | 'eta: {eta}', 332 | '{meters}', 333 | 'time: {time}', 334 | 'data: {data}', 335 | 'max mem: {memory:.0f}' 336 | ]) 337 | else: 338 | log_msg = self.delimiter.join([ 339 | header, 340 | '[{0' + space_fmt + '}/{1}]', 341 | 'eta: {eta}', 342 | '{meters}', 343 | 'time: {time}', 344 | 'data: {data}' 345 | ]) 346 | MB = 1024.0 * 1024.0 347 | for obj in iterable: 348 | data_time.update(time.time() - end) 349 | yield obj 350 | iter_time.update(time.time() - end) 351 | if i % print_freq == 0 or i == len(iterable) - 1: 352 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 353 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 354 | if torch.cuda.is_available(): 355 | print(log_msg.format( 356 | i, len(iterable), eta=eta_string, 357 | meters=str(self), 358 | time=str(iter_time), data=str(data_time), 359 | memory=torch.cuda.max_memory_allocated() / MB)) 360 | else: 361 | print(log_msg.format( 362 | i, len(iterable), eta=eta_string, 363 | meters=str(self), 364 | time=str(iter_time), data=str(data_time))) 365 | i += 1 366 | end = time.time() 367 | total_time = time.time() - start_time 368 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 369 | print('{} Total time: {} ({:.6f} s / it)'.format( 370 | header, total_time_str, total_time / len(iterable))) 371 | 372 | 373 | def get_sha(): 374 | cwd = os.path.dirname(os.path.abspath(__file__)) 375 | 376 | def _run(command): 377 | return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() 378 | sha = 'N/A' 379 | diff = "clean" 380 | branch = 'N/A' 381 | try: 382 | sha = _run(['git', 'rev-parse', 'HEAD']) 383 | subprocess.check_output(['git', 'diff'], cwd=cwd) 384 | diff = _run(['git', 'diff-index', 'HEAD']) 385 | diff = "has uncommited changes" if diff else "clean" 386 | branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) 387 | except Exception: 388 | pass 389 | message = f"sha: {sha}, status: {diff}, branch: {branch}" 390 | return message 391 | 392 | 393 | def is_dist_avail_and_initialized(): 394 | if not dist.is_available(): 395 | return False 396 | if not dist.is_initialized(): 397 | return False 398 | return True 399 | 400 | 401 | def get_world_size(): 402 | if not is_dist_avail_and_initialized(): 403 | return 1 404 | return dist.get_world_size() 405 | 406 | 407 | def get_rank(): 408 | if not is_dist_avail_and_initialized(): 409 | return 0 410 | return dist.get_rank() 411 | 412 | 413 | def is_main_process(): 414 | return get_rank() == 0 415 | 416 | 417 | def save_on_master(*args, **kwargs): 418 | if is_main_process(): 419 | torch.save(*args, **kwargs) 420 | 421 | 422 | def setup_for_distributed(is_master): 423 | """ 424 | This function disables printing when not in master process 425 | """ 426 | import builtins as __builtin__ 427 | builtin_print = __builtin__.print 428 | 429 | def print(*args, **kwargs): 430 | force = kwargs.pop('force', False) 431 | if is_master or force: 432 | builtin_print(*args, **kwargs) 433 | 434 | __builtin__.print = print 435 | 436 | 437 | def init_distributed_mode(args): 438 | # launched with torch.distributed.launch 439 | if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 440 | args.rank = int(os.environ["RANK"]) 441 | args.world_size = int(os.environ['WORLD_SIZE']) 442 | args.gpu = int(os.environ['LOCAL_RANK']) 443 | # launched with submitit on a slurm cluster 444 | elif 'SLURM_PROCID' in os.environ: 445 | args.rank = int(os.environ['SLURM_PROCID']) 446 | args.gpu = args.rank % torch.cuda.device_count() 447 | # launched naively with `python main_dino.py` 448 | # we manually add MASTER_ADDR and MASTER_PORT to env variables 449 | elif torch.cuda.is_available(): 450 | print('Will run the code on one GPU.') 451 | args.rank, args.gpu, args.world_size = 0, 0, 1 452 | os.environ['MASTER_ADDR'] = '127.0.0.1' 453 | os.environ['MASTER_PORT'] = '29500' 454 | else: 455 | print('Does not support training without GPU.') 456 | sys.exit(1) 457 | 458 | dist.init_process_group( 459 | backend="nccl", 460 | init_method=args.dist_url, 461 | world_size=args.world_size, 462 | rank=args.rank, 463 | ) 464 | 465 | torch.cuda.set_device(args.gpu) 466 | print('| distributed init (rank {}): {}'.format( 467 | args.rank, args.dist_url), flush=True) 468 | dist.barrier() 469 | setup_for_distributed(args.rank == 0) 470 | 471 | 472 | def accuracy(output, target, topk=(1,)): 473 | """Computes the accuracy over the k top predictions for the specified values of k""" 474 | maxk = max(topk) 475 | batch_size = target.size(0) 476 | _, pred = output.topk(maxk, 1, True, True) 477 | pred = pred.t() 478 | correct = pred.eq(target.reshape(1, -1).expand_as(pred)) 479 | return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] 480 | 481 | 482 | def _no_grad_trunc_normal_(tensor, mean, std, a, b): 483 | # Cut & paste from PyTorch official master until it's in a few official releases - RW 484 | # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf 485 | def norm_cdf(x): 486 | # Computes standard normal cumulative distribution function 487 | return (1. + math.erf(x / math.sqrt(2.))) / 2. 488 | 489 | if (mean < a - 2 * std) or (mean > b + 2 * std): 490 | warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " 491 | "The distribution of values may be incorrect.", 492 | stacklevel=2) 493 | 494 | with torch.no_grad(): 495 | # Values are generated by using a truncated uniform distribution and 496 | # then using the inverse CDF for the normal distribution. 497 | # Get upper and lower cdf values 498 | l = norm_cdf((a - mean) / std) 499 | u = norm_cdf((b - mean) / std) 500 | 501 | # Uniformly fill tensor with values from [l, u], then translate to 502 | # [2l-1, 2u-1]. 503 | tensor.uniform_(2 * l - 1, 2 * u - 1) 504 | 505 | # Use inverse cdf transform for normal distribution to get truncated 506 | # standard normal 507 | tensor.erfinv_() 508 | 509 | # Transform to proper mean, std 510 | tensor.mul_(std * math.sqrt(2.)) 511 | tensor.add_(mean) 512 | 513 | # Clamp to ensure it's in the proper range 514 | tensor.clamp_(min=a, max=b) 515 | return tensor 516 | 517 | 518 | def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): 519 | # type: (Tensor, float, float, float, float) -> Tensor 520 | return _no_grad_trunc_normal_(tensor, mean, std, a, b) 521 | 522 | 523 | class LARS(torch.optim.Optimizer): 524 | """ 525 | Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py 526 | """ 527 | def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001, 528 | weight_decay_filter=None, lars_adaptation_filter=None): 529 | defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, 530 | eta=eta, weight_decay_filter=weight_decay_filter, 531 | lars_adaptation_filter=lars_adaptation_filter) 532 | super().__init__(params, defaults) 533 | 534 | @torch.no_grad() 535 | def step(self): 536 | for g in self.param_groups: 537 | for p in g['params']: 538 | dp = p.grad 539 | 540 | if dp is None: 541 | continue 542 | 543 | if p.ndim != 1: 544 | dp = dp.add(p, alpha=g['weight_decay']) 545 | 546 | if p.ndim != 1: 547 | param_norm = torch.norm(p) 548 | update_norm = torch.norm(dp) 549 | one = torch.ones_like(param_norm) 550 | q = torch.where(param_norm > 0., 551 | torch.where(update_norm > 0, 552 | (g['eta'] * param_norm / update_norm), one), one) 553 | dp = dp.mul(q) 554 | 555 | param_state = self.state[p] 556 | if 'mu' not in param_state: 557 | param_state['mu'] = torch.zeros_like(p) 558 | mu = param_state['mu'] 559 | mu.mul_(g['momentum']).add_(dp) 560 | 561 | p.add_(mu, alpha=-g['lr']) 562 | 563 | 564 | class MultiCropWrapper(nn.Module): 565 | """ 566 | Perform forward pass separately on each resolution input. 567 | The inputs corresponding to a single resolution are clubbed and single 568 | forward is run on the same resolution inputs. Hence we do several 569 | forward passes = number of different resolutions used. We then 570 | concatenate all the output features and run the head forward on these 571 | concatenated features. 572 | """ 573 | def __init__(self, backbone, head): 574 | super(MultiCropWrapper, self).__init__() 575 | # disable layers dedicated to ImageNet labels classification 576 | backbone.fc, backbone.head = nn.Identity(), nn.Identity() 577 | self.backbone = backbone 578 | self.head = head 579 | 580 | def forward(self, x): 581 | # convert to list 582 | if not isinstance(x, list): 583 | x = [x] 584 | idx_crops = torch.cumsum(torch.unique_consecutive( 585 | torch.tensor([inp.shape[-1] for inp in x]), 586 | return_counts=True, 587 | )[1], 0) 588 | start_idx = 0 589 | for end_idx in idx_crops: 590 | _out = self.backbone(torch.cat(x[start_idx: end_idx])) 591 | if start_idx == 0: 592 | output = _out 593 | else: 594 | output = torch.cat((output, _out)) 595 | start_idx = end_idx 596 | # Run the head forward on the concatenated features. 597 | return self.head(output) 598 | 599 | 600 | def get_params_groups(model): 601 | regularized = [] 602 | not_regularized = [] 603 | for name, param in model.named_parameters(): 604 | if not param.requires_grad: 605 | continue 606 | # we do not regularize biases nor Norm parameters 607 | if name.endswith(".bias") or len(param.shape) == 1: 608 | not_regularized.append(param) 609 | else: 610 | regularized.append(param) 611 | return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}] 612 | 613 | 614 | def has_batchnorms(model): 615 | bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) 616 | for name, module in model.named_modules(): 617 | if isinstance(module, bn_types): 618 | return True 619 | return False 620 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import random 4 | import pathlib 5 | import json 6 | import numpy as np 7 | from datetime import datetime 8 | from tqdm import tqdm as tqdm_bar 9 | import torchvision 10 | import torch 11 | import torch.nn as nn 12 | import torch.nn.functional as F 13 | import torchvision.transforms.functional as VF 14 | from torch.utils.data import DataLoader 15 | from pytorch_lightning.utilities.seed import seed_everything 16 | from pytorch_lightning.callbacks import ModelCheckpoint 17 | import pytorch_lightning as pl 18 | from pytorch_lightning import Trainer 19 | from pytorch_lightning.loggers import TensorBoardLogger 20 | from multiprocessing import get_context 21 | torch.autograd.set_detect_anomaly(True) 22 | 23 | 24 | from primaps_modules.primaps import PriMaPs 25 | from primaps_modules.backbone.dino.dinovit import DinoFeaturizerv2 26 | from primaps_modules.ema import EMA 27 | import datasets 28 | from datasets.cocostuff import get_coco_labeldata 29 | from primaps_modules.metrics import UnsupervisedMetrics 30 | import primaps_modules.transforms as transforms 31 | from primaps_modules.visualization import visualize_confusion_matrix, batch_visualize_segmentation 32 | from datasets.cityscapes import classes as cs_classes 33 | from datasets.potsdam import classes as pd_classes 34 | from primaps_modules.parser import train_parser 35 | from primaps_modules.clustering import ConvClusterProbe 36 | from primaps_modules.clustering import ClusterLoss 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | class UnsupervisedSegmenter(pl.LightningModule): 45 | def __init__(self, opts): 46 | super().__init__() 47 | self.opts = opts 48 | 49 | if os.path.split(self.opts.dataset_root)[-1] == 'cityscapes': 50 | self.dataset_info = cs_classes 51 | elif os.path.split(self.opts.dataset_root)[-1] == 'cocostuff': 52 | self.dataset_info = get_coco_labeldata()[0] 53 | elif os.path.split(self.opts.dataset_root)[-1] == 'potsdam': 54 | self.dataset_info = pd_classes 55 | 56 | if ('stego_ckpt' in [a[0] for a in vars(opts).items()] and opts.stego_ckpt != ''): 57 | print('-- train on top of stego') 58 | sys.path.append(os.path.join(os.getcwd(), 'external', 'STEGO', 'src')) 59 | from train_segmentation import LitUnsupervisedSegmenter 60 | 61 | class STEGOFeaturizer(): 62 | def __init__(self, stego_ckpt): 63 | super(STEGOFeaturizer).__init__() 64 | self.model = LitUnsupervisedSegmenter.load_from_checkpoint(stego_ckpt).net.to('cuda:'+str(opts.gpu_ids[0])) 65 | opts.backbone_dim = self.model.cluster1[0].weight.shape[0] 66 | def __call__(self, x, n): 67 | return self.model(x)[-1] 68 | self.net = STEGOFeaturizer(opts.stego_ckpt) 69 | elif ('hp_ckpt' in [a[0] for a in vars(opts).items()] and opts.hp_ckpt != ''): 70 | print('-- train on top of HP') 71 | sys.path.append(os.path.join(os.getcwd(), 'external', 'HP')) 72 | from build import build_model 73 | from utils.common_utils import parse 74 | 75 | class HPFeaturizer(): 76 | def __init__(self, ckpt_dir, opt_dir): 77 | super(HPFeaturizer).__init__() 78 | parser_opt = parse(opts.hp_opt) 79 | self.model, _, _ = build_model(opt=parser_opt["model"], 80 | n_classes=opts.num_classes, 81 | is_direct=parser_opt["eval"]["is_direct"]) 82 | self.model.to(torch.device('cuda:'+str(opts.gpu_ids[0]))) 83 | self.model.eval() 84 | checkpoint_loaded = torch.load(ckpt_dir, map_location=torch.device('cuda:'+str(opts.gpu_ids[0]))) 85 | self.model.load_state_dict(checkpoint_loaded['net_model_state_dict'], strict=True) 86 | opts.backbone_dim = self.model.ema_model1[0].weight.shape[0] 87 | def __call__(self, x, n): 88 | return self.model(x)[1] 89 | self.net = HPFeaturizer(opts.hp_ckpt, opts.hp_opt) 90 | 91 | else: 92 | self.net = DinoFeaturizerv2(self.opts.backbone_arch, self.opts.backbone_patch) 93 | 94 | self.cluster_probe = ConvClusterProbe(opts.backbone_dim, opts.num_classes) 95 | self.cluster_loss = ClusterLoss() 96 | self.test_cluster_metrics = UnsupervisedMetrics("final/cluster/", self.opts.num_classes, 0, True) 97 | 98 | self.pseudo_decomposer = PriMaPs(threshold=opts.threshold, 99 | ignore_id=opts.ignore_label) 100 | 101 | self.linear_probe = nn.Conv2d(opts.backbone_dim, self.opts.num_classes, (1, 1)) 102 | self.linear_probe_loss_fn = torch.nn.CrossEntropyLoss(ignore_index=self.opts.ignore_label, reduction='none') 103 | self.test_linear_metrics = UnsupervisedMetrics("final/linear/", self.opts.num_classes, 0, False) 104 | 105 | self.seghead = nn.utils.weight_norm(nn.Conv2d(opts.backbone_dim, self.opts.num_classes, (1, 1), bias=False), name='weight', dim=0) 106 | 107 | class FocalLoss(): 108 | def __init__(self, gamma, ignore_id): 109 | super(FocalLoss).__init__() 110 | self.gamma = gamma 111 | self.ignore_index = ignore_id 112 | 113 | def __call__(self, logits, pseudo_gt): 114 | mean_cls_conf = logits.detach().clone().softmax(1).permute(1, 0, 2, 3).reshape(logits.size(1), -1).mean(dim=1) 115 | focal_weight = (1-mean_cls_conf)**self.gamma 116 | focalloss = F.cross_entropy(logits, pseudo_gt, weight=focal_weight ,ignore_index=self.ignore_index, reduction="none").mean() 117 | return focalloss 118 | 119 | self.seghead_loss = FocalLoss(opts.seghead_focalloss, opts.ignore_label) 120 | self.seghead_metrics = UnsupervisedMetrics("final/seghead/", self.opts.num_classes, 0, True) 121 | 122 | self.max_metrics = {'THETA_M Accuracy': 0, 'Linear Accuracy': 0, 'THETA_R Accuracy': 0, 123 | 'THETA_M mIoU': 0, 'Linear mIoU': 0, 'THETA_R mIoU': 0} 124 | 125 | self.automatic_optimization = False 126 | self.vis_img_eval = [] 127 | self.vis_train = [] 128 | self.save_hyperparameters() 129 | 130 | if self.opts.cluster_ckpt_path != "": 131 | print('-- Init cluster from checkpoint...') 132 | weights = torch.load(self.opts.cluster_ckpt_path)['state_dict']['cluster_probe.cluster_centers.weight_v'].to(self.device) 133 | self.cluster_probe.cluster_centers.weight_v = torch.nn.Parameter(weights.detach().clone()) 134 | self.seghead.weight_v = torch.nn.Parameter(weights.detach().clone()) 135 | self.seghead.weight_g = torch.nn.Parameter(torch.ones_like(self.seghead.weight_g)) 136 | 137 | if ('stego_ckpt' in [a[0] for a in vars(opts).items()] and opts.stego_ckpt != ''): 138 | print('-- cluster weights from STEGO') 139 | cluster_weights = LitUnsupervisedSegmenter.load_from_checkpoint(opts.stego_ckpt).cluster_probe.clusters 140 | self.cluster_probe.cluster_centers.weight_v = torch.nn.Parameter(cluster_weights.unsqueeze(-1).unsqueeze(-1).detach().clone()) 141 | self.seghead.weight_v = torch.nn.Parameter(cluster_weights.unsqueeze(-1).unsqueeze(-1).detach().clone()) 142 | self.seghead.weight_g = torch.nn.Parameter(torch.ones_like(self.seghead.weight_g)) 143 | 144 | if ('hp_ckpt' in [a[0] for a in vars(opts).items()] and opts.hp_ckpt != ''): 145 | print('-- cluster weights from HP') 146 | cluster_weights = torch.load(opts.hp_ckpt)['cluster_model_state_dict']['clusters'] 147 | self.seghead.weight_v = torch.nn.Parameter(cluster_weights.unsqueeze(-1).unsqueeze(-1).detach().clone()) 148 | self.seghead.weight_g = torch.nn.Parameter(torch.ones_like(self.seghead.weight_g)) 149 | 150 | 151 | def training_step(self, batch, batch_idx): 152 | log_args = dict(sync_dist=False, rank_zero_only=True) 153 | 154 | # Optimizers 155 | linear_probe_optim, cluster_probe_optim, seghead_optim = self.optimizers() 156 | linear_probe_optim.zero_grad() 157 | cluster_probe_optim.zero_grad() 158 | seghead_optim.zero_grad() 159 | 160 | label = batch[1] 161 | with torch.no_grad(): 162 | features = self.net(batch[0], n=self.opts.dino_block).detach().clone() 163 | 164 | lin_feats = features.detach().clone() 165 | linear_logits = self.linear_probe(lin_feats) 166 | linear_logits = F.interpolate(linear_logits, batch[1].shape[-2:], mode='bilinear', align_corners=False) 167 | linear_loss = self.linear_probe_loss_fn(linear_logits, label.squeeze(1)).mean() 168 | 169 | 170 | if self.opts.train_state == 'baseline': 171 | cluster_probs = self.cluster_probe(features.detach().clone()) 172 | cluster_loss, _ = self.cluster_loss(cluster_probs) 173 | cluster_preds = cluster_probs.argmax(1) 174 | seghead_logits = self.seghead(features.detach().clone()) 175 | pseudogt = cluster_preds 176 | seghead_loss = 0.0 177 | 178 | 179 | if self.opts.train_state == 'method': 180 | cluster_loss = 0.0 181 | features = F.interpolate(features, label.shape[-2:], mode='bilinear', align_corners=False) 182 | cluster_probs = self.cluster_probe(features) 183 | cluster_preds = cluster_probs.argmax(1) 184 | 185 | if (self.opts.precomp_primaps or self.opts.precomp_primaps_root != ''): 186 | cls_prior = cluster_preds 187 | 188 | pseudogt = [] 189 | for cls, msk in zip(cls_prior, batch[-1].squeeze()): 190 | pseudo = torch.ones_like(msk).to('cpu')*self.opts.ignore_label 191 | for m in msk.unique()[msk.unique()!=self.opts.ignore_label]: 192 | fill = (pseudo==self.opts.ignore_label)*(msk==m).to('cpu') 193 | try: 194 | pseudo_id = cls[fill][cls[fill] != self.opts.ignore_label].mode()[0] 195 | except: 196 | print('-- Error matching pseudo mask') 197 | pseudo_id = self.opts.ignore_label 198 | pseudo[fill] = pseudo_id 199 | pseudogt.append(pseudo) 200 | pseudogt = torch.stack(pseudogt).long().to(self.device) 201 | 202 | if self.opts.student_augs: 203 | with torch.no_grad(): 204 | features = self.net(batch[2], n=self.opts.dino_block).detach().clone() 205 | features = F.interpolate(features, label.shape[-2:], mode='bilinear', align_corners=False) 206 | 207 | seghead_logits = self.seghead(features.detach().clone()) 208 | seghead_loss = self.seghead_loss(seghead_logits, pseudogt) 209 | 210 | loss = linear_loss + cluster_loss + seghead_loss 211 | self.log('loss/linear', linear_loss, **log_args) 212 | self.log('loss/cluster', cluster_loss, **log_args) 213 | self.log('loss/seghead', seghead_loss, **log_args) 214 | 215 | self.manual_backward(loss) 216 | linear_probe_optim.step() 217 | cluster_probe_optim.step() 218 | seghead_optim.step() 219 | 220 | ### Exponential Moving Average 221 | if self.opts.train_state == 'method': 222 | if self.global_step > 0 and self.global_step%self.opts.ema_update_step == 0 and self.opts.ema_update_step != -1: 223 | print('-- EMA weights to cluster') 224 | self.cluster_probe.update() 225 | 226 | 227 | ### Visualize 228 | if batch_idx == 0 and self.opts.gpu_ids.__len__() == 1: 229 | print('-- Visualize Train Batch') 230 | num_vis = 4 231 | cluster_preds = F.interpolate(cluster_preds.unsqueeze(1).float(), label.shape[-2:], mode='nearest').long().squeeze(1).to('cpu') 232 | seghead_logits = F.interpolate(seghead_logits.float(), label.shape[-2:], mode='nearest').long().to('cpu') 233 | pseudogt = F.interpolate(pseudogt.unsqueeze(1).float(), label.shape[-2:], mode='nearest').long().squeeze(1).to('cpu') 234 | self.test_cluster_metrics.update(cluster_preds.to('cpu'), label.to('cpu')) 235 | self.seghead_metrics.update(seghead_logits.argmax(1).to('cpu'), label.to('cpu')) 236 | self.test_cluster_metrics.compute() 237 | self.seghead_metrics.compute() 238 | vis_pseudo = pseudogt.detach().clone().to('cpu') 239 | vis_pseudo[vis_pseudo None: 296 | super().validation_epoch_end(outputs) 297 | log_args = dict(sync_dist=False, rank_zero_only=True) 298 | tb_metrics = { 299 | **self.test_linear_metrics.compute(), 300 | **self.test_cluster_metrics.compute(), 301 | **self.seghead_metrics.compute(), 302 | } 303 | print(tb_metrics) 304 | 305 | print('--------------------------------------------------') 306 | print('THETA_M mIoU: '+ str(round(tb_metrics['final/cluster/mIoU'], 4))) 307 | print('THETA_R mIoU: '+ str(round(tb_metrics['final/seghead/mIoU'], 4))) 308 | print('Linear mIoU: '+ str(round(tb_metrics['final/linear/mIoU'], 4))) 309 | print('--------------------------------------------------') 310 | log_args = dict(sync_dist=False, rank_zero_only=True) 311 | self.log('iou/linear', tb_metrics['final/linear/mIoU'], **log_args) 312 | self.log('accuracy/linear', tb_metrics['final/linear/Accuracy'], **log_args) 313 | self.log('iou/cluster', tb_metrics['final/cluster/mIoU'], **log_args) 314 | self.log('accuracy/cluster', tb_metrics['final/cluster/Accuracy'], **log_args) 315 | self.log('iou/seghead', tb_metrics['final/seghead/mIoU'], **log_args) 316 | self.log('accuracy/seghead', tb_metrics['final/seghead/Accuracy'], **log_args) 317 | 318 | if self.max_metrics['THETA_M mIoU'] < tb_metrics['final/cluster/mIoU']: 319 | self.max_metrics['THETA_M mIoU'] = tb_metrics['final/cluster/mIoU'] 320 | self.max_metrics['THETA_M Accuracy'] = tb_metrics['final/cluster/Accuracy'] 321 | if self.max_metrics['Linear mIoU'] < tb_metrics['final/linear/mIoU']: 322 | self.max_metrics['Linear mIoU'] = tb_metrics['final/linear/mIoU'] 323 | self.max_metrics['Linear Accuracy'] = tb_metrics['final/linear/Accuracy'] 324 | if self.max_metrics['THETA_R mIoU'] < tb_metrics['final/seghead/mIoU']: 325 | self.max_metrics['THETA_R mIoU'] = tb_metrics['final/seghead/mIoU'] 326 | self.max_metrics['THETA_R Accuracy'] = tb_metrics['final/seghead/Accuracy'] 327 | max_metrics_txt = "".join("\t" + line for line in json.dumps([str(met)+" : "+str(self.max_metrics[met]) for met in self.max_metrics], indent=2).splitlines(True)) 328 | self.logger.experiment.add_text('Max Matrics', max_metrics_txt, self.global_step) 329 | print('-- Max Metrics: '+str(self.max_metrics)) 330 | 331 | clsiou_txt = "".join("\t" + line for line in json.dumps([str(round(ln,2))+"; "+str(round(cl, 2))+"; "+str(round(sh, 2))+"; -- "+str(cls) for cls, ln, cl, sh in zip(self.dataset_info, tb_metrics['final/linear/Class IoUs'], tb_metrics['final/cluster/Class IoUs'], tb_metrics['final/seghead/Class IoUs'])], indent=2).splitlines(True)) 332 | self.logger.experiment.add_text('Class IoUs', clsiou_txt, global_step=self.global_step) 333 | self.logger.experiment.add_image('Cluster Confusion Matrix', 334 | visualize_confusion_matrix(self.dataset_info, self.test_cluster_metrics.to('cpu')).transpose(2, 0, 1), 335 | global_step=self.global_step) 336 | if self.vis_img_eval != []: 337 | self.logger.experiment.add_image('Eval Visualization', self.vis_img_eval, global_step=self.global_step) 338 | if self.vis_train != []: 339 | self.logger.experiment.add_image('Train Visualization', self.vis_train, global_step=self.global_step) 340 | self.logger.experiment.add_image('Linear Confusion Matrix', 341 | visualize_confusion_matrix(self.dataset_info, self.test_linear_metrics.to('cpu')).transpose(2, 0, 1), 342 | global_step=self.global_step) 343 | self.test_linear_metrics.reset() 344 | self.test_cluster_metrics.reset() 345 | self.seghead_metrics.reset() 346 | 347 | 348 | def configure_optimizers(self): 349 | linear_probe_optim = torch.optim.Adam(list(self.linear_probe.parameters()), lr=self.opts.linear_lr) 350 | seghead_optim = torch.optim.Adam(list(self.seghead.parameters()), lr=self.opts.seghead_lr) 351 | cluster_probe_optim = torch.optim.Adam(list(self.cluster_probe.parameters()), lr=self.opts.cluster_lr) 352 | return linear_probe_optim, cluster_probe_optim, seghead_optim 353 | 354 | 355 | 356 | 357 | def main(opts): 358 | # Create checkpoints directory 359 | now = datetime.now().strftime("%y%m%d-%H%M%S") 360 | opts.checkpoints_root = os.path.join(opts.checkpoints_root, now.split('-')[0]) 361 | opts.log_name = opts.log_name+'_'+now.split('-')[1] 362 | opts.logg_root = os.path.join(opts.logg_root, now.split('-')[0]) 363 | pathlib.Path(opts.checkpoints_root).mkdir(parents=True, exist_ok=True) 364 | pathlib.Path(opts.logg_root).mkdir(parents=True, exist_ok=True) 365 | # Setup dataset 366 | seed_everything(seed=opts.seed, workers=True) 367 | np.random.seed(opts.seed) 368 | random.seed(opts.seed) 369 | torch.manual_seed(opts.seed) 370 | torch.cuda.manual_seed(opts.seed) 371 | torch.backends.cudnn.deterministic = True 372 | torch.backends.cudnn.benchmark = False 373 | os.environ["PYTHONHASHSEED"] = str(opts.seed) 374 | 375 | dataset_name = os.path.split(opts.dataset_root)[-1] 376 | train_transforms = transforms.Compose([transforms.Resize([opts.crop_size[0]]), 377 | transforms.CenterCrop([opts.crop_size[0], opts.crop_size[0]]), 378 | transforms.RandomResizedCrop(opts.crop_size, opts.augs_randcrop_scale, opts.augs_randcrop_ratio), 379 | transforms.ToTensor(), 380 | transforms.IdsToTrainIds(source=dataset_name), 381 | transforms.Normalize()]) 382 | val_transforms = transforms.Compose([transforms.ToTensor(), 383 | transforms.IdsToTrainIds(source=dataset_name), 384 | transforms.Resize(opts.validation_resize), 385 | transforms.CenterCrop([opts.validation_resize[0], opts.validation_resize[0]]), 386 | transforms.Normalize()]) 387 | 388 | train_dataset = datasets.__dict__[dataset_name](root=opts.dataset_root, 389 | split="train", 390 | transforms=train_transforms) 391 | val_dataset = datasets.__dict__[dataset_name](root=opts.dataset_root, 392 | split="val", 393 | transforms=val_transforms) 394 | 395 | # Dataloader 396 | train_loader = DataLoader(train_dataset, 397 | batch_size=opts.batch_size, 398 | num_workers=opts.num_workers, 399 | sampler=None, 400 | shuffle=True, 401 | drop_last=True, 402 | pin_memory=True if torch.cuda.is_available() else False) 403 | val_loader = DataLoader(val_dataset, 404 | batch_size=opts.eval_batch_size, 405 | num_workers=opts.num_workers, 406 | sampler=None, 407 | shuffle=False, 408 | pin_memory=True if torch.cuda.is_available() else False) 409 | model = UnsupervisedSegmenter(opts) 410 | print('-- Dataset sizes: Train: '+str(train_dataset.__len__())+' Val: '+str(val_dataset.__len__())) 411 | 412 | 413 | if opts.precomp_primaps: 414 | train_transforms = transforms.Compose([transforms.Resize([opts.crop_size[0]]), 415 | transforms.CenterCrop([opts.crop_size[0], opts.crop_size[0]]), 416 | transforms.RandomResizedCrop(opts.crop_size, opts.augs_randcrop_scale, opts.augs_randcrop_ratio), 417 | transforms.ToTensor(), 418 | transforms.IdsToTrainIds(source=dataset_name), 419 | transforms.Normalize()]) 420 | train_dataset = datasets.__dict__[dataset_name](root=opts.dataset_root, 421 | split="train", 422 | transforms=train_transforms) 423 | train_loader = DataLoader(train_dataset, 424 | batch_size=opts.batch_size, 425 | num_workers=opts.num_workers, 426 | sampler=None, 427 | shuffle=False, 428 | pin_memory=True if torch.cuda.is_available() else False) 429 | 430 | 431 | print('-- Precompute Pseudo Dataset') 432 | dir_names = ['imgs', 'gts', 'pseudos'] 433 | if opts.precomp_primaps_root != '': 434 | root_pth = opts.precomp_primaps_root 435 | else: 436 | root_pth = os.path.join(os.path.dirname(opts.dataset_root), 'cached_datasets', opts.log_name) 437 | for dir_name in dir_names: 438 | os.makedirs(os.path.join(root_pth, dir_name), exist_ok=True) 439 | model.to(torch.device('cuda', opts.gpu_ids[0])) 440 | 441 | # Write parser to folder 442 | f = open(os.path.join(root_pth, 'parser.txt'), "a") 443 | for a, b in vars(opts).items(): 444 | f.write(str(a)+" : "+str(b)+"\n") 445 | f.close() 446 | 447 | 448 | with get_context('forkserver').Pool(opts.num_workers) as pool: 449 | for _, (batch) in tqdm_bar(enumerate(train_loader)): 450 | 451 | names = [os.path.split(p)[-1].replace('_leftImg8bit.png', '').replace('.jpg', '')+'.png' for p in batch[-1]] 452 | mask = torch.Tensor([os.path.isfile(os.path.join(root_pth, dir_names[-1], i))==False for i in names]).bool() 453 | if (mask==False).all(): 454 | print('-- All pseudos already computed') 455 | continue 456 | else: 457 | batch[0] = batch[0][mask] 458 | batch[1] = batch[1][mask] 459 | names = [n for i, n in enumerate(names) if mask[i]==True] 460 | 461 | print('-- Compute %s' %batch[-1]) 462 | imgs = batch[0].to(model.device) 463 | labels = batch[1] 464 | with torch.no_grad(): 465 | feats = model.net(imgs, n=opts.dino_block) 466 | pseudos = model.pseudo_decomposer(pool, batch[0], feats, torch.zeros_like(feats)).long() 467 | for name, i ,l, p in zip(names, imgs.to('cpu'), labels, pseudos.to('cpu')): 468 | VF.to_pil_image(transforms.UnNormalize()(i)).save(os.path.join(root_pth, dir_names[0], name)) 469 | torchvision.io.write_png(l.type(torch.uint8), os.path.join(root_pth, dir_names[1], name)) 470 | print('-- Write data to %s', os.path.join(root_pth, dir_names[2], name)) 471 | torchvision.io.write_png(p.unsqueeze(0).type(torch.uint8), os.path.join(root_pth, dir_names[2], name)) 472 | del pseudos, feats, imgs, labels 473 | torch.cuda.empty_cache() 474 | print('-- Cached dataset successfully') 475 | sys.exit() 476 | 477 | if (opts.precomp_primaps or opts.precomp_primaps_root != ''): 478 | train_transforms = [ 479 | transforms.Resize([opts.crop_size[0]]), 480 | transforms.CenterCrop([opts.validation_resize[0], opts.validation_resize[0]]), 481 | transforms.RandomResizedCrop(opts.crop_size, opts.augs_randcrop_scale, opts.augs_randcrop_ratio), 482 | transforms.RandomHFlip()] 483 | if opts.augs_photometric: train_transforms + [ 484 | transforms.RandGaussianBlur(), 485 | transforms.ColorJitter(), 486 | transforms.MaskGrayscale()] 487 | train_transforms = transforms.Compose(train_transforms+[transforms.ToTensor(), transforms.Normalize()], opts.student_augs) 488 | train_dataset = datasets.PrecomputedDataset(opts.precomp_primaps_root if opts.precomp_primaps_root != '' else root_pth, 489 | transforms=train_transforms, 490 | student_augs=opts.student_augs) 491 | train_loader = DataLoader(train_dataset, 492 | batch_size=opts.batch_size, 493 | num_workers=opts.num_workers, 494 | sampler=None, 495 | shuffle=True, 496 | drop_last=True, 497 | pin_memory=True if torch.cuda.is_available() else False) 498 | 499 | print('-- Cached Dataset sizes: Train: '+str(train_dataset.__len__())+' Val: '+str(val_dataset.__len__())) 500 | print('-- Test cached dataset') 501 | try: 502 | all_iter = 0 503 | for batch in tqdm_bar(train_loader): 504 | count_iter = batch[-1].clone() 505 | count_iter[count_iter==255] = 0 506 | all_iter = all_iter + count_iter.squeeze(1).flatten(1).max(dim=-1)[0].sum() 507 | print('Iter per sample %s' %(all_iter/train_loader.sampler.num_samples)) 508 | except: 509 | print('-- Cached dataset corrupted!') 510 | sys.exit() 511 | 512 | if opts.pcainit: 513 | print('-- PCA cluster initialization') 514 | with torch.no_grad(): 515 | model.to(torch.device('cuda', opts.gpu_ids[0])) 516 | pca_init = [] 517 | for idx, (batch) in tqdm_bar(enumerate(train_loader)): 518 | if idx > opts.num_batch_pcainit: 519 | break 520 | feats = model.net(batch[0].to(device=model.device), n=opts.dino_block) 521 | pca_init.append(feats.permute(1, 0, 2, 3).reshape(feats.size(1), -1).to('cpu')) 522 | model.to('cpu') 523 | pca_init = torch.cat(pca_init, 1).permute(1, 0).to(torch.device('cuda', opts.gpu_ids[0])) 524 | 525 | _, _, v = torch.pca_lowrank(pca_init, q=2*opts.num_classes, niter=200) 526 | v = v[:, :opts.num_classes] 527 | pca_weights = v.permute(1, 0).unsqueeze(-1).unsqueeze(-1) 528 | model.cluster_probe.cluster_centers.weight_v = torch.nn.Parameter(pca_weights.detach().clone()) 529 | model.cluster_probe.cluster_centers.weight_g = torch.nn.Parameter(torch.ones_like(model.cluster_probe.cluster_centers.weight_g)) 530 | model.seghead.weight_v = torch.nn.Parameter(pca_weights.detach().clone()) 531 | model.seghead.weight_g = torch.nn.Parameter(torch.ones_like(model.seghead.weight_g)) 532 | del feats, batch, pca_init, v, pca_weights 533 | torch.cuda.empty_cache() 534 | 535 | if dataset_name == 'cityscapes': 536 | gpu_args = dict(gpus=opts.gpu_ids, check_val_every_n_epoch=opts.validation_freq, num_sanity_val_steps=-1) 537 | elif dataset_name == 'cocostuff': 538 | gpu_args = dict(gpus=opts.gpu_ids, val_check_interval=100, num_sanity_val_steps=-1) 539 | elif dataset_name == 'potsdam': 540 | gpu_args = dict(gpus=opts.gpu_ids, check_val_every_n_epoch=opts.validation_freq, num_sanity_val_steps=-1) 541 | 542 | if len(opts.gpu_ids) > 1: 543 | gpu_args['accelerator'] = 'ddp' 544 | logger = TensorBoardLogger(os.path.join(opts.logg_root, opts.log_name), default_hp_metric=False) 545 | parser_txt = "".join("\t" + line for line in json.dumps([str(a)+" : "+str(b) for a, b in vars(opts).items()], indent=2).splitlines(True)) 546 | logger.experiment.add_text('Parser', parser_txt) 547 | 548 | trainer = Trainer(max_epochs=opts.num_epochs, 549 | log_every_n_steps=1, 550 | logger=logger, 551 | benchmark = True, 552 | enable_checkpointing=True, 553 | callbacks=[ModelCheckpoint( 554 | dirpath=os.path.join(opts.checkpoints_root, opts.log_name), 555 | filename='model', 556 | every_n_epochs=opts.validation_freq, 557 | save_top_k=1, 558 | save_last=True if opts.train_state == 'baseline' else False, 559 | monitor="iou/cluster", 560 | mode="max")], 561 | **gpu_args) 562 | trainer.fit(model, train_loader, val_loader) 563 | 564 | 565 | 566 | if __name__ == '__main__': 567 | args = train_parser() 568 | print(args) 569 | main(args) 570 | --------------------------------------------------------------------------------