### Initialize ClearML SDK Setup Source: https://docs.ultralytics.com/integrations/clearml Initialize the ClearML SDK setup process. This command starts the configuration and prompts for necessary credentials to connect to the ClearML server. ```bash # Initialize your ClearML SDK setup process clearml-init ``` -------------------------------- ### Initialize and Train with BaseTrainer Source: https://docs.ultralytics.com/reference/engine/trainer Example of initializing a BaseTrainer with a configuration file and starting the training process. ```python >>> trainer = BaseTrainer(cfg="config.yaml") >>> trainer.train() ``` -------------------------------- ### YOLOX Training Command Example Source: https://docs.ultralytics.com/compare/yolox-vs-yolov5 An example command for training a YOLOX model. This typically requires manual repository cloning, setup.py installation, and complex CLI arguments, indicating a more involved setup process compared to YOLOv5. ```bash # Example YOLOX training command python tools/train.py -f exps/default/yolox_s.py -d 1 -b 64 --fp16 -o ``` -------------------------------- ### Initialize and Run Similarity Search App Source: https://docs.ultralytics.com/reference/solutions/similarity_search Instantiate the SearchApp with a specified data directory and device, then start the Flask web server. Ensure Flask is installed. ```python from ultralytics.solutions import SearchApp app = SearchApp(data="path/to/images", device="cuda") app.run(debug=True) ``` -------------------------------- ### Train Example with MNIST (CLI) Source: https://docs.ultralytics.com/datasets/classify/mnist Start training a classification model on the MNIST dataset from a pretrained .pt file using the CLI. ```bash yolo classify train data=mnist model=yolo26n-cls.pt epochs=100 imgsz=28 ``` -------------------------------- ### Train YOLOv5 Model with CLI Source: https://docs.ultralytics.com/compare/yolo11-vs-yolov5 This example demonstrates how to train a YOLOv5 model using its command-line interface (CLI). It involves cloning the repository, installing dependencies, and running the training script. ```bash # Clone the repository and run the training script git clone https://github.com/ultralytics/yolov5 cd yolov5 pip install -r requirements.txt python train.py --img 640 --batch 16 --epochs 50 --data coco128.yaml --weights yolov5s.pt ``` -------------------------------- ### PoseTrainer Initialization and Training Example Source: https://docs.ultralytics.com/reference/models/yolo/pose/train Demonstrates how to initialize the PoseTrainer with specific model and data configurations and then start the training process. This snippet is useful for setting up and running a pose estimation training session. ```python >>> from ultralytics.models.yolo.pose import PoseTrainer >>> args = dict(model="yolo26n-pose.pt", data="coco8-pose.yaml", epochs=3) >>> trainer = PoseTrainer(overrides=args) >>> trainer.train() ``` -------------------------------- ### Getting Started with YOLO26 Source: https://docs.ultralytics.com/compare/yolo26-vs-yolov9 Load a pre-trained YOLO26 model, train it on custom data, and run inference. This example uses the Ultralytics API and assumes necessary installations. ```python from ultralytics import YOLO # Load the latest state-of-the-art YOLO26 nano model model = YOLO("yolo26n.pt") # Train the model on the COCO8 dataset utilizing the MuSGD optimizer results = model.train( data="coco8.yaml", epochs=100, imgsz=640, device=0, # Uses GPU 0, or use 'cpu' for CPU training ) # Run an NMS-free inference on a sample image predictions = model("https://ultralytics.com/images/bus.jpg") # Display the bounding boxes and confidences predictions[0].show() ``` -------------------------------- ### Example: Run Analytics Solution with Custom Configuration Source: https://docs.ultralytics.com/reference/cfg/__init__ Shows how to execute the analytics solution using `handle_yolo_solutions`, specifying custom configuration parameters like confidence threshold and video source. ```python handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"]) ``` -------------------------------- ### Getting Started with YOLO26 Training and Inference Source: https://docs.ultralytics.com/compare/yolo26-vs-yolov6 This Python code demonstrates how to load a YOLO26 model, train it on a custom dataset, perform inference, and export the model. It requires the Ultralytics Python package to be installed. ```python from ultralytics import YOLO # Load the highly efficient YOLO26 nano model model = YOLO("yolo26n.pt") # Train the model on the COCO8 dataset for 100 epochs results = model.train(data="coco8.yaml", epochs=100, imgsz=640) # Run end-to-end NMS-free inference on an image results = model.predict("https://ultralytics.com/images/bus.jpg") # Export seamlessly to ONNX for CPU deployment model.export(format="onnx") ``` -------------------------------- ### Initialize Git and DVCLive Environment Source: https://docs.ultralytics.com/integrations/dvc Set up a Git repository and initialize DVCLive for experiment tracking. Ensure to configure user email and name for Git. ```bash git init -q git config --local user.email "your-email" git config --local user.name "Your Name" dvc init -q git commit -m "DVC init" ``` -------------------------------- ### setup_model Source: https://docs.ultralytics.com/reference/engine/trainer Load, create, or download a model for any task. This method handles the initialization of the model, including loading checkpoints or pre-trained weights. ```APIDOC ## Method `ultralytics.engine.trainer.BaseTrainer.setup_model` ### Description Load, create, or download model for any task. ### Method Signature ```python def setup_model(self) ``` ### Returns - **dict | None**: Checkpoint to resume training from, or None if no checkpoint is loaded. ``` -------------------------------- ### Getting Started with Ultralytics YOLO26 Python API Source: https://docs.ultralytics.com/compare/yolov6-vs-yolov10 Load, train, evaluate, predict, and export YOLO26 models using the Ultralytics Python API. This example demonstrates initializing a nano model, training on COCO8, evaluating, performing NMS-free inference, and exporting to ONNX format. ```python from ultralytics import YOLO # Initialize the cutting-edge YOLO26 nano model model = YOLO("yolo26n.pt") # Train the model effortlessly on the COCO8 dataset results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=0) # Evaluate model performance on validation data metrics = model.val() # Run real-time NMS-free inference on a target image predictions = model.predict("https://ultralytics.com/images/bus.jpg") # Export to ONNX format for cross-platform deployment model.export(format="onnx") ``` -------------------------------- ### Example Response for Class Statistics Source: https://docs.ultralytics.com/platform/api Example JSON response structure for the GET /api/datasets/{datasetId}/class-stats endpoint. ```JSON { "classes": [{ "classId": 0, "count": 1500, "imageCount": 450 }], "imageStats": { "widthHistogram": [{ "bin": 640, "count": 120 }], "heightHistogram": [{ "bin": 480, "count": 95 }], "pointsHistogram": [{ "bin": 4, "count": 200 }] }, "locationHeatmap": { "bins": [ [5, 10], [8, 3] ], "maxCount": 50 }, "dimensionHeatmap": { "bins": [ [2, 5], [3, 1] ], "maxCount": 12, "minWidth": 10, "maxWidth": 1920, "minHeight": 10, "maxHeight": 1080 }, "classNames": ["person", "car", "dog"], "cached": true, "sampled": false, "sampleSize": 1000 } ``` -------------------------------- ### Install JupyterLab and Ultralytics Source: https://docs.ultralytics.com/integrations/jupyterlab Install the necessary packages for using JupyterLab with Ultralytics. This is a prerequisite for running the subsequent code examples. ```bash pip install jupyterlab ultralytics ``` -------------------------------- ### Example Response for Models Trained on Dataset Source: https://docs.ultralytics.com/platform/api Example JSON response structure for the GET /api/datasets/{datasetId}/models endpoint. ```JSON { "models": [ { "_id": "model_abc123", "name": "experiment-1", "slug": "experiment-1", "status": "completed", "task": "detect", "epochs": 100, "bestEpoch": 87, "projectId": "project_xyz", "projectSlug": "my-project", "projectIconColor": "#3b82f6", "projectIconLetter": "M", "username": "johndoe", "startedAt": "2024-01-14T22:00:00Z", "completedAt": "2024-01-15T10:00:00Z", "createdAt": "2024-01-14T21:55:00Z", "metrics": { "mAP50": 0.85, "mAP50-95": 0.72, "precision": 0.88, "recall": 0.81 } } ], "count": 1 } ``` -------------------------------- ### Initialize OBBModel with Configuration and Weights Source: https://docs.ultralytics.com/reference/models/yolo/obb/train Use this method to create an OBBModel instance with specific configuration and pretrained weights. Ensure the configuration file and weights path are correct. ```python def get_model(self, cfg: str | dict | None = None, weights: str | Path | None = None, verbose: bool = True) -> OBBModel: """Return OBBModel initialized with specified config and weights.""" model = OBBModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1) if weights: model.load(weights) return model ``` ```python >>> trainer = OBBTrainer() >>> model = trainer.get_model(cfg="yolo26n-obb.yaml", weights="yolo26n-obb.pt") ``` -------------------------------- ### Run TrackZone Example with CLI Source: https://docs.ultralytics.com/guides/trackzone Execute a basic TrackZone example using the command-line interface. ```bash yolo solutions trackzone show=True ``` -------------------------------- ### Example cURL Request Source: https://docs.ultralytics.com/platform/api This example shows how to make a GET request to the datasets endpoint using cURL with the correct Authorization header. ```curl curl -H "Authorization: Bearer YOUR_API_KEY" \ https://platform.ultralytics.com/api/datasets ``` -------------------------------- ### Start TensorBoard Logging Source: https://docs.ultralytics.com/integrations/tensorboard Launch TensorBoard to visualize training metrics. Ensure to replace 'path/to/your/tensorboard/logs' with the actual directory where YOLO26 saves its logs. ```bash tensorboard --logdir path/to/your/tensorboard/logs ``` -------------------------------- ### Speed Estimator Example Usage Source: https://docs.ultralytics.com/reference/solutions/speed_estimation Demonstrates how to initialize and use the `SpeedEstimator` to process a single image frame. This example shows the basic setup for speed estimation. ```python estimator = SpeedEstimator() image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) results = estimator.process(image) ``` -------------------------------- ### Use Pre-built Solutions with YOLO CLI Source: https://docs.ultralytics.com/usage/cli Leverage ready-to-use solutions for common computer vision tasks. This example shows how to count objects in a video. ```bash yolo solutions count source="path/to/video.mp4" ``` -------------------------------- ### Initialize ClearML SDK Source: https://docs.ultralytics.com/integrations/clearml Initialize the ClearML SDK in your environment. This command sets up the connection to your ClearML server. ```bash clearml-init ``` -------------------------------- ### Get GitHub Assets Example Source: https://docs.ultralytics.com/reference/utils/downloads Example of how to call the get_github_assets function to retrieve the latest release tag and assets from the ultralytics/assets repository. This function is useful for programmatically accessing release information. ```python >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest") ``` -------------------------------- ### Create Instances with Bounding Boxes, Segments, and Keypoints Source: https://docs.ultralytics.com/reference/utils/instance Demonstrates how to initialize an Instances object with bounding box, segment, and keypoint data. Assumes normalized coordinates by default. ```python from ultralytics.utils.instance import Instances import numpy as np instances = Instances( bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]), segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])], keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]), ) ``` -------------------------------- ### on_predict_start Callback Function Source: https://docs.ultralytics.com/reference/utils/callbacks/base Called at the beginning of the prediction process. This is useful for any setup required before predictions start. ```python def on_predict_start(predictor): """Called when the prediction starts.""" pass ``` -------------------------------- ### BaseSolution Initialization and Usage Example Source: https://docs.ultralytics.com/reference/solutions/solutions Demonstrates how to initialize and use the BaseSolution class for tracking objects within a defined region. Requires a YOLO model file and an image. ```python >>> solution = BaseSolution(model="yolo26n.pt", region=[(0, 0), (100, 0), (100, 100), (0, 100)]) >>> solution.initialize_region() >>> image = cv2.imread("image.jpg") >>> solution.extract_tracks(image) >>> solution.display_output(image) ``` -------------------------------- ### Fine-tune Downloaded Model Source: https://docs.ultralytics.com/platform/explore Example of using a locally downloaded model as a starting point for fine-tuning on a custom dataset. ```bash yolo train model=path/to/downloaded-model.pt data=my-dataset.yaml epochs=50 ``` -------------------------------- ### Run Tracking with Default and Custom Trackers (CLI) Source: https://docs.ultralytics.com/modes/track Shows how to initiate object tracking from the command line using the default BoT-SORT tracker and how to specify ByteTrack by providing its YAML configuration. ```bash # Default tracker (BoT-SORT) yolo track model=yolo26n.pt source="https://youtu.be/LNwODJXcvt4" show # Switch to ByteTrack yolo track model=yolo26n.pt source="https://youtu.be/LNwODJXcvt4" tracker="bytetrack.yaml" ``` -------------------------------- ### Example Usage of PositionEmbeddingRandom Source: https://docs.ultralytics.com/reference/models/sam/modules/blocks Demonstrates how to initialize and use the PositionEmbeddingRandom module to get positional encoding for a given size. ```python >>> pe = PositionEmbeddingRandom(num_pos_feats=64) >>> size = (32, 32) >>> encoding = pe(size) >>> print(encoding.shape) torch.Size([128, 32, 32]) ``` -------------------------------- ### LRPCHead Initialization Example Source: https://docs.ultralytics.com/reference/nn/modules/head Demonstrates how to create an LRPCHead instance with vocabulary, proposal filter, and localization modules. The head can be enabled or disabled. ```python vocab = nn.Conv2d(256, 80, 1) pf = nn.Conv2d(256, 1, 1) loc = nn.Conv2d(256, 4, 1) head = LRPCHead(vocab, pf, loc, enabled=True) ``` -------------------------------- ### Full Implementation of build_sam3_image_model Source: https://docs.ultralytics.com/reference/models/sam/build_sam3 Provides the complete source code for the build_sam3_image_model function, including model component creation, checkpoint loading, and evaluation setup. Ensure CLIP is installed via `pip install git+https://github.com/ultralytics/CLIP.git` before running. ```python def build_sam3_image_model(checkpoint_path: str, enable_segmentation: bool = True, compile: bool = False): """Build SAM3 image model. Args: checkpoint_path: Optional path to model checkpoint enable_segmentation: Whether to enable segmentation head compile: Whether to enable compilation of the model Returns: A SAM3 image model """ try: import clip except ImportError: from ultralytics.utils.checks import check_requirements check_requirements("git+https://github.com/ultralytics/CLIP.git") import clip # Create visual components compile_mode = "default" if compile else None vision_encoder = _create_vision_backbone(compile_mode=compile_mode, enable_inst_interactivity=True) # Create text components text_encoder = VETextEncoder( tokenizer=clip.simple_tokenizer.SimpleTokenizer(), d_model=256, width=1024, heads=16, layers=24, ) # Create visual-language backbone backbone = SAM3VLBackbone(visual=vision_encoder, text=text_encoder, scalp=1) # Create transformer components transformer = _create_sam3_transformer() # Create dot product scoring dot_prod_scoring = DotProductScoring( d_model=256, d_proj=256, prompt_mlp=MLP( input_dim=256, hidden_dim=2048, output_dim=256, num_layers=2, residual=True, out_norm=nn.LayerNorm(256), ), ) # Create segmentation head if enabled segmentation_head = ( UniversalSegmentationHead( hidden_dim=256, upsampling_stages=3, aux_masks=False, presence_head=False, dot_product_scorer=None, act_ckpt=True, cross_attend_prompt=nn.MultiheadAttention( num_heads=8, dropout=0, embed_dim=256, ), pixel_decoder=PixelDecoder( num_upsampling_stages=3, interpolation_mode="nearest", hidden_dim=256, compile_mode=compile_mode, ), ) if enable_segmentation else None ) # Create geometry encoder input_geometry_encoder = SequenceGeometryEncoder( pos_enc=PositionEmbeddingSine( num_pos_feats=256, normalize=True, scale=None, temperature=10000, ), encode_boxes_as_points=False, boxes_direct_project=True, boxes_pool=True, boxes_pos_enc=True, d_model=256, num_layers=3, layer=TransformerEncoderLayer( d_model=256, dim_feedforward=2048, dropout=0.1, pos_enc_at_attn=False, pre_norm=True, pos_enc_at_cross_attn_queries=False, pos_enc_at_cross_attn_keys=True, ), use_act_ckpt=True, add_cls=True, add_post_encode_proj=True, ) # Create the SAM3SemanticModel model model = SAM3SemanticModel( backbone=backbone, transformer=transformer, input_geometry_encoder=input_geometry_encoder, segmentation_head=segmentation_head, num_feature_levels=1, o2m_mask_predict=True, dot_prod_scoring=dot_prod_scoring, use_instance_query=False, multimask_output=True, ) # Load checkpoint model = _load_checkpoint(model, checkpoint_path) model.eval() return model ``` -------------------------------- ### Install Dependencies and Run Server Source: https://docs.ultralytics.com/guides/vertex-ai-deployment-with-docker Commands to install project dependencies using pip and to run the FastAPI server using uv. Ensure you are in the project's root directory. ```bash # Install dependencies uv pip install -e . # Run the FastAPI server directly uv run src/main.py ``` -------------------------------- ### Create Setup Intent for Payment Method Source: https://docs.ultralytics.com/platform/api Creates a setup intent, returning a client secret required for adding a new payment method to the account. ```bash POST /api/billing/payment-methods/setup ``` -------------------------------- ### PoseMetrics.clear_image_metrics Source: https://docs.ultralytics.com/reference/utils/metrics Clears all stored per-image metrics. This is useful for resetting the metrics calculation, for example, when starting a new evaluation or processing a new set of images. ```APIDOC ## Method `ultralytics.utils.metrics.PoseMetrics.clear_image_metrics` ### Description Clear stored per-image metrics. ### Method ```python clear_image_metrics(self) -> None ``` ### Returns - `None` ``` -------------------------------- ### Example: Run People Counting Solution Source: https://docs.ultralytics.com/reference/cfg/__init__ Demonstrates how to call `handle_yolo_solutions` to run the people counting solution with default settings. ```python handle_yolo_solutions(["count"]) ``` -------------------------------- ### Python Tracking Example Source: https://docs.ultralytics.com/datasets/track Use this Python snippet to perform multi-object tracking on a video source using a YOLO model. Ensure you have the Ultralytics library installed. ```python from ultralytics import YOLO model = YOLO("yolo26n.pt") results = model.track(source="https://youtu.be/LNwODJXcvt4", conf=0.1, iou=0.7, show=True) ``` -------------------------------- ### Run Default Queue Management Example (CLI) Source: https://docs.ultralytics.com/guides/queue-management Execute a default queue management example using the Ultralytics CLI. This is a quick way to test the functionality. ```bash yolo solutions queue show=True ``` -------------------------------- ### Quickstart: Load, Train, and Infer with Ultralytics YOLO Source: https://docs.ultralytics.com/compare/yolov7-vs-damo-yolo Demonstrates the streamlined process of loading a pre-trained YOLOv7 model, training it on a custom dataset, running inference, and exporting the model to ONNX format using the Ultralytics Python package. ```python from ultralytics import YOLO # Load a pre-trained YOLOv7 model (or newer models like yolo26n.pt) model = YOLO("yolov7.pt") # Train the model on the COCO8 dataset with automated hyperparameter handling results = model.train(data="coco8.yaml", epochs=50, imgsz=640) # Run inference on an image predictions = model("https://ultralytics.com/images/bus.jpg") # Export to ONNX format for deployment model.export(format="onnx") ``` -------------------------------- ### CLIP Class Initialization and Usage Example Source: https://docs.ultralytics.com/reference/nn/text_model Demonstrates how to initialize the CLIP text model and encode text into feature vectors. Ensure PyTorch and the CLIP library are installed. ```python >>> import torch >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") >>> clip_model = CLIP(size="ViT-B/32", device=device) >>> tokens = clip_model.tokenize(["a photo of a cat", "a photo of a dog"]) >>> text_features = clip_model.encode_text(tokens) >>> print(text_features.shape) ``` -------------------------------- ### Train YOLOv26 with Default Augmentations Source: https://docs.ultralytics.com/integrations/albumentations Load a pretrained YOLOv26 model and start training with default augmentations automatically applied by Albumentations. Ensure the Albumentations package is installed. ```python from ultralytics import YOLO # Load a pretrained model model = YOLO("yolo26n.pt") # Train the model with default augmentations results = model.train(data="coco8.yaml", epochs=100, imgsz=640) ``` -------------------------------- ### Run Tracking with Default and Custom Trackers (Python) Source: https://docs.ultralytics.com/modes/track Demonstrates how to run object tracking on a video using the default BoT-SORT tracker and how to switch to the ByteTrack tracker by specifying a YAML configuration file. ```Python from ultralytics import YOLO model = YOLO("yolo26n.pt") # Default tracker (BoT-SORT) results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True) # Switch to ByteTrack results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml") ``` -------------------------------- ### TQDM as a Context Manager Source: https://docs.ultralytics.com/reference/utils/tqdm Illustrates using TQDM as a context manager, which automatically handles setup and cleanup. This example configures the progress bar for byte units with auto-scaling. ```python >>> with TQDM(total=100, unit="B", unit_scale=True) as pbar: ... for i in range(100): ... pbar.update(1) ``` -------------------------------- ### Example Usage of generate_crop_boxes Source: https://docs.ultralytics.com/reference/models/sam/amg Demonstrates how to call the `generate_crop_boxes` function with sample parameters and shows the expected output variables. ```python im_size = (800, 1200) # Height, width n_layers = 3 overlap_ratio = 0.25 crop_boxes, layer_idxs = generate_crop_boxes(im_size, n_layers, overlap_ratio) ``` -------------------------------- ### Get Pip Distribution Name Source: https://docs.ultralytics.com/reference/utils/checks Retrieves the pip distribution name for a given import name. Useful for mapping common import aliases to their installed package names. ```python def get_distribution_name(import_name: str) -> str: """Get the pip distribution name for a given import name (e.g., 'cv2' -> 'opencv-python-headless').""" for dist in metadata.distributions(): top_level = (dist.read_text("top_level.txt") or "").split() if import_name in top_level: return dist.metadata["Name"] return import_name ``` -------------------------------- ### BaseTrainer.setup_model Source: https://docs.ultralytics.com/reference/engine/trainer Loads, creates, or downloads a model for any task. It handles checkpoint loading and model initialization. ```python def setup_model(self): """Load, create, or download model for any task. Returns: (dict | None): Checkpoint to resume training from, or None if no checkpoint is loaded. """ if isinstance(self.model, torch.nn.Module): # if model is loaded beforehand. No setup needed return cfg, weights = self.model, None ckpt = None if str(self.model).endswith(".pt"): weights, ckpt = load_checkpoint(self.model) cfg = weights.yaml if isinstance(self.args.pretrained, (str, Path)): weights, _ = load_checkpoint(self.args.pretrained) elif self.args.pretrained is False and not self.resume: weights = None self.model = self.get_model(cfg=cfg, weights=weights, verbose=RANK in {-1, 0}) # calls Model(cfg, weights) return ckpt ``` -------------------------------- ### YOLOv7 Training Command Example Source: https://docs.ultralytics.com/compare/yolo11-vs-yolov7 Illustrates a typical command-line execution for training a YOLOv7 model. This example highlights the need for manual configuration of paths, devices, and other parameters, contrasting with YOLO11's API-driven approach. ```bash python train.py --workers 8 --device 0 --batch-size 32 --data data/coco.yaml --img 640 640 --cfg cfg/training/yolov7.yaml --weights 'yolov7_training.pt' ``` -------------------------------- ### Resolve QNN Library Paths Source: https://docs.ultralytics.com/reference/utils/export/qnn Use this function to get the paths for the QNN Execution Provider and HTP backend libraries. It automatically detects the installation method of onnxruntime-qnn. ```python def qnn_library_paths() -> tuple[str | None, str]: """Resolve the QNN Execution Provider and HTP backend library paths for the installed onnxruntime-qnn build. onnxruntime-qnn ships two ways: plugin builds expose an `onnxruntime_qnn` helper module, while monolithic builds expose `QNNExecutionProvider` directly and bundle the QNN backend libraries in `onnxruntime/capi`. Returns: (tuple[str | None, str]): `(ep_library_path, htp_backend_path)`. `ep_library_path` is `None` when QNN is already built into ONNX Runtime and does not need `register_execution_provider_library`. """ try: import onnxruntime_qnn as qnn_ep return qnn_ep.get_library_path(), qnn_ep.get_qnn_htp_path() except ImportError: import onnxruntime capi = Path(onnxruntime.__file__).parent / "capi" if "QNNExecutionProvider" in onnxruntime.get_available_providers(): ep_lib = None else: ep_lib = capi / ("onnxruntime_providers_qnn.dll" if WINDOWS else "libonnxruntime_providers_qnn.so") htp_lib = "QnnHtp.dll" if WINDOWS else "libQnnHtp.so" return str(ep_lib) if ep_lib else None, str(capi / htp_lib) ```