altametris.sara.yolo¶
YOLO - Object Detection and Instance Segmentation.
Wrapper autour de Ultralytics YOLO (v8, v11).
Submodules¶
Classes¶
YOLO detector implementing BaseDetector interface. |
|
YOLO exporter implementing BaseExporter interface. |
|
YOLO model wrapper implementing BaseModel interface. |
|
YOLO trainer implementing BaseTrainer interface. |
Package Contents¶
- class altametris.sara.yolo.YoloDetector(model_path: str | pathlib.Path, task: str = 'detect', device: str = 'auto', warmup: bool = True, **kwargs: Any)¶
Bases:
altametris.sara.core.base_detector.BaseDetectorYOLO detector implementing BaseDetector interface.
Provides inference capabilities with support for images, videos, and batch processing.
- Parameters:
model_path – Path to YOLO model weights
task – YOLO task (“detect”, “segment”, “obb”, “pose”)
device – Inference device
warmup – Run warmup on initialization
Example
>>> detector = YoloDetector(model_path="yolo11x.pt", device="cuda") >>> results = detector.predict("image.jpg", conf=0.5, imgsz=640)
- SUPPORTED_TASKS = ['detect', 'segment', 'obb', 'pose', 'classify']¶
- task = 'detect'¶
- model: ultralytics.YOLO¶
- _load_model(model_path: pathlib.Path, **kwargs: Any) None¶
Load YOLO model from path.
- Parameters:
model_path – Path to model file
**kwargs – Additional loading arguments
- Raises:
ModelError – If model cannot be loaded
- _validate_predict_params(conf: float, iou: float, imgsz: int) None¶
Validate prediction parameters before inference.
- Parameters:
conf – Confidence threshold
iou – IoU threshold
imgsz – Image size
- Raises:
ConfigurationError – If parameters are invalid
- predict(source: str | pathlib.Path | numpy.typing.NDArray[numpy.uint8] | PIL.Image.Image | List[Any], conf: float = 0.25, iou: float = 0.45, imgsz: int = 640, verbose: bool = False, **kwargs: Any) Any¶
Run inference on source.
- Parameters:
source – Input source (image path, array, PIL Image, or list)
conf – Confidence threshold
iou – IoU threshold for NMS
imgsz – Input image size
verbose – Verbose output
**kwargs – Additional inference arguments
- Returns:
Ultralytics Results object(s)
- Raises:
ConfigurationError – If parameters (conf, iou, imgsz) are invalid
InferenceError – If prediction fails
Example
>>> # Single image >>> results = detector.predict("image.jpg", conf=0.5) >>> >>> # Batch of images >>> results = detector.predict(["img1.jpg", "img2.jpg"], conf=0.5) >>> >>> # NumPy array >>> img : NDArray[np.uint8] = np.random.rand(640, 640, 3).astype(np.uint8) >>> results = detector.predict(img, conf=0.5)
- predict_batch(sources: List[str | pathlib.Path | numpy.typing.NDArray[numpy.uint8]], batch_size: int = 32, **kwargs: Any) List[Any]¶
Run batch inference on multiple sources.
- Parameters:
sources – List of input sources
batch_size – Batch size for processing
**kwargs – Additional inference arguments
- Returns:
List of results for each source
Example
>>> images = ["img1.jpg", "img2.jpg", "img3.jpg"] >>> results = detector.predict_batch(images, batch_size=8)
- warmup(iterations: int = 3, imgsz: int = 640) None¶
Warmup model with dummy inference.
- Parameters:
iterations – Number of warmup iterations
imgsz – Image size for warmup
Example
>>> detector.warmup(iterations=5, imgsz=640)
- get_names() dict[int, str]¶
Get class names mapping.
- Returns:
Dictionary mapping class IDs to names
Example
>>> names = detector.get_names() >>> print(names[0]) # 'person'
- property num_classes: int¶
Get number of classes.
- __repr__() str¶
String representation.
- class altametris.sara.yolo.YoloExporter(model_path: str | pathlib.Path, output_dir: str | pathlib.Path | None = None)¶
Bases:
altametris.sara.core.base_exporter.BaseExporterYOLO exporter implementing BaseExporter interface.
Supports export to multiple formats via Ultralytics backend.
- Parameters:
model_path – Path to YOLO model weights
output_dir – Output directory for exports
Example
>>> exporter = YoloExporter(model_path="yolo11x.pt") >>> onnx_path = exporter.export(format="onnx", imgsz=640) >>> trt_path = exporter.export(format="tensorrt", imgsz=640, half=True)
- SUPPORTED_FORMATS = ['onnx', 'torchscript', 'tensorrt', 'coreml', 'tflite', 'engine']¶
- export(format: str = 'onnx', imgsz: int | tuple[int, int] = 640, half: bool = False, dynamic: bool = False, simplify: bool = True, **kwargs: Any) pathlib.Path¶
Export YOLO model to specified format.
- Parameters:
format – Export format
imgsz – Input image size (int or (height, width))
half – Use FP16 precision
dynamic – Dynamic axes for ONNX
simplify – Simplify ONNX model
**kwargs – Additional export arguments
- Returns:
Path to exported model
- Raises:
ExportError – If export fails
Example
>>> # Export to ONNX >>> exporter.export(format="onnx", imgsz=640, half=False) >>> >>> # Export to TensorRT >>> exporter.export(format="tensorrt", imgsz=640, half=True)
- validate_export(export_path: pathlib.Path, test_image: str | pathlib.Path | None = None, **kwargs: Any) bool¶
Validate exported model.
- Parameters:
export_path – Path to exported model
test_image – Optional test image for validation
**kwargs – Additional validation arguments
- Returns:
True if validation passes
- Raises:
ExportError – If validation fails
Example
>>> onnx_path = exporter.export(format="onnx") >>> exporter.validate_export(onnx_path, test_image="test.jpg")
- export_to_tensorrt(imgsz: int | tuple[int, int] = 640, half: bool = True, workspace: float = 4.0, **kwargs: Any) pathlib.Path¶
Export to TensorRT with optimized settings.
- Parameters:
imgsz – Input image size
half – Use FP16 precision
workspace – TensorRT workspace size (GB)
**kwargs – Additional TensorRT arguments
- Returns:
Path to TensorRT engine
Example
>>> trt_path = exporter.export_to_tensorrt(imgsz=640, half=True)
- export_to_onnx(imgsz: int | tuple[int, int] = 640, dynamic: bool = True, simplify: bool = True, **kwargs: Any) pathlib.Path¶
Export to ONNX with optimized settings.
- Parameters:
imgsz – Input image size
dynamic – Dynamic axes for variable input size
simplify – Simplify ONNX graph
**kwargs – Additional ONNX arguments
- Returns:
Path to ONNX model
Example
>>> onnx_path = exporter.export_to_onnx(imgsz=640, dynamic=True)
- __repr__() str¶
String representation.
- class altametris.sara.yolo.YoloModel(model_path: str | pathlib.Path | None = None, version: str = '11', task: str = 'detect', size: str = 'x', pretrained: bool = False, device: str = 'auto', **kwargs: Any)¶
Bases:
altametris.sara.core.base_model.BaseModelYOLO model wrapper implementing BaseModel interface.
Provides standardized interface for YOLO models from Ultralytics with support for multiple versions, tasks, and sizes.
- Parameters:
model_path – Path to existing model weights (optional)
version – YOLO version (“11” or “v8”)
task – YOLO task (“detect”, “segment”, “obb”, “pose”, “classify”)
size – Model size (“n”, “s”, “m”, “l”, “x”)
pretrained – Load pretrained weights from Ultralytics
device – Device for model (“cpu”, “cuda”, “mps”, “auto”)
Example
>>> # Create from scratch >>> model = YoloModel(version="11", task="detect", size="x") >>> >>> # Load from weights >>> model = YoloModel(model_path="weights/best.pt")
- SUPPORTED_VERSIONS = ['11', 'v8']¶
- SUPPORTED_TASKS = ['detect', 'segment', 'obb', 'pose', 'classify']¶
- SUPPORTED_SIZES = ['n', 's', 'm', 'l', 'x']¶
- yolo: ultralytics.YOLO¶
- _validate_init_params(version: str, task: str, size: str, model_path: str | pathlib.Path | None, pretrained: bool) None¶
Validate initialization parameters.
- _get_model_name(version: str, task: str, size: str) str¶
Generate Ultralytics model name.
- Parameters:
version – YOLO version
task – Task type
size – Model size
- Returns:
Model name string (e.g., “yolo11x-seg.pt”)
- forward(x: torch.Tensor, **kwargs: Any) Any¶
Forward pass through YOLO model.
- Parameters:
x – Input tensor (B, C, H, W)
**kwargs – Additional forward arguments
- Returns:
Model output
Example
>>> x = torch.randn(1, 3, 640, 640) >>> output = model(x)
- load_weights(path: str | pathlib.Path, **kwargs: Any) None¶
Load weights from file.
- Parameters:
path – Path to weights file
**kwargs – Additional loading arguments
- Raises:
ModelError – If weights cannot be loaded
- save_weights(path: str | pathlib.Path, **kwargs: Any) None¶
Save model weights in Ultralytics checkpoint format.
This method uses the native Ultralytics save() API which creates a complete checkpoint file compatible with YOLO loading.
- Parameters:
path – Path to save weights
**kwargs – Additional saving arguments
Example
>>> model.save_weights("weights/my_model.pt")
Note
The saved file is a complete Ultralytics checkpoint that can be reloaded with YoloModel(model_path=path) or YOLO(path).
- property names: dict[int, str]¶
Get class names mapping.
- property task: str¶
Get model task.
- property version: str¶
Get YOLO version.
- __repr__() str¶
String representation.
- class altametris.sara.yolo.YoloTrainer(model: altametris.sara.yolo.model.YoloModel, device: str = 'auto', callbacks: list[altametris.sara.core.base_callback.BaseCallback] | None = None)¶
Bases:
altametris.sara.core.base_trainer.BaseTrainerYOLO trainer implementing BaseTrainer interface.
Wraps Ultralytics training with Altametris callback system and standardized configuration.
- Parameters:
model – YOLO model to train
device – Training device
callbacks – Training callbacks
Example
>>> model = YoloModel(version="11", task="detect", size="n") >>> trainer = YoloTrainer(model=model, device="cuda") >>> results = trainer.train( ... dataset_config="data.yaml", ... epochs=100, ... batch_size=16, ... imgsz=640 ... )
- _resolve_device_for_ultralytics() str¶
Convert Altametris device format to Ultralytics-compatible format.
Ultralytics does not support ‘auto’ device. It requires explicit device specification: ‘cpu’, ‘0’, ‘1’, etc.
- Conversion rules:
‘auto’ -> ‘cpu’ (if no GPU) or ‘0’ (if GPU available)
‘cuda’ -> ‘0’ (first GPU)
‘cuda:0’ -> ‘0’ (extract GPU index)
‘cpu’ -> ‘cpu’ (unchanged)
- Returns:
Device string compatible with Ultralytics (e.g., ‘cpu’, ‘0’)
Note
This method checks actual GPU availability using torch.cuda.device_count() to avoid errors when CUDA is installed but no GPU is present.
- _register_ultralytics_callbacks() None¶
Bridge between Altametris callbacks and Ultralytics callbacks.
Registers hooks into Ultralytics training lifecycle that forward events to the Altametris callback manager. This ensures callbacks are triggered automatically during Ultralytics training.
- Ultralytics hooks registered:
on_train_start: Called when training begins
on_train_epoch_end: Called after each training epoch
on_val_end: Called after validation
on_train_end: Called when training completes
Note
This method is called automatically during __init__. Manual callback invocations in train() are not needed.
- load_config(config_path: str | pathlib.Path) Dict[str, Any]¶
Load and parse YAML configuration file.
Supports both dataset configuration files (data.yaml) and training parameter files (train-params.yaml).
- Parameters:
config_path – Path to YAML configuration file
- Returns:
Dictionary containing parsed configuration
- Raises:
TrainingError – If config file not found or invalid YAML
Example
>>> # Load dataset config >>> dataset_config = trainer.load_config("data/detect/config.yml") >>> print(dataset_config['names']) {0: 'Chassis A', 1: 'Chassis C', ...}
>>> # Load training params >>> train_params = trainer.load_config("data/detect/train-parameter-detect.yaml") >>> epochs = train_params['train']['epochs']
- train(dataset_config: str | pathlib.Path | Dict[str, Any], epochs: int = 100, batch_size: int = 16, imgsz: int = 640, save_dir: str | pathlib.Path | None = None, **kwargs: Any) dict[str, Any]¶
Train YOLO model.
- Parameters:
dataset_config – Path to dataset YAML configuration or dict
epochs – Number of training epochs
batch_size – Batch size
imgsz – Input image size
save_dir – Directory to save results
**kwargs – Additional Ultralytics training arguments
- Returns:
Training results dictionary
- Raises:
TrainingError – If training fails
Example
>>> # Using YAML path >>> results = trainer.train( ... dataset_config="data.yaml", ... epochs=10, ... batch_size=8, ... imgsz=640 ... )
>>> # Using dict config >>> config = trainer.load_config("train-params.yaml") >>> results = trainer.train( ... dataset_config="data.yaml", ... epochs=config['train']['epochs'], ... batch_size=config['train']['batch_size'] ... )
- validate(dataset_config: str | pathlib.Path, **kwargs: Any) dict[str, Any]¶
Validate YOLO model.
- Parameters:
dataset_config – Path to validation dataset config
**kwargs – Additional validation arguments
- Returns:
Validation metrics
- Raises:
TrainingError – If validation fails
Example
>>> metrics = trainer.validate(dataset_config="val.yaml")
- _extract_metrics(results: Any) dict[str, Any]¶
Extract metrics from Ultralytics results.
- Parameters:
results – Ultralytics training/validation results
- Returns:
Dictionary of metrics
- resume_training(checkpoint_path: str | pathlib.Path, **kwargs: Any) dict[str, Any]¶
Resume training from checkpoint.
- Parameters:
checkpoint_path – Path to checkpoint file
**kwargs – Additional training arguments
- Returns:
Training results
Example
>>> results = trainer.resume_training("runs/train/exp/weights/last.pt")