RelateAnything README

The project's README from github.com/Maelic/RelateAnything. As one markdown file: README.md.

RelateAnything

Real-time open-vocabulary relation prediction from any inputs.

arXiv models demo ci license

Paper · Project page · Models · Training data · Documentation

Give RelateAnything an image, object regions, and the relations you want to look for. It returns scored (subject, relation, object) triplets, such as person → riding → horse.

https://github.com/user-attachments/assets/76544f31-53ac-407b-9445-157e83946938

The same relation model across five scenes, with tracked regions and relations. Clip credits · Reproduce the video

Try the browser demo — no installation; inference runs on your device using WebGPU or WASM.

Quickstart · Models · Deployment · Performance · Results · How it works

Quickstart

Use Python 3.12+. Install a CUDA-enabled PyTorch build for NVIDIA GPU inference, or use device="cpu" in the example below.

git clone https://github.com/Maelic/RelateAnything.git
cd RelateAnything
pip install -e ".[hub]"

Run this from the repository root. The sample photo is included; the two example boxes identify the person and the horse.

import numpy as np
from PIL import Image
from relsgg import RelateAnything

model = RelateAnything.from_pretrained("maelic/relsgg-vits16plus", device="cuda")
image = Image.open("assets/reel/images/horse.jpg").convert("RGB")
boxes = np.array([[470, 130, 650, 630], [90, 310, 1010, 875]], dtype=np.float32)

# Boxes are [x1, y1, x2, y2] in original-image pixels.
# Labels are optional and only make the printed triplets easier to read.
for triplet in model.predict(image, boxes, box_labels=["person", "horse"], topk=5):
    print(triplet)

# Change what relations to look for, without retraining.
model.set_vocabulary(["riding", "carrying a rider", "beside", "in front of"])
graphs = model.predict(image, boxes, box_labels=["person", "horse"], decompose=True)
print(graphs["spatial"])
print(graphs["semantic"])

Released checkpoints include the backbone configuration and text encoder; no gated DINOv3 login is needed for inference. Replace the sample image and boxes with your own inputs; the API also supports masks and a larger built-in relation vocabulary.

API guide: inputs, vocabularies, masks, and scores · Installation and offline use

Models

Start with relsgg-vits16plus, the recommended balance of quality and speed. All three checkpoints use the same training recipe; their vision backbones differ.

Checkpoint Backbone Parameters
relsgg-vits16 DINOv3 ViT-S/16 46.1 M
relsgg-vits16plus DINOv3 ViT-S/16+ 53.2 M
relsgg-vitb16 DINOv3 ViT-B/16 113.8 M

Compare model quality and speed. Each model card includes evaluation results and calibration details.

Deployment

After downloading the relation graph and building the local detector as explained in the deployment guide:

# CPU image demo; omit --image to use a webcam.
python deploy/demo_webcam.py --dist deploy/dist/relsgg-vits16plus --image photo.jpg

# NVIDIA GPU, after building both TensorRT engines.
python deploy/demo_webcam.py --dist deploy/dist/relsgg-vits16plus \
  --backend tensorrt --device cuda --image photo.jpg --decompose

The relation model consumes regions; it does not detect objects itself. Demo detectors are rebuilt locally and have separate licenses. The exported ONNX/TensorRT graph scores boxes; native mask inputs are supported by the PyTorch API. Deployment contracts and limitations.

Performance

On an RTX 3080 Laptop GPU, the recommended ViT-S+ model takes 17.2 ms per image with TensorRT FP32, including preprocessing, transfers and triplet decoding. Object regions are provided as input.

With YOLO26m detection included, the full pipeline takes 36.5 ms per image. Detection uses PyTorch FP32; ViT-S+ relations use TensorRT FP32.

Warm median latency, batch 1, 35 relation types, 6 sample images; loading and setup excluded.

All models and runtimes · YOLO26, YOLO-World and YOLOE comparison · Paper pipeline benchmarks

Results

The paper evaluates relation prediction across datasets, open vocabularies and spatial reasoning tasks. Selected transfer results for ViT-S+, using ground-truth boxes and one relation per ordered pair:

Test set OvSGTR F1@50 RelateAnything F1@50
VG150 16.5 36.9
PSG 13.5 34.7
IndoorVG 20.2 37.8

Both models use the same evaluator and vocabulary. OvSGTR receives object labels; RelateAnything does not. The full results cover stronger baselines including ROBIN-3B, zero-shot controls and the complete evaluation.

Evaluation protocol · Scoring guide

How it works

Figure 2: RelateAnything's visual path, text embedding bank, predicate-conditioned scoring gate, and training objective

Figure 2 from the paper. Click to enlarge.

A DINOv3 backbone reads the image once. Regions become visual tokens; a pair sampler selects candidate relations; a transformer refines them using the scene. A vocabulary head scores each pair against embeddings of your predicate strings, mixing spatial and semantic features. Swapping that embedding bank changes the vocabulary without retraining the vision model.

Architecture guide

Data and evaluation packs

Reproduce and contribute

The documentation index covers the API, architecture, training, data and deployment. Read evaluation pitfalls before comparing results or changing the scoring path.

License

Full third-party notices and credits

Citation

@article{neau2026relateanything,
  title   = {RelateAnything: Real-Time Open-Vocabulary Relation Prediction From Any Inputs},
  author  = {Neau, Ma\"elic},
  journal = {arXiv preprint arXiv:2609.12552},
  eprint  = {2609.12552},
  archivePrefix = {arXiv},
  primaryClass  = {cs.CV},
  url     = {https://arxiv.org/abs/2609.12552},
  year    = {2026}
}

RelateAnything (Maelic/RelateAnything)

Searching Database…

Что это такое?RelateAnything — модель для предсказания отношений с открытым словарём, работающая в реальном времени: даёте ей изображение, области объектов и отношения, которые нужно найти, а она возвращает оцененные тройки (субъект, отношение, объект) вроде person → riding → horse.
Что я получаю на деле — библиотеку для Python, веб-приложение, сервис?Это код к научной статье: PyTorch API с предобученными чекпоинтами, а также инструменты для обучения и оценки, ONNX-граф для запуска через TensorRT и OpenVINO и демонстрация в браузере, не требующая установки.
Как запустить её на своей фотографии?Запустите quickstart из корня репозитория: туда уже входят пример фото и две рамки (человек и лошадь); подставьте своё изображение и свои рамки. Маски и более крупный встроенный словарь отношений тоже поддерживаются.
Нужно ли что-то особое установить заранее?Python 3.12+ и PyTorch — для инференса на GPU от NVIDIA ставьте сборку с поддержкой CUDA, либо запускайте на CPU с device='cpu'. Выпущенные чекпоинты уже содержат бэкбон и текстовый энкодер, так что вход по логину в DINOv3 для инференса не нужен.
В чём подвох — сможет ли она сама найти объекты на фото?Нет — детекцией объектов она не занимается: области задаёте вы — детектором, сегментатором или вручную, а маски необязательны. Демо-детекторы собираются локально и распространяются под отдельными лицензиями.
Если я попробую демо в браузере, мои изображения уйдут на сервер?Нет — демо выполняет инференс целиком на вашем устройстве через WebGPU или WASM, так что изображения из него никуда не передаются.
Код и модель можно использовать свободно?Использовать можно свободно, но с оговоркой: код под Apache-2.0, однако веса являются производными от Meta DINOv3, аннотации RA-4M распространяются по Gemma Terms of Use, а демо-детекторы под AGPL-3.0 и в выпускаемые артефакты не входят.
Для этого нужна видеокарта NVIDIA?Нет. Инференс на CPU работает сразу из коробки, на ноутбуках локальные демо на ONNX или OpenVINO идут с изображением или веб-камерой, а браузерному демо ничего ставить не нужно — вариант с GPU от NVIDIA и TensorRT просто самый быстрый.
Что значит «открытый словарь» — могу ли я искать свои собственные отношения?Да — фразы-отношения вы задаёте прямо на этапе инференса, без дообучения. Небольшой текстовый энкодер один раз превращает их в эмбеддинги, и никакая языковая модель не запускается на каждый кадр; есть и более крупный встроенный словарь отношений.
Как быстро это реально работает?На RTX 3080 Laptop GPU рекомендуемая модель ViT-S+ обрабатывает изображение за 17.2 мс с TensorRT FP32, включая предобработку; с добавлением детекции YOLO26m весь конвейер занимает 36.5 мс на изображение.
Чекпоинтов три — какой мне выбрать?Начните с relsgg-vits16plus (53.2M параметров) — это рекомендуемый баланс качества и скорости. relsgg-vits16 (46.1M) и relsgg-vitb16 (113.8M) обучены по той же схеме и отличаются только бэкбонами DINOv3 ViT.
А как она сравнивается с предыдущими моделями отношений с открытым словарём?С большим отрывом: F1@50 — 36.9 против 16.5 у OvSGTR на VG150, 34.7 против 13.5 на PSG и 37.8 против 20.2 на IndoorVG, причём оценщик один и тот же; и в отличие от OvSGTR, RelateAnything не получает меток объектов.
Creator
Maelic
Size
27.5 MB
Stars
1.1K
Updated
CommitOct 12
Age
1mo
Commits · 90 Days