Embeddings API¶
YoloNASEmbedder turns images — or boxes within them — into fixed-length vectors from
the backbone and neck, without ever running the detection head. For boxes and
embeddings from a single forward pass, use
YoloNASDetector.predict with Task flags instead.
See the embeddings guide for layer choice, the single-pass API and why letterbox padding is excluded from pooling.
Task flags¶
modern_yolonas.inference.embed.Task
¶
Bases: Flag
What a :meth:YoloNASDetector.predict call should produce.
Combine with |. The backbone and neck run exactly once no matter how many
are asked for, which is the point — detection and embedding share everything
up to the head, so getting both costs one pass rather than two::
from modern_yolonas import Task, YoloNASDetector
detector = YoloNASDetector("yolo_nas_s")
result = detector.predict(image, Task.DETECT | Task.EMBED_OBJECTS)
result.detections # sv.Detections
result.detections.data["embedding"] # (N, 768), one row per detection
Members
DETECT: Boxes, scores and class ids, as result.detections.
EMBED: One vector for the whole image, as result.embedding.
EMBED_OBJECTS: One vector per detection, in
result.detections.data["embedding"]. Implies DETECT, since
the boxes are what gets embedded.
Source code in src/modern_yolonas/inference/embed.py
modern_yolonas.inference.embed.Prediction
dataclass
¶
What :meth:YoloNASDetector.predict returns.
Fields not asked for are None, so a Task.EMBED-only call does not have
to invent an empty Detections to carry the vector.
Attributes:
| Name | Type | Description |
|---|---|---|
detections |
Detections | None
|
Present for :attr: |
embedding |
ndarray | None
|
Present for :attr: |
Source code in src/modern_yolonas/inference/embed.py
YoloNASEmbedder¶
modern_yolonas.inference.embed.YoloNASEmbedder
¶
Turn images (or boxes within them) into fixed-length feature vectors.
The detection head never runs, so this is the cheapest path when embeddings
are all you want. If you need boxes and embeddings, use
:meth:~modern_yolonas.inference.detect.YoloNASDetector.predict with
:class:Task flags instead — it gets both from one forward pass.
Usage::
from modern_yolonas import YoloNASEmbedder
embedder = YoloNASEmbedder("yolo_nas_s", device="cuda")
vec = embedder("image.jpg") # (768,) L2-normalized
bank = embedder.embed_batch(paths) # (N, 768)
similarity = bank @ vec # cosine, because both are normalized
# Per-object vectors, straight from a detection result
detections = YoloNASDetector("yolo_nas_s")(image)
crops = embedder.embed_boxes(image, detections.xyxy) # (len(detections), 768)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Variant name — |
'yolo_nas_s'
|
device
|
str | device
|
Torch device. |
'cuda' if is_available() else 'cpu'
|
input_size
|
int
|
Square letterbox size the image is resized into. |
640
|
layers
|
tuple[str, ...] | list[str]
|
See :class: |
('c5',)
|
pooling
|
str
|
See :class: |
'avg'
|
normalize
|
bool
|
See :class: |
True
|
pretrained
|
bool
|
Load the COCO checkpoint. |
True
|
precision
|
str
|
|
'fp32'
|
weights
|
str | Path | None
|
Optional checkpoint path, as in
:class: |
None
|
num_classes
|
int
|
Head width of that checkpoint. It does not affect the embedding — the head is never run — but the architecture has to be built to match before the weights will load. |
80
|
Source code in src/modern_yolonas/inference/embed.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
layers
property
¶
Feature maps being pooled.
embedding_dim
property
¶
Width of the vectors this embedder produces.
Measured by a single forward pass on a blank image the first time it is asked, then cached — the channel counts are config-derived and there is no cheaper way to get them that cannot drift from what the model actually does.
__call__(source)
¶
Embed a single image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | ndarray
|
File path or BGR numpy array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in src/modern_yolonas/inference/embed.py
embed_batch(sources)
¶
Embed several images in one forward pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
list[str | Path | ndarray]
|
File paths or BGR numpy arrays. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in src/modern_yolonas/inference/embed.py
embed_boxes(source, xyxy)
¶
Embed regions of one image — one vector per box.
This is the per-object counterpart of :meth:__call__, for recognition,
re-identification and "find me more of this thing" search. The boxes are
cropped out of the feature maps with roi_align rather than out of the
image, so a whole frame's worth of objects costs a single forward pass.
When the boxes come from this project's own detector, prefer
:meth:YoloNASDetector.predict with :attr:Task.EMBED_OBJECTS — it
reuses the detection pass instead of running a second one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | ndarray
|
File path or BGR numpy array. |
required |
xyxy
|
ndarray
|
|
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
image first; one that clips to zero area samples nothing and comes back |
ndarray
|
as a zero vector rather than a NaN. |
Source code in src/modern_yolonas/inference/embed.py
Pooling¶
modern_yolonas.inference.embed.FeaturePooler
¶
Turns feature maps into fixed-length vectors.
Split out from :class:YoloNASEmbedder so the detector can reuse the exact
same pooling on the features it already computed, rather than growing a second
copy of it that could drift.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layers
|
tuple[str, ...] | list[str]
|
Which feature maps to pool and concatenate, from
:data: |
('c5',)
|
pooling
|
str
|
|
'avg'
|
normalize
|
bool
|
L2-normalize the result, which makes a dot product a cosine similarity. Leave it on unless you need raw activation magnitude. |
True
|
Source code in src/modern_yolonas/inference/embed.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
dim(features)
¶
pool_images(features, regions, canvas)
¶
One vector per sample in the batch, padding excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
dict[str, Tensor]
|
Output of :meth: |
required |
regions
|
list[tuple[int, int, int, int]]
|
Per sample |
required |
canvas
|
int
|
Side length of the letterboxed input. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in src/modern_yolonas/inference/embed.py
pool_images_masked(features, regions, canvas)
¶
:meth:pool_images, written so it can be traced and exported.
Same result, different mechanics. :meth:pool_images slices each sample's
map with Python int bounds, which is data-dependent control flow that
torch.export cannot see through. This builds a boolean mask from the
region tensor and reduces over it instead, so every step is an op on
tensors and the whole thing survives ONNX export.
The bounds use integer arithmetic — (left * width) // canvas rather
than floor(left / stride) — because float division at exact multiples
is where the two implementations would drift apart. test_embed.py pins
them to each other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
dict[str, Tensor]
|
Output of :meth: |
required |
regions
|
Tensor
|
|
required |
canvas
|
int
|
Side length of the letterboxed input. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in src/modern_yolonas/inference/embed.py
pool_rois(features, rois, canvas)
¶
One vector per box, cropped out of the feature maps with roi_align.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
dict[str, Tensor]
|
Output of :meth: |
required |
rois
|
Tensor
|
|
required |
canvas
|
int
|
Side length of the letterboxed input. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in src/modern_yolonas/inference/embed.py
finalize(vectors)
¶
L2-normalize if configured to, and hand back float32 numpy.
Source code in src/modern_yolonas/inference/embed.py
Raw feature maps¶
If you would rather pool the feature maps yourself, the model exposes them directly.
modern_yolonas.model.YoloNAS.forward_features(x)
¶
Run backbone and neck and return every intermediate feature map.
The detection head is skipped entirely — this is the representation the
model builds before it commits to boxes and classes, which is what an
image-retrieval or re-identification pipeline wants. See
:class:~modern_yolonas.inference.embed.YoloNASEmbedder for the
image-in, vector-out wrapper around it.
Deliberately a separate method rather than a flag on forward: the
signature of forward is what ONNX export, the Frigate graph, the
parity tests and the FX-traced quantization path all depend on.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Normalized input batch, |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
dict[str, Tensor]
|
are the backbone outputs ( |
dict[str, Tensor]
|
neck's fused pyramid levels. At 640x640 the strides are 4, 8, 16, 32 |
dict[str, Tensor]
|
for |