TinyFormer
TinyFormer is a trainable transformer detector with a DINOv3 backbone.
- Задачи
- detection
- Установка
pip install libreyolo- Уровень поддержки
- Основной, начиная с v1.6.0. Основные обучаемые детекторы: функции появляются вслед за флагманами в той же волне релиза.
- Исходный проект
- TinyFormer от TinyFormer authors, Apache-2.0; DINOv3 terms. Статья, исходный код
- Лицензии
- Код: MIT, веса: Apache-2.0; DINOv3 terms. Коммерческое использование
Install
pip install "libreyolo"Predict
from libreyolo import LibreYOLO, SAMPLE_IMAGE model = LibreYOLO("LibreTinyFormers.pt", device="cpu")result = model(SAMPLE_IMAGE)print(result)Choose a published checkpoint below. The naming distinguishes the VisDrone variants and Objects365-to-COCO variants. Prediction requires a square imgsz; rectangular inputs raise an error.
Train
Training accepts a detection dataset YAML. Omitted epochs, batch, imgsz, lr0 and amp use the family recipe.
Dataset setup describes the required training data.
from libreyolo import LibreYOLO model = LibreYOLO("LibreTinyFormers.pt", device="cpu")# coco8.yaml is a built-in 8-image detection dataset that downloads on first use.# Replace it with the path to your own detection dataset YAML.model.train(data="coco8.yaml", epochs=1, device="cpu", workers=0)Validate
from libreyolo import LibreYOLO model = LibreYOLO("LibreTinyFormers.pt", device="cpu")# coco8.yaml downloads on first use; pass your own detection dataset YAML instead.metrics = model.val(data="coco8.yaml", workers=0)print(metrics)Use the dataset format for this task. Validation explains the dataset requirements and returned metrics.
Export
| Задача | ONNX | TorchScript | ExecuTorch | TensorRT | OpenVINO | Paddle | MNN | RKNN | ncnn | TFLite | CoreML | Core AI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Detection | Detection to ONNX: поддерживается | Detection to TorchScript: поддерживается | Detection to ExecuTorch: поддерживается | Detection to TensorRT: поддерживается | Detection to OpenVINO: поддерживается | Detection to Paddle: не поддерживается | Detection to MNN: не поддерживается | Detection to RKNN: не поддерживается | Detection to ncnn: не поддерживается | Detection to TFLite: не поддерживается | Detection to CoreML: не поддерживается | Detection to Core AI: не поддерживается |
from libreyolo import LibreYOLO, SAMPLE_IMAGE model = LibreYOLO("LibreTinyFormers.pt", device="cpu")model.export(format="onnx")Export setup lists format dependencies and loading exported artifacts.
ONNX inputs and outputs
| Тензор | images float32 [batch, 3, height, width] |
|---|---|
| Цвет | RGB |
| Масштабирование | пиксель / 255 |
| Нормализация | среднее [0.485,0.456,0.406], стандартное отклонение [0.229,0.224,0.225] |
| Изменение размера | растянуть до ширины x высоты (без заполнения, соотношение сторон не сохраняется), Pillow bilinear |
Как воспроизвести билинейное изменение размера Pillow
LibreYOLO меняет размер фильтром BILINEAR из Pillow (Image.resize). Это не OpenCV INTER_LINEAR и не INTER_AREA: при уменьшении Pillow расширяет фильтр на коэффициент уменьшения, а изменение размера в OpenCV меняет детекции и сдвигает рамки на несколько пикселей. Чтобы воспроизвести его без Pillow, измените размер по одной оси, округлите до 8 бит, затем измените размер по другой оси и округлите снова. Для каждой оси пусть s = in_size / out_size и f = max(s, 1). Выходной пиксель i имеет центр c = (i + 0.5) * s и читает исходные пиксели j от int(c - f + 0.5) до int(c + f + 0.5) - 1, ограниченные изображением, каждый с весом max(0, 1 - |j + 0.5 - c| / f), деленным на сумму весов. Pillow считает в фиксированной точке и выбирает порядок осей по форме изображения, поэтому веса с плавающей точкой могут отличаться от него на один уровень на нескольких пикселях. Это не меняет результаты в наших проверках.
Square input only. Export rejects a non-square imgsz, and height and width are 640 by default for every size. Another square imgsz must be a multiple of 32.
Batch size 1 only. The graph declares a dynamic batch axis, but batches of 2 or more fail in 1.7.0.
After the resize, divide by 255, then subtract the ImageNet mean and divide by the ImageNet std, per channel in RGB order.
Detection, экспорт по умолчанию
| Выход | Форма | Смысл |
|---|---|---|
pred_logits | [batch, queries, nc] | One logit per query and class. Sigmoid is not applied. queries is 300 for every size. |
pred_boxes | [batch, queries, 4] | cx, cy, w, h of each query, normalized 0 to 1 of the input. The input is the whole image stretched, so these are also fractions of the original image. |
Постобработка
- Apply sigmoid to pred_logits.
- Flatten the [queries, nc] scores and take the top 300 (max_det, 300 by default). For flat index k, the query is k // nc and the class is k % nc. One query can yield several classes.
- Keep the pairs whose score is above the confidence threshold (0.25 by default).
- Convert the query's box to x1 = cx - w / 2, y1 = cy - h / 2, x2 = cx + w / 2, y2 = cy + h / 2. Multiply x by the original image width and y by the original image height.
- There is no NMS and the iou threshold is not used. TinyFormer predicts a set of boxes, and export with nms=True raises NotImplementedError.
- LibreYOLO does not clip these boxes, so an edge can sit slightly outside the image.
Чтобы проверить собственную реализацию, пропустите тот же файл через LibreYOLO: LibreYOLO("model.onnx").predict("image.jpg") возвращает эталонные результаты. Проверено на LibreYOLO 1.7.0.
Checkpoints
| Файл | Лицензия весов |
|---|---|
| Detection | |
| LibreTinyFormers.pt | other |
| LibreTinyFormerm.pt | other |
| LibreTinyFormerl.pt | other |
| LibreTinyFormerx.pt | other |
| LibreTinyFormerxl.pt | other |
| LibreTinyFormers-visdrone.pt | other |
| LibreTinyFormerm-visdrone.pt | other |
| LibreTinyFormerl-visdrone.pt | other |
| LibreTinyFormerx-visdrone.pt | other |
| LibreTinyFormerx-obj2coco.pt | other |
| LibreTinyFormerxl-obj2coco.pt | other |
Все перечисленные выше файлы уже доступны в организации LibreYOLO и скачиваются при первом использовании.
Licensing
Проверяйте лицензию в репозитории конкретных весов на Hugging Face. Она указана для каждого чекпойнта в организации LibreYOLO и может различаться даже внутри одного семейства. Этот репозиторий считается авторитетным источником, а сводка ниже описывает условия на момент последней проверки страницы.
Это описание соответствующих лицензий, а не юридическая консультация. Если ответ важен для коммерческого использования, прочитайте лицензии самостоятельно и проконсультируйтесь с юристом.
- Оригинальная работа
- TinyFormer, TinyFormer authors
- Лицензия исходного проекта
- Apache-2.0; DINOv3 terms
- Исходный код проекта
- github.com/mmpmmpmmpjosh/TinyFormer
- Код LibreYOLO
- MIT
- Веса
- Apache-2.0; DINOv3 terms, повторно опубликованы на huggingface.co/LibreYOLO
- Толкование
- The detector uses Apache-2.0 source and a DINOv3 backbone with its own terms. Check the publisher declarations for the chosen checkpoint.
Citation
@article{hsieh2026tinyformer,
title={TinyFormer: Preserving Tiny Objects in YOLO-DETR Hybrid Real-time Detectors},
author={Hsieh, Jun-Wei and Kao, Meng-Yu and Kurniawan, Ghufron Wahyu and Peng, Kuan-Chuan},
journal={arXiv preprint arXiv:2605.25046},
year={2026}
}Скопировано из блока цитирования авторов на странице raw.githubusercontent.com/mmpmmpmmpjosh/TinyFormer/main/README.md.