> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.ovalbee.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.ovalbee.com/_mcp/server.

# Train Grounding DINO

> Train Grounding DINO object detection model using MMDetection framework.

Runs on: gpu  Dockerfile

> **Note**
>
> First run can take longer while the worker pulls the configured Docker image.

## Overview

Fine-tunes Grounding DINO on an OvalBee dataset. The node exports the datasets to COCO itself, so no conversion step runs in front of it.

Grounding DINO detects objects from text, which means the pretrained model already finds classes it was never trained on. Fine-tuning is what you do when that zero-shot behaviour is close but not accurate enough on your own data.

The badge shows the best mAP at IoU 0.5 reached on the validation split.

```mermaid
flowchart LR
  n1["Train dataset"] --> n3["Train Grounding DINO"] --> n4["Model asset"]
  n2["Validation dataset"] --> n3
```

#### Pretrained Models

* Grounding DINO Swin-T (lighter, \~170M params)
* Grounding DINO Swin-B (\~240M params)
* Grounding DINO Swin-L (best quality, \~340M params)

## Prerequisites

| Requirement              | What you need                                                                                                            |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| **GPU worker**           | A worker with a GPU.                                                                                                     |
| **Train dataset**        | An annotated dataset with the objects to learn.                                                                          |
| **Validation dataset**   | A second annotated dataset. Grounding DINO scores mAP on it every `val_interval` epochs and refuses to train without it. |
| **A model to fine-tune** | A model of this workspace, picked in **Model**. Create one from the picker to copy an architecture in from the zoo.      |

#### What the node writes to disk

```text
📁 dataset_directory/
├── 📄 data.yaml
├── 📁 images/
│   ├── 📁 train/
│   └── 📁 val/
└── 📁 annotations/
    ├── 📄 train.json
    └── 📄 val.json
```

The node builds this tree in the task's own scratch space at the start of every run, and `data.yaml` names the classes it trained on. Nothing here survives the run — the checkpoints leave through the model asset.

## How it works

Exports both datasets to COCO in one pass, so train and val share one class index.

Builds the training config from the selected architecture, the class list, and your overrides.

Fine-tunes Grounding DINO, writing metrics and TensorBoard events beside the dataset, the weights as `config.json` plus `model.safetensors` each time validation mAP improves, and, at the end of the first epoch and then at an epoch's end at most every two minutes, a checkpoint a resumed run continues from.

Uploads those weights and creates the model asset that carries them, along with the architecture, classes, and the metrics of the epoch those weights come from.

## FAQ

#### How does it estimate data usefulness?

The node saves the model's weights near 10%, 25% and 50% of the epoch budget into a scratch directory that is never published, and after training it runs inference over the training split with those snapshots and with the final weights. For every labelled object it records the confidence of the best matching prediction of the right class, or zero when nothing matches, and scores each image by the average of one minus those confidences. An object counts as found once that confidence reaches 0.3, the default confidence threshold of the matching Predict node, and an image counts as learned once at least 80% of its objects are found.

Images learned in the first quarter of the run and never lost again are the ones the model needed least. Confident predictions that match no label are counted separately: they point at missing labels or genuine mistakes, and they do not decide whether an image was learned.

#### How is the Recommended keep set chosen?

Only images solved early and never forgotten can be dropped, easiest first, and every class keeps at least 80% of its instances. When nothing is safely droppable, the output stays empty rather than handing over a dataset the report advises against. To check the estimate, train again on the keep set from the same model this run started from and compare the two runs' evaluation metrics.

#### Do I need a conversion step in front of this node?

No. Connect the datasets directly. The node exports them to COCO itself, in a single pass so the two splits agree on the class order.

#### Where do the trained files end up?

On the model asset, as `config.json` plus `model.safetensors`: a plain safetensors state_dict, text encoder included. The run writes everything else to scratch space that disappears with the container.

#### Is the model asset ready to use after training?

Yes. It carries the checkpoint, so predict and export nodes can take it as-is.

#### What happens if training fails partway through?

The version is created before training starts and receives the best weights so far about every two minutes. At the end of the first epoch, and then at an epoch's end at most every two minutes, the node also saves a checkpoint into the version: the network, the optimizer, the position in the learning-rate schedule and its warmup, the mixed-precision scaler and the best mAP so far, with the best weights and logs as of that epoch. The optimizer's state makes a checkpoint about three times the size of the weights: with Swin-T, 692 MB of weights and 1.4 GB of training state, about 2.1 GB uploaded at every checkpoint while the next epoch trains. Only the latest one is kept. Training never waits for that upload, and no new checkpoint starts while one uploads, so a run that is killed loses the training since its last checkpoint that finished uploading: about one epoch or two minutes, whichever is longer, plus the time a checkpoint takes to upload. A run that stops after its first checkpoint leaves the version **Incomplete**: the model pickers offer it with its best weights so far, marked as not fully trained, and running the node with that version in **Model** (**Latest** picks it while it is the newest) continues the run from its last checkpoint into the same version, with the settings it started with. The continued run does not repeat the first epochs' random draws, and an epoch that does not beat the best mAP reached before the interruption leaves the version's best weights alone. The run's last epoch is not a checkpoint, so a run interrupted after it repeats that epoch. On Kubernetes, a run whose machine was taken away is retried and continues from its last checkpoint by itself. A run that stops before its first checkpoint marks its version failed, and it isn't offered in the model pickers. If uploading fails five times in a row, the node stops training rather than carry on with no way to save the result.

#### Why does a continued run refuse to start?

A run that continues an unfinished version trains with the settings it started with, so the node first compares the run with the checkpoint and refuses, naming each difference, when the hyperparameters (`epochs` included), the classes, the datasets, the architecture or the mmdet version differ. To train longer or with other settings, start from a fully trained version, or save the unfinished one as a new version and train from that.

#### Which hyperparameters, and written how?

Only the keys the default lists: a key outside it is refused by name rather than ignored, so nothing in the YAML can name weights, a file, a URL or code for the run to load.

Each value may be written any way YAML produces the number or the switch it means. `lr: 1e-4` and `lr: 0.0001` are the same learning rate, `epochs: 12`, `epochs: 12.0` and `epochs: 1e1` the same length, and `freeze_backbone: true` and `freeze_backbone: 1` the same switch. The three switches - `amp`, `freeze_backbone`, `freeze_text_encoder` - may be left empty, which is off, and so may the eight optional augmentation settings - `scale_min`, `scale_max`, `brightness_delta`, `contrast_lower`, `contrast_upper`, `saturation_lower`, `saturation_upper`, `hue_delta` - for their default, which is what commenting them out does. `amp_dtype` takes `fp16` or `float16`, `bf16` or `bfloat16`, and `lr_schedule` takes `constant` or `cosine`.

What is refused is a value the run would read as something else: `amp: "no"` is a non-empty word, which reads as *on*, a `lr_schedule` that is neither of the two schedules would silently train at a constant learning rate, and a whole number written as text that no double holds exactly (`imgsz: 1e100`) would arrive as a different number. `seed` takes a whole number from 0 to 2147483647, the range every generator in the run accepts.

#### Can I watch the run while it trains?

Yes. The report is published early and keeps updating, so charts and checkpoints appear as they are produced rather than only at the end.

#### Do I need to train at all?

Often not. The pretrained model detects classes from their names, so try [Predict Grounding DINO](/node-library/nodes/models-grounding-dino-predict-grounding-dino) on your data first and fine-tune only if the zero-shot result falls short.

#### Which backbone should I pick?

Swin-T for speed and the smallest memory footprint, Swin-L when accuracy matters most, Swin-B in between. Larger backbones need a smaller batch size to fit.

#### Why did the run fail right at the start?

Usually the data or the config. Both datasets need annotated objects — a validation split with no boxes is refused rather than trained blind — and **Config** has to be a valid YAML mapping whose keys the trainer accepts, each with a value of its type.

## Inputs

**`Train dataset`** `dataset` — required

Dataset the model is trained on. The node converts it to COCO itself. Key: `TRAIN_DATASET`.

---

**`Validation dataset`** `dataset` — required

Dataset held out for validation. Grounding DINO reports mAP on it, and cannot train without it. Key: `VAL_DATASET`.

---

**`Estimate data usefulness`** `boolean` — required, default: true

After training, score every training image with weight snapshots saved near 10%, 25% and 50% of the run to estimate how much of the data was actually needed, and publish the subset worth keeping. The snapshots are weights only and are not published, scoring adds a few inference passes over the training split after the run. Key: `ESTIMATE_DATA_USEFULNESS`.

---

**`Model`** `model` — required

Model to fine-tune: its weights are where the run starts. A version copied from the zoo downloads the weights its catalog entry names, which are pickled `.pth` files that load only with safe weights off, one from an earlier run continues from its `model.safetensors`. The run is registered as a new version of this model unless Destination Model names another one. When the version picked is not fully trained (Latest picks one when it is the newest), the run continues that training with the settings it started with, not the ones set here. Key: `MODEL`.

---

**`Destination model`** `model`

Where the trained version is registered, when it should not go to the model being trained. Leave empty to add the version to the Model above. Key: `DESTINATION_MODEL`.

---

**`Hyperparameters`** `yaml` — required

Training hyperparameters in YAML - how long the run trains, at what resolution, and how much the images are augmented. Comments in the default explain the less obvious ones, and a commented-out line stays off until you uncomment it. Key: `CONFIG`.

---

## Outputs

**`Report Asset`** `report`

ID of the asset containing the live Grounding DINO training report. Shown as an artifact. Key: `REPORT_ID`.

---

**`Model`** `model`

Reference to the registry version this run produced, as `&lt;model id&gt;@&lt;version id&gt;`. It wires into the Model input of a predict or evaluate node and pins it to exactly these weights. Empty when the run could not be registered. Shown as an artifact. Key: `MODEL`.

---

**`Best mAP50`** `string`

Best mAP50 achieved during training (shown as a badge). Shown on the node as a badge. Key: `BEST_MAP50`.

---

**`Recommended keep set`** `dataset`

The training images this run's usefulness estimate says are worth keeping. To check the estimate, wire it into the Train dataset of another Train Grounding DINO node that starts from the same model this run started from, and compare the two runs' evaluation metrics. Short-lived, so copy it if you want to keep it. Empty when the estimate found nothing safe to drop. Shown as an artifact. Key: `KEEP_DATASET`.

---

**`Keep share`** `string`

Share of the training images the keep set retains. Shown on the node as a badge. Selecting the badge opens `KEEP_DATASET`. Key: `KEEP_SHARE`.

---

## Models and configuration

**Model** is both what training starts from and where its result is filed: the run adds a version to that model. Its weights are downloaded and checked before anything loads them. A version copied from the zoo downloads the MM Grounding DINO checkpoint its catalog entry names from OpenMMLab: a pickled `.pth`, which loads only while the instance's safe-weights setting is off. One produced by an earlier run continues from its `model.safetensors`, and the new version records it as its parent.

Set **Destination Model** to file the result elsewhere — the trained version is created there instead, and **Model** is then only the starting weights.

The Swin-T backbone is the fastest, Swin-L the most accurate, and Swin-B the middle ground.

**Config** holds the training settings as YAML. Dataset paths and the class count are injected by the node, and a key the node does not know, or a value of the wrong type (`amp: "no"`, an `lr_schedule` other than `constant` or `cosine`), is refused: the config tunes the run, never names weights or files to load.

Set `seed: 0` (or another integer from 0 to 2147483647) to choose the run's seed. When omitted, a fresh run chooses one at random. The effective config and training checkpoint record the chosen seed, and a continued run keeps that original seed: the order the images are shown in each epoch and the seeds of the data-loading workers stay the ones the seed gives, as in a run never interrupted, while the training process's own random draws start afresh from a seed derived from it at every continuation.

## Report

The report appears near the start of the run and updates as training produces results. It opens in the preview widget on the node.

#### Report sections

| Section                          | What it shows                                                                        |
| -------------------------------- | ------------------------------------------------------------------------------------ |
| **Overview**                     | The architecture, task, configured epochs, elapsed time, dataset sizes, and classes. |
| **Predictions**                  | The best checkpoint applied to a fixed sample of validation images, once one exists. |
| **Evaluation Metrics**           | Detection metrics from the best validation epoch.                                    |
| **Training Plots**               | Every loss, metric, and learning-rate series recorded during the run.                |
| **TensorBoard**                  | The raw TensorBoard event stream.                                                    |
| **Artifacts**                    | The checkpoints written so far, and the model asset panel once the run finishes.     |
| **Classes**                      | The class names the run trained on.                                                  |
| **Hyperparameters**              | The config the run actually used.                                                    |
| **How to Use the Trained Model** | A short local example that loads the checkpoint and predicts an image.               |

## Runtime

The node runs in its own GPU container. Memory use follows the architecture, the input size, and the batch size, so a model that will not fit is the first thing to check when a run dies early.

The first run takes longer while the worker pulls the image and downloads pretrained weights. Every run downloads its datasets again — the container keeps nothing between runs.

## JSON config

Machine-readable node interface for automation and advanced usage.

#### Show JSON

```json
{
  "name": "Train Grounding DINO",
  "description": "Train Grounding DINO object detection model using MMDetection framework.",
  "category": "Train",
  "namespace": "ovalbee",
  "templateKey": "models/grounding_dino/train_grounding_dino",
  "version": "v1",
  "inputs": [
    {
      "key": "TRAIN_DATASET",
      "label": "Train dataset",
      "type": "dataset",
      "description": "Dataset the model is trained on. The node converts it to COCO itself.",
      "required": true,
      "default": null,
      "visibleWhen": null,
      "options": {
        "creatable": false
      }
    },
    {
      "key": "VAL_DATASET",
      "label": "Validation dataset",
      "type": "dataset",
      "description": "Dataset held out for validation. Grounding DINO reports mAP on it, and cannot train without it.",
      "required": true,
      "default": null,
      "visibleWhen": null,
      "options": {
        "creatable": false
      }
    },
    {
      "key": "ESTIMATE_DATA_USEFULNESS",
      "label": "Estimate data usefulness",
      "type": "boolean",
      "description": "After training, score every training image with weight snapshots saved near 10%, 25% and 50% of the run to estimate how much of the data was actually needed, and publish the subset worth keeping. The snapshots are weights only and are not published; scoring adds a few inference passes over the training split after the run.\n",
      "required": true,
      "default": true,
      "visibleWhen": null
    },
    {
      "key": "MODEL",
      "label": "Model",
      "type": "model",
      "description": "Model to fine-tune: its weights are where the run starts. A version copied from the zoo downloads the weights its catalog entry names, which are pickled `.pth` files that load only with safe weights off; one from an earlier run continues from its `model.safetensors`. The run is registered as a new version of this model unless Destination Model names another one. When the version picked is not fully trained (Latest picks one when it is the newest), the run continues that training with the settings it started with, not the ones set here.\n",
      "required": true,
      "default": null,
      "visibleWhen": null,
      "options": {
        "scope": "my",
        "framework": "grounding_dino",
        "task_type": "object_detection",
        "include_incomplete_versions": true
      }
    },
    {
      "key": "DESTINATION_MODEL",
      "label": "Destination model",
      "type": "model",
      "description": "Where the trained version is registered, when it should not go to the model being trained. Leave empty to add the version to the Model above.\n",
      "required": false,
      "default": null,
      "visibleWhen": null,
      "options": {
        "scope": "my",
        "framework": "grounding_dino",
        "task_type": "object_detection"
      }
    },
    {
      "key": "CONFIG",
      "label": "Hyperparameters",
      "type": "yaml",
      "description": "Training hyperparameters in YAML - how long the run trains, at what resolution, and how much the images are augmented. Comments in the default explain the less obvious ones, and a commented-out line stays off until you uncomment it.\n",
      "required": true,
      "default": "# --- Schedule ---\nepochs: 12\nbatch_size: 2\nlr: 5.0e-5\nweight_decay: 0.0001\nwarmup_iters: 200\nval_interval: 1\nworkers: 4\n# --- Input ---\nimgsz: 800          # input resolution: scales whole multi-scale envelope by imgsz/800 (aspect kept). short edge up to imgsz, long-edge cap ~imgsz*1.667. For 16:9 the long cap binds, so e.g. native 1920x1080 ~ imgsz 1150.\n# --- Augmentation ---\nrandom_flip: 0.5    # horizontal flip probability (0.0 to disable)\n# random_flip_vertical: 0.0    # vertical flip probability (0.0 to disable)\n# scale_min: 0.5               # min random resize scale factor relative to imgsz\n# scale_max: 2.0               # max random resize scale factor relative to imgsz\n# brightness_delta: 32         # max pixel brightness shift (0-255, 0 to disable)\n# contrast_lower: 0.5          # contrast multiplier lower bound\n# contrast_upper: 1.5          # contrast multiplier upper bound\n# saturation_lower: 0.5        # saturation multiplier lower bound\n# saturation_upper: 1.5        # saturation multiplier upper bound\n# hue_delta: 18                # max hue shift in degrees (0 to disable)\n# --- Model ---\nfreeze_backbone: false   # freeze image backbone weights\nfreeze_text_encoder: false  # freeze BERT text encoder; set true only to save VRAM (reduces quality for overlapping class names)\n# --- LR Schedule ---\n# lr_schedule: cosine  # \"constant\" (default) or \"cosine\" - cosine decay from lr to lr*lr_min_ratio\n# lr_min_ratio: 0.01   # final LR as a fraction of lr (only used with lr_schedule: cosine)\n# --- Optimizer ---\ngrad_clip: 0.1      # gradient clip max norm (0 to disable)\n# --- Performance ---\namp: false          # mixed precision (AmpOptimWrapper): ~half activation memory + faster on tensor-core GPUs, fits a larger batch. Set true to enable.\n# amp_dtype: fp16   # \"fp16\" (default, required: mmcv deformable-attn has no bf16 CUDA kernel) or \"bf16\" (only if a future mmcv build adds the bf16 MSDA kernel)\n",
      "visibleWhen": null
    }
  ],
  "outputs": [
    {
      "key": "REPORT_ID",
      "label": "Report Asset",
      "type": "report",
      "description": "ID of the asset containing the live Grounding DINO training report.",
      "artifact": true,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "MODEL",
      "label": "Model",
      "type": "model",
      "description": "Reference to the registry version this run produced, as `<model id>@<version id>`. It wires into the Model input of a predict or evaluate node and pins it to exactly these weights. Empty when the run could not be registered.\n",
      "artifact": true,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "BEST_MAP50",
      "label": "Best mAP50",
      "type": "string",
      "description": "Best mAP50 achieved during training (shown as a badge).",
      "artifact": false,
      "badge": true,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "KEEP_DATASET",
      "label": "Recommended keep set",
      "type": "dataset",
      "description": "The training images this run's usefulness estimate says are worth keeping. To check the estimate, wire it into the Train dataset of another Train Grounding DINO node that starts from the same model this run started from, and compare the two runs' evaluation metrics. Short-lived, so copy it if you want to keep it. Empty when the estimate found nothing safe to drop.\n",
      "artifact": true,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "KEEP_SHARE",
      "label": "Keep share",
      "type": "string",
      "description": "Share of the training images the keep set retains.",
      "artifact": false,
      "badge": true,
      "badgeOpens": "KEEP_DATASET",
      "hidden": false
    }
  ],
  "runtime": {
    "type": "docker",
    "devices": [
      "gpu"
    ],
    "dockerImage": "ovalbee/node-grounding_dino:0.0.47"
  },
  "widgets": {
    "widget": {
      "id": "report-preview",
      "settings": {
        "reportAsset": {
          "type": "variable",
          "value": "self.outputs.REPORT_ID"
        },
        "name": {
          "type": "input",
          "value": "Open training report"
        }
      }
    }
  }
}
```

## References

#### Sources and related pages

* [Predict Grounding DINO](/node-library/nodes/models-grounding-dino-predict-grounding-dino) runs the model asset this node produces.
* [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) is the upstream implementation.