From masked tokens to object detections in a single denoising step.
DDM-Det · 40.50 AP · 58.82 FPS · One reverse diffusion update
PyTorch implementation · COCO 2017 · Detectron2
Overview · Results · Installation · Data · Evaluation · Training · Inference
This repository accompanies Fast Object Detection via One-Step Discrete Diffusion and implements DDM-Det (Discrete Diffusion Model for Detection). It formulates object detection as image-conditioned generation of discrete tokens: four quantized bounding-box coordinates and one category token per object query.
During training, detection tokens are masked according to a continuous-time noise schedule, and the model learns to recover the targets from the corrupted sequence. At inference, it starts with fully masked detection tokens and predicts boxes and classes in one reverse diffusion update.
flowchart LR
A[Input image] --> B[ResNet-50 + transformer encoder]
B --> D[Image-conditioned decoder]
C[Fully masked detection tokens] --> D
D -->|One reverse diffusion update| E[Box and class tokens]
E --> F[Object detections]
The implementation includes:
- Joint box and category prediction through a shared discrete vocabulary.
- One-step inference, with all detection tokens predicted in parallel.
- Set-based supervision using Hungarian matching and token-level losses.
- A ResNet-50 configuration with modulated deformable convolutions in the last two stages and a six-layer transformer encoder and decoder.
- Training and evaluation utilities for distributed execution, automatic mixed precision, gradient clipping, optional EMA, TensorBoard, and Weights & Biases.
“One step” refers to the reverse diffusion update; the decoder itself contains six transformer layers.
The following results are reported in Tables 1–2 of the manuscript. Comparisons use single-scale backbone features; FPS is reported as end-to-end inference speed.
| Method | Diffusion steps | AP ↑ | AP50 ↑ | AP75 ↑ | FPS ↑ |
|---|---|---|---|---|---|
| DiffusionDet | 1 | 38.17 | 56.56 | 40.23 | 54.75 |
| DiffusionDet | 5 | 39.51 | 59.20 | 41.42 | 23.26 |
| DiffusionDet | 10 | 39.64 | 59.54 | 41.65 | 13.70 |
| DiffuDETR | 1 | 38.06 | 54.74 | 40.83 | 43.63 |
| DiffuDETR | 2 | 39.02 | 56.33 | 41.94 | 34.60 |
| DiffuDETR | 5 | 38.98 | 55.81 | 42.11 | 21.32 |
| DDM-Det | 1 | 40.50 | 60.58 | 42.29 | 58.82 |
DDM-Det achieves +2.33 AP over one-step DiffusionDet. Against ten-step DiffusionDet, it achieves +0.86 AP at approximately 4.3× the reported FPS (58.82 / 13.70).
| DDM-Det | AP | AP50 | AP75 | AP small | AP medium | AP large |
|---|---|---|---|---|---|---|
| ResNet-50, one step | 40.50 | 60.58 | 42.29 | 18.45 | 45.58 | 60.98 |
The manuscript reports experiments on two RTX 5090 GPUs with 32 GB each. These are paper-reported measurements, not a speed guarantee for other hardware or a fresh benchmark of this checkout. The included run_eval.sh evaluates detection accuracy; it is not a dedicated latency benchmark.
Models are trained on COCO and evaluated on CrowdHuman without fine-tuning. Table 3 reports person-category AP50 using visible bounding boxes:
| Method | AP50 ↑ |
|---|---|
| DiffusionDet | 47.25 |
| DiffuDETR | 49.81 |
| DDM-Det | 50.73 |
The configurations included in this checkout target COCO; a CrowdHuman evaluation configuration is not included.
Run all commands from the repository root after cloning or downloading this project.
Use Linux with an NVIDIA GPU and a CUDA-enabled PyTorch installation. The supplied training loop requires CUDA, and the default backbone uses Detectron2's compiled deformable-convolution operators.
conda create -n one-step-det python=3.10 -y conda activate one-step-det python -m pip install --upgrade pip
Install matching torch and torchvision builds for your CUDA environment using the official PyTorch instructions. Then build Detectron2 against that installation:
python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
python -m pip install -r requirements.txt
python -m pip install -U huggingface_hubDetectron2 is required separately; it is not listed in requirements.txt. Building its CUDA operators requires a compatible CUDA toolkit and C++ compiler. See the Detectron2 installation guide for build requirements and troubleshooting.
For reference, an existing COCO evaluation log records this environment:
| Component | Recorded version |
|---|---|
| Python | 3.10.18 |
| PyTorch | 2.8.0+cu129 |
| torchvision | 0.23.0+cu129 |
| Detectron2 | 0.6, built with CUDA 12.9 |
| NumPy | 2.2.5 |
| GPUs | 2 × NVIDIA GeForce RTX 5090 |
These versions describe the recorded evaluation environment.
python -m detectron2.utils.collect_env
python -c "import torch; import detectron2; print('CUDA available:', torch.cuda.is_available())"Download the COCO 2017 training images, validation images, and instance annotations from the COCO website. Arrange them as follows:
datasets/
└── coco/
├── train2017/
│ └── *.jpg
├── val2017/
│ └── *.jpg
└── annotations/
├── instances_train2017.json
└── instances_val2017.json
The configuration uses Detectron2's built-in coco_2017_train and coco_2017_val registrations. If the data is stored elsewhere, point DETECTRON2_DATASETS to the parent of the coco directory:
export DETECTRON2_DATASETS=/absolute/path/to/datasetsWithout this variable, Detectron2 looks under ./datasets. See its built-in dataset documentation for details. Evaluation needs only the validation images and validation annotations.
The main entry point is configs/config_r50_200ep_32bs.py.
| Setting | Value |
|---|---|
| Backbone | ResNet-50; modulated deformable convolutions in res4 and res5 |
| Image features | res5, projected to 256 dimensions |
| Transformer | 6 encoder layers / 6 decoder layers / 8 attention heads |
| Object queries | 100 |
| Detection representation | (x_min, y_min, x_max, y_max, class) tokens |
| Coordinate quantization | 300 bins |
| Categories | 80 COCO classes |
| Noise schedule | Log-linear, eps=1e-3 |
| Reverse diffusion updates | 1 |
| Optimizer | AdamW; learning rate 1e-4, backbone multiplier 0.1 |
| Weight decay | 1e-4 |
| Global training batch size | 32 |
| Training length | 739,400 iterations, approximately 200 COCO epochs |
| Learning-rate schedule | Linear warmup for 5 epochs; decay at epoch 160 |
| Validation resize | Short edge 800 pixels; maximum long edge 1333 |
| Mixed precision | Enabled for training |
| EMA / Weights & Biases | Disabled by default |
The supplied configuration initializes from a detection checkpoint by default. Use the explicit initialization override in the training command below when starting a new training run.
Place the trained checkpoint at:
checkpoints/r50_200ep_32bs_300_bins/model_final.pth
The pretrained DDM-Det checkpoint (ResNet-50, COCO 2017) is available on Hugging Face.
Download the checkpoint:
mkdir -p checkpoints/r50_200ep_32bs_300_bins
hf download NeereshPerla/ddm-det model_final.pth \
--local-dir checkpoints/r50_200ep_32bs_300_binsThe checkpoint is excluded from Git and must be downloaded separately.
Evaluate on COCO val2017 with one GPU:
python train_net.py \
--config-file configs/config_r50_200ep_32bs.py \
--num-gpus 1 \
--eval-only \
train.init_checkpoint=checkpoints/r50_200ep_32bs_300_bins/model_final.pthFor two-GPU evaluation, use --num-gpus 2, or run the included helper:
bash run_eval.sh
COCO bounding-box metrics are printed to the terminal. Predictions and evaluation artifacts are written under outputs/r50_200ep_32bs_300_bins/, including coco_instances_results.json and instances_predictions.pth.
Initialize the backbone from ImageNet-pretrained ResNet-50 weights and use a new output directory:
python train_net.py \
--config-file configs/config_r50_200ep_32bs.py \
--num-gpus 2 \
train.init_checkpoint=detectron2://ImageNetPretrained/torchvision/R-50.pkl \
train.output_dir=./outputs/r50_200ep_32bs_trainThe pretrained backbone weights are downloaded on first use. Newly introduced parameters, including deformable-convolution offsets and the detection transformer, are initialized by the model.
dataloader.train.total_batch_size=32 is the global batch size across all GPUs. Changing --num-gpus does not automatically change this value. Choose a GPU count and batch size that fit your available memory.
If you change the global batch size, update train.max_iter, the scheduler in configs/common/coco_schedule.py, and the evaluation/checkpoint intervals to preserve the intended epoch schedule. The iteration budget is not automatically rescaled.
Use the same output directory as the interrupted run:
python train_net.py \
--config-file configs/config_r50_200ep_32bs.py \
--num-gpus 2 \
--resume \
train.output_dir=./outputs/r50_200ep_32bs_trainWhen a saved checkpoint exists in that directory, --resume restores the training state. Without one, the trainer falls back to train.init_checkpoint.
This runs 20 training iterations, with evaluation at iterations 10 and 20. It still uses the configured validation dataset.
python train_net.py \
--config-file configs/config_r50_200ep_32bs.py \
--num-gpus 1 \
train.fast_dev_run.enabled=True \
dataloader.train.total_batch_size=2 \
train.init_checkpoint=detectron2://ImageNetPretrained/torchvision/R-50.pkl \
train.output_dir=./outputs/debugTraining writes console logs, metrics.json, TensorBoard events, and periodic checkpoints to train.output_dir.
tensorboard --logdir ./outputs
Weights & Biases logging is optional. After authenticating with wandb login, add train.wandb.enabled=True to the training command. Configure its project and run name through train.wandb.params.
The model accepts Detectron2-style input dictionaries and returns Instances containing pred_boxes, scores, and pred_classes. The example below uses the same RGB loading and resizing convention as validation.
Run this Python code from the repository root after installing dependencies and obtaining a checkpoint:
import numpy as np import torch from PIL import Image from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import LazyConfig, instantiate from detectron2.data import transforms as T cfg = LazyConfig.load("configs/config_r50_200ep_32bs.py") model = instantiate(cfg.model).to(cfg.train.device) DetectionCheckpointer(model).load( "checkpoints/r50_200ep_32bs_300_bins/model_final.pth" ) model.eval() image = np.array(Image.open("path/to/image.jpg").convert("RGB")) height, width = image.shape[:2] resize = T.ResizeShortestEdge([800, 800], 1333) image = resize.get_transform(image).apply_image(image) image = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1))) with torch.inference_mode(): instances = model([{ "image": image, "height": height, "width": width, }])[0]["instances"].to("cpu") instances = instances[instances.scores >= 0.5] print("Boxes (original-image XYXY):", instances.pred_boxes.tensor) print("Scores:", instances.scores) print("Classes (contiguous COCO IDs, 0–79):", instances.pred_classes)
The model handles pixel normalization internally. The score threshold above is an application-level choice; COCO evaluation uses the evaluation pipeline without this extra filtering. The supplied sampler is stochastic, so set random seeds when comparing individual predictions.
.
├── configs/
│ ├── config_r50_200ep_32bs.py # Model, vocabulary, and run settings
│ ├── r50_200ep_32bs.py # Optimization and training schedule
│ └── common/ # Data loading, optimizer, and shared settings
├── d2u/
│ ├── ddmdet.py # Detector, diffusion loss, and one-step sampler
│ ├── resnet.py # Backbone and deformable convolutions
│ ├── transformer.py # Encoder–decoder interface
│ ├── encoder.py # Image feature encoder
│ ├── decoder.py # Noise-conditioned token decoder
│ └── tasks/
│ ├── object_detection.py # Tokenization, matching, and box decoding
│ └── raw_task.py # Shared sequence-processing utilities
├── noise_scheduler.py # Diffusion noise schedules
├── train_net.py # Training and COCO evaluation entry point
├── ema.py # Optional exponential moving average
├── wandb_helper.py # Optional experiment logging
├── run_eval.sh
├── requirements.txt
├── README.md
└── LICENSE
| Issue | Action |
|---|---|
ModuleNotFoundError: detectron2 |
Install Detectron2 separately in the active Python environment. |
| Missing CUDA operators or undefined symbols | Check PyTorch/CUDA/compiler compatibility and rebuild Detectron2 against the installed PyTorch. |
| COCO images or annotations not found | Check the dataset layout and set DETECTRON2_DATASETS before starting Python. |
| Evaluation checkpoint not found | Supply a trained checkpoint using train.init_checkpoint=/absolute/path/to/model.pth. |
| CUDA out of memory during training | Reduce the global batch size or use more GPUs; adjust the iteration schedule if the global batch size changes. |
Custom datasets: register the dataset with Detectron2, update the dataset names and evaluator, and adapt the class vocabulary. The current output decoder also contains a hard-coded 80-class validity check in d2u/tasks/object_detection.py; changing num_classes alone is insufficient. Changing the query count requires a corresponding update to seq_pos_length (six prompt tokens plus five tokens per query). Vocabulary or architecture changes may make existing detection checkpoints incompatible.
This implementation uses PyTorch and Detectron2. Several components retain source attributions to detrex and DETR; see the individual source-file headers.
If you find DDM-Det useful in your research, please cite our paper:
Fast Object Detection via One-Step Discrete Diffusion
Accepted at the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV), 2027.
The official publication link and BibTeX citation will be added when available.
This project is licensed under the Apache License 2.0. See the LICENSE file for details.
This repository includes components adapted from third-party open-source projects. Original copyright and license notices are retained in the respective source files.