Ultralytics YOLO27: Trag dich auf die Warteliste ein.
Erste Schritte

CoreML-Export für YOLO26-Modelle#

Apple verbaut in jedem modernen iPhone, iPad und Mac eigens entwickelte KI-Chips — die Neural Engine — und CoreML ist der von Ultralytics unterstützte Weg, Modelle heute darauf bereitzustellen. Beim Export von Ultralytics YOLO26-Modellen nach CoreML wird ein trainierter .pt-Checkpoint in ein natives .mlpackage umgewandelt. Damit lassen sich alle sieben YOLO-Aufgaben mit geringer Latenz direkt auf dem Gerät ausführen, ohne Netzwerkverbindung und ohne dass Daten das Gerät verlassen.

Führe YOLO schon heute mit den offiziellen mobilen Apps auf der Apple Neural Engine aus

Das offizielle Ultralytics YOLO iOS SDK und Flutter-Plugin führen CoreML-Exporte ohne zusätzliche Einrichtung auf der Apple Neural Engine aus: mit Kamera-Inferenz in Echtzeit, Vorhersagen für einzelne Bilder und automatischem Modell-Download für alle sieben YOLO26-Aufgaben, einschließlich Tiefe. Informationen zur NPU-Bereitstellung für Android findest du in der Qualcomm QNN-Integration.

Offizielle Eingabegrößen für Mobilgeräte

Exportiere Klassifizierungsmodelle mit imgsz=224. Exportiere Erkennungs-, Segmentierungs-, semantische Segmentierungs-, Tiefen-, Pose- und OBB-Modelle mit imgsz=640. Dieser Standard von 224/640 wird von den offiziellen CoreML-, LiteRT- und QNN-Assets für Mobilgeräte verwendet.

Apples neues Core-AI-Format

Apple hat das neue Core-AI-Framework und das Format .aimodel für die Generation iOS 27 und macOS 27 eingeführt, und Ultralytics exportiert es mit format="coreai". CoreML bleibt das Standardformat für die Ultralytics-SDKs für iOS und Flutter. Diese laden Core AI auf Geräten mit iOS 27 optional; außerdem bietet CoreML breitere Kompatibilität mit Apple-Geräten.



Ansehen: So exportierst du Ultralytics YOLO26 mit INT8-Quantisierung nach CoreML | Bereitstellung auf Apple-Geräten | iOS/macOS 🍎

Was ist CoreML?#

Apple CoreML deployment pipeline

CoreML (von Apple als „Core ML“ geschrieben) ist Apples geräteinternes Machine-Learning-Framework. Es lädt Modelle im modernen Format ML Program – dem .mlpackage-Paket, das der Ultralytics-Exporter erstellt – und verteilt ihre Ausführung auf CPU, GPU und Apple Neural Engine (ANE), die dedizierte NPU in jedem Apple-Silicon-Chip. Da alles lokal ausgeführt wird, funktioniert die Inferenz offline, verursacht keine Netzwerklatenz und belässt Nutzerdaten auf dem Gerät.

CoreML ist direkt in Apples Vision-Framework integriert. Dieses verarbeitet die Bildskalierung und Ausrichtung, bevor die Bilder in das Modell gelangen. So übergibt das Ultralytics-iOS-SDK Kamerabilder an YOLO – praktisch ohne Vorverarbeitungsaufwand.

Warum YOLO26 nach CoreML exportieren?#

  • Geschwindigkeit der Neural Engine: CoreML führt unterstützte Operationen auf Apples Neural Engine aus und ermöglicht so Inferenz mit geringer Latenz auf dem Gerät. Sieh dir die Tabelle mit den Messwerten auf physischen Geräten unten an und miss die Geschwindigkeit deines konkreten Exports auf der Zielhardware.
  • Ausgabe auswählen: Bei Standardexporten überlässt du NMS deiner Anwendung. Verwende nms=True, um NMS einzubetten, oder nms=False für den NMS-freien Kopf von YOLO26.
  • Privat und offline: Die gesamte Berechnung findet auf dem Gerät statt – keine Cloud-Aufrufe, keine API-Schlüssel, umfassender Datenschutz.
  • Ein Export für das gesamte Ökosystem: Dasselbe .mlpackage läuft unter iOS, iPadOS, macOS, watchOS, tvOS und visionOS und bildet die Grundlage für das offizielle iOS-SDK und das offizielle Flutter-Plugin von Ultralytics.

Gemessene Leistung#

End-to-End-Inferenz für ein einzelnes Bild mit den standardisierten v8.3.0 YOLO26n-INT8-CoreML-Assets auf einem iPhone 17 Pro mit 12 GB Speicher und iOS 27.0.1. Der A19 Pro verfügt über eine 6-Core-CPU (2 Performance- und 4 Effizienzkerne), eine 6-Core-GPU mit Neural Accelerators und eine 16-Core Neural Engine. Jede Zelle zeigt die Gesamtzeit (Vorverarbeitung + Inferenz + Nachverarbeitung, ohne Annotation) und darunter die Aufteilung nach Phasen. Unter iOS skaliert Vision die Eingabe innerhalb der Inferenzanfrage, daher wird die Vorverarbeitung mit 0 angegeben und ihre Dauer der Inferenz zugerechnet.

ModellAufgabeGröße
(Pixel)
CPU
Core ML .cpuOnly
(ms)
CPU + ANE bevorzugt
Core ML .cpuAndNeuralEngine
(ms)
YOLO26nDetect6408.8
0.0 / 8.8 / 0.0
3.7
0.0 / 3.7 / 0.0
YOLO26n-segSegment64012.3
0.0 / 11.7 / 0.6
4.9
0.0 / 4.3 / 0.6
YOLO26n-semSemantisch6409.3
0.0 / 9.0 / 0.3
4.4
0.0 / 4.1 / 0.3
YOLO26n-depthTiefe64026.0
0.0 / 25.1 / 1.0
5.5
0.0 / 4.7 / 0.9
YOLO26n-clsKlassifizieren2244.1
0.0 / 4.1 / 0.0
2.0
0.0 / 1.9 / 0.0
YOLO26n-posePose64012.0
0.0 / 12.0 / 0.0
4.0
0.0 / 4.0 / 0.0
YOLO26n-obbOBB64010.7
0.0 / 10.7 / 0.0
3.9
0.0 / 3.9 / 0.0
  • Die exakten v8.3.0-Release-Assets geben Eingabegrößen von 224×224 für die Klassifizierung und 640×640 für alle anderen Aufgaben an.
  • Unter iOS 27.0.1 stürzt die .cpuOnly-Inferenz der Tiefen-, Pose- und OBB-Modelle l und x innerhalb der CPU-Kernels von Core ML ab (EXC_BAD_ACCESS in libBNNS); dieselben Modelle laufen mit .cpuAndNeuralEngine, und alle anderen Aufgaben und Größen laufen auf der CPU.
  • Geschwindigkeitswerte sind Latenzen bei Einzelbild-Bursts – der Mittelwert aus 15 Durchläufen nach 3 Aufwärmdurchläufen auf bus.jpg. Gemessen wurden sie anhand der Zeitangaben pro Phase des iOS-SDKs über die Benchmark-Testumgebung des Flutter-Plugins im Profilmodus (optimierter nativer Code). Die Reihenfolge von CPU und Beschleuniger wechselte bei den Aufgaben innerhalb eines sequenziellen Durchlaufs. Bei CPU-Zeilen wird Core ML .cpuOnly angefordert, bei Zeilen mit bevorzugter CPU- und ANE-Ausführung .cpuAndNeuralEngine; die endgültige Zuweisung der Operationen übernimmt Core ML. Bei dauerhaftem Echtzeit-Kamerabetrieb fallen die Werte höher aus, da die Aufnahme- und Skalierungspipeline sowie die thermische Stabilisierung hinzukommen. Bei einer historischen Kameramessung vor der Standardisierung wurden auf demselben Gerät 11.3 ms/Bild für YOLO26n detect und 16.5 ms/Bild für YOLO26n Depth gemessen – weitere Informationen zur Profilierung im Dauerbetrieb findest du in der Leistungsdokumentation des iOS-SDKs.
  • Vergleiche die CPU-/GPU-Ergebnisse für Android in der LiteRT-Integration und die NPU-Ergebnisse für Snapdragon in der Qualcomm-QNN-Integration.

Unterstützte Aufgaben#

Der CoreML-Export unterstützt alle sieben Aufgaben von Ultralytics. Semantische Segmentierung und Tiefenschätzung sind nur mit YOLO26 verfügbar – der einzigen Modellfamilie, die diese Ausgabeköpfe mitbringt.

AufgabeYOLOv8YOLO11YOLO26
Erkennung✅✅✅
Segmentierung✅✅✅
Semantik❌❌✅
Tiefe❌❌✅
Klassifizierung✅✅✅
Pose✅✅✅
OBB✅✅✅

YOLO26-Modelle nach CoreML exportieren#

Installation#

Führe zum Installieren des erforderlichen Pakets Folgendes aus:

Installation
# Install the required package for YOLO26
pip install ultralytics

Der coremltools-Konverter wird beim ersten Export automatisch installiert. Der Export läuft unter macOS oder Linux auf x86. Detaillierte Anweisungen und bewährte Vorgehensweisen findest du in unserem Installationsleitfaden und im Leitfaden zu häufigen Problemen.

Verwendung#

Das CoreML-Format unterstützt die Modi Export, Vorhersage und Validierung. Inferenz und Validierung mit CoreML sind nur unter macOS möglich. Exportiere dein Modell und lade anschließend das exportierte Modell, um Inferenz auszuführen oder die Genauigkeit zu validieren.

Exportieren
from ultralytics import YOLO

# Ein YOLO26-Modell laden
model = YOLO("yolo26n.pt")

# Mit INT8-Gewichtquantisierung nach CoreML exportieren, passend zu den offiziellen App-Modellen
model.export(format="coreml", quantize=8, imgsz=640)  # für die Klassifizierung imgsz=224 verwenden
Vorhersagen
from ultralytics import YOLO

# Das exportierte CoreML-Modell laden (macOS)
model = YOLO("yolo26n.mlpackage")

# Inferenz ausführen
results = model("https://ultralytics.com/images/bus.jpg")
Validieren
from ultralytics import YOLO

# Das exportierte CoreML-Modell laden (macOS)
model = YOLO("yolo26n.mlpackage")

# Die Genauigkeit anhand des COCO8-Datensatzes validieren
metrics = model.val(data="coco8.yaml")

Exportargumente#

ArgumentTypStandardBeschreibung
formatstr'coreml'Zielformat des exportierten Modells, das die Kompatibilität mit verschiedenen Bereitstellungsumgebungen festlegt.
imgszint oder tuple640Gewünschte Bildgröße für die Modelleingabe. Kann eine Ganzzahl für quadratische Bilder oder ein Tupel (height, width) für bestimmte Abmessungen sein.
quantizeint oder strNoneQuantisierungsgenauigkeit: 16 (FP16), 8 oder "w8a16" (identisch: mit 8-Bit-k-means palettierte Gewichte und FP16-Berechnung) oder 32 bzw. keine Angabe (FP32). NMS-ML-Programme verwenden FP16 (für die Xcode-Vorschau und erforderlich für Segmentierung und Posenschätzung); bei Erkennung kannst du mit 32 einen anderen Wert festlegen. Ersetzt die veralteten Flags half/int8.
nmsbool, optionalNoneWähle rohe Ausgaben (None, Standard), eingebettetes NMS (True) oder den NMS-freien Kopf (False). Eingebettetes NMS unterstützt detect, segment und pose mit dynamic=False.
dynamicboolFalseErmöglicht dynamische Eingabegrößen. Für Klassifizierungs- oder RT-DETR-Modelle nicht unterstützt und nicht mit nms=True kombinierbar.
batchint1Legt die Batchgröße für die Inferenz des exportierten Modells oder die Höchstzahl der Bilder fest, die das exportierte Modell gleichzeitig im Modus predict verarbeitet. Für Werte über 1 ist dynamic=True erforderlich.
devicestrNoneLegt das Exportgerät fest: GPU (device=0), CPU (device=cpu), MPS für Apple Silicon (device=mps).

Weitere Informationen zum Exportvorgang findest du auf der Ultralytics-Dokumentationsseite zum Export.

Die Neural Engine als Ziel auswählen#

CoreML wählt die Hardware über MLModelConfiguration.computeUnits aus. Das Ultralytics-iOS-SDK verwendet unter iOS 16 und höher standardmäßig .cpuAndNeuralEngine statt .all: In einer Echtzeit-Kamera-App ist die GPU bereits mit der Darstellung der Vorschau und der Overlays beschäftigt. Wenn sie ausgeschlossen wird, lassen sich Ressourcenkonflikte und Schwankungen der Bilddauer vermeiden, während die ANE die rechenintensiven Aufgaben übernimmt. Lege .cpuOnly nur für Kompatibilitätstests fest – die Tabelle oben zeigt die Leistungseinbußen.

Die Ausführung eines CoreML-Modells mit Python auf einem Mac-Host (über Ultralytics oder coremltools) folgt derselben Regel: Ultralytics lädt das Modell mit ComputeUnit.CPU_AND_NE (macOS 13+, bei älteren macOS-Versionen wird auf CPU_ONLY zurückgegriffen), sodass die Inferenz auf der Neural Engine bleibt (~3× schneller als auf der CPU). So wird außerdem eine aktuelle Einschränkung von macOS-Hosts umgangen: Die standardmäßigen Optionen ComputeUnit.ALL / CPU_AND_GPU – die den GPU-/MPSGraph-Kompilierungspfad hinzufügen – brechen den Prozess ab, und zwar mit einer Error: MLIR pass manager failed-Assertion unter coremltools 9.x. RT-DETR-Modelle sind die Ausnahme: Sie werden mit ComputeUnit.ALL geladen, da ihre FP16-Genauigkeit allein auf der Neural Engine abnimmt.

Exportierte YOLO26-CoreML-Modelle bereitstellen#

Am schnellsten geht es mit dem offiziellen Ultralytics-YOLO-iOS-SDK, demselben Swift-Paket, das die Ultralytics-iOS-App und das Flutter-Plugin verwenden. Es erkennt offizielle Modellnamen automatisch, lädt das .mlpackage herunter, speichert es im Cache und gibt vollständig dekodierte Ergebnisse zurück:

import UltralyticsYOLO

// Loads the official INT8 model (downloaded and cached on first use), then runs inference
let yolo = YOLO("yolo26n", task: .detect) { result in
    if case .success(let model) = result {
        let results = model(uiImage)  // boxes, labels, confidences, timing
    }
}

Für Kamera-Apps kannst du YOLOView des SDKs für Echtzeitinferenz mit nativen Overlays einbinden oder das Flutter-Plugin für plattformübergreifende Apps verwenden, die sich eine Codebasis mit Android teilen.

Auch die direkte Integration eines nicht weiter verarbeiteten .mlpackage ist mit Apples Technologie-Stack unkompliziert: Lade es mit MLModel, binde es in ein VNCoreMLRequest ein und übergib Bilder über VNImageRequestHandler. Weitere Informationen findest du in diesen Ressourcen:

Binde das Modell entweder direkt in das App-Paket ein (sofort verfügbar, ideal für Nano-/Small-Modelle) oder lade es beim ersten Start herunter und speichere es im Cache (kleinere Binärdatei, einfache Modellaktualisierungen). Die offiziellen Apps kombinieren beide Ansätze: Standardmäßige Nano-Modelle sind sofort einsatzbereit in der App enthalten, während größere Varianten bei Bedarf heruntergeladen und lokal zwischengespeichert werden.

  1. Trainiere dein Modell mit dem Train-Modus von Ultralytics oder verwende die offiziellen YOLO26-Gewichte als Ausgangspunkt.
  2. Exportiere mit model.export(format="coreml", quantize=8, imgsz=640) unter macOS oder Linux auf x86 (imgsz=224 für die Klassifizierung)
  3. Überprüfe die Genauigkeit mit model.val() auf einem Mac und erstelle mit einem Core-ML-Leistungsbericht in Xcode ein Profil auf deinem Zielgerät
  4. Stelle das Modell mit dem iOS-SDK, dem Flutter-Plugin oder deiner eigenen Vision-Integration für .cpuAndNeuralEngine bereit

Zusammenfassung#

In dieser Anleitung hast du gelernt, Ultralytics-YOLO26-Modelle in das .mlpackage-Format von CoreML zu exportieren, sie für die Apple Neural Engine zu quantisieren und mit Latenzen im einstelligen Millisekundenbereich einzusetzen – entweder über das offizielle iOS SDK und das Flutter-Plugin oder deine eigene Vision-Integration.

Häufig gestellte Fragen#

  • Führe model.export(format="coreml", imgsz=640) in Python oder yolo export model=yolo26n.pt format=coreml imgsz=640 über die CLI unter macOS oder Linux auf x86 aus. Verwende imgsz=224 für die Klassifizierung und füge quantize=8 hinzu, um die offiziellen App-Modelle nachzubilden. Beim Export entsteht ein yolo26n.mlpackage-ML-Program, das für Xcode, das iOS-SDK oder das Flutter-Plugin bereit ist.

  • Verwende nms=True, wenn deine App Erkennungen mit eingebettetem NMS benötigt. Beim standardmäßigen Export nms=None erhält deine App rohe One-to-many-Ausgaben zur Verarbeitung; mit nms=False wird der NMS-freie Kopf von YOLO26 ausgewählt. Eingebettetes NMS unterstützt detect, segment und pose mit statischen Formen; andere Aufgaben behalten ihre nativen Ausgaben.

  • Die offiziellen Ultralytics-App-Modelle werden als INT8 ausgeliefert. Das minimiert die Downloadgröße und ermöglicht die oben angegebenen Geschwindigkeiten. quantize=16 (FP16) ist eine konservative Alternative, die praktisch keinen Genauigkeitsverlust verursacht. Validiere deinen konkreten Export vor der Bereitstellung mit model.val() auf einem Mac.

  • Lege MLModelConfiguration.computeUnits = .cpuAndNeuralEngine fest (Standardeinstellung des iOS-SDKs unter iOS 16 und höher). Vermeide .all in Kamera-Apps – die GPU ist mit der Darstellung der Vorschau beschäftigt, und Inferenz auf der GPU führt zu Schwankungen der Bilddauer. Prüfe die Zuweisung mit einem Core-ML-Leistungsbericht in Xcode.

  • Ja, unter macOS funktionieren yolo predict model=yolo26n.mlpackage source=image.jpg und yolo val model=yolo26n.mlpackage data=coco8.yaml wie bei jedem anderen Format. Für die CoreML-Ausführung ist Apple-Hardware erforderlich, daher sind diese Modi unter Linux und Windows nicht verfügbar.

  • Verwende das offizielle Ultralytics-YOLO-iOS-SDK (Swift Package) oder das Flutter-Plugin. Beide laden offizielle Modelle anhand ihres Namens automatisch herunter und speichern sie im Cache, führen sie auf der Neural Engine aus und bieten vollständige Benutzeroberflächen für Echtzeitkameras – die Tabelle mit den Messwerten oben wurde genau mit diesem Technologie-Stack erstellt.

Kommentare13

Stell eine Frage, teile deine Ergebnisse oder hilf jemand anderem.

  1. Afool4UAfool4UGitHub

    Hello! I have trouble when I tried to export yolo11n.pt to coreml model with tracking. for example, the exist tracking method is like this:

    # use YOLO tracking
    results = yolo_model.track(frame, persist=True, verbose=False)

    And I've export pt format and reloaded the new coreml format model like this:

    model.export(format='coreml', nms=True, half=False)
    model = ct.models.MLModel('yolo11n.mlpackage')

    But when I tried to make a tracking on my camera stream, it seems that object 'model' have no attribute named 'track'. So how could I use tracking by a coreml format model? It's very important to me because the coreml model works well on my macbook.

  2. SebastianxhjSebastianxhjGitHub

    I used the example python code you guys gave. Why does output output confidence and coordination after converting my target detection model to mlpackage format. is it normal to not return processed images? Or is there something wrong with my export process.

    1. Glenn JocherGlenn JocherUltralytics

      @taeja7 the CoreML export returns raw detection outputs (confidence, coordinates) rather than processed images by design. This is normal behavior, as post-processing like bounding box rendering is typically handled within the application layer after inference. For implementation guidance, see the CoreML deployment documentation on handling model outputs in Apple apps.

  3. smadsenjcsmadsenjcGitHub

    I have a trained model that is doing very well in Python, but once I convert it to CoreML .mlpackage format and run inference in Swift, the results are garbage on the same images.

    If I export with nms=True, I get multiple overlapping bounding boxes back, similar-ish to when no NMS is done. The number of clusters matches the objects I expect, and they're kind of relatively positioned correctly, although the boxes themselves are too large and clustered in the wrong location. The predicted labels are right.

    If I export with nms=False, I get a different result back from VNCoreMLRequest: a single VNCoreMLFeatureValueObservation instead of an array of VNRecognizedObjectObservation.

    I've used both coremltools 8.0 and 8.2. If I run inference in Python using the CoreML model, it's fine (with nms=False; True fails).

    This was working back in November, but I got side-tracked with other work. I haven't touched the model.

    1. Glenn JocherGlenn JocherUltralytics

      @smadsenjc for CoreML inference discrepancies between Python and Swift, ensure you're handling NMS parameters correctly in your Swift implementation. The CoreML export with nms=True requires explicit IOU and confidence threshold inputs during inference - these must match your Python training parameters. We recommend verifying your Swift preprocessing matches Ultralytics' RGB channel ordering and normalization (scale=1/255, bias=[0,0,0]). For direct assistance with Apple's Vision framework implementation, refer to Apple's CoreML integration guide linked in our documentation.

  4. CharanPrasadKCharanPrasadKGitHub

    When I am Converting the Yolo .pt model to coreml model , mlpackage is creating and when I am checking it in the xcode the class labels are missing. For the core ml models in ultralytics github page class labels are there. If its solved i can test my custom yolo models. Thank you.

    1. Glenn JocherGlenn JocherUltralytics(bearbeitet)

      @CharanPrasadK it seems the class labels are not being included in your CoreML export. Ensure that your model is correctly labeled during training and export by checking the names attribute in the model. If the issue persists, please verify that you're using the latest ultralytics package. For further details, refer to the CoreML export documentation. Let us know if you need additional assistance!

  5. ChristalZhuChristalZhuGitHub

    Still the same problem, this is the result of running in the terminal: PyTorch: starting from '/Users/doublepeng/Desktop/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) ((1, 37, 8400), (1, 32, 160, 160)) (6.5 MB)

    CoreML: starting export with coremltools 7.2... CoreML: WARNING ⚠️ 'nms=True' is only available for Detect models like 'yolov8n.pt'. Tuple detected at graph output. This will be flattened in the converted model. Converting PyTorch Frontend ==> MIL Ops: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▌| 679/681 [00:00<00:00, 8273.25 ops/s] Running MIL frontend_pytorch pipeline: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00<00:00, 157.94 passes/s] Running MIL default pipeline: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 78/78 [00:00<00:00, 82.56 passes/s] Running MIL backend_mlprogram pipeline: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 12/12 [00:00<00:00, 160.71 passes/s] CoreML: export success ✅ 7.7s, saved as '/Users/doublepeng/Desktop/best.mlpackage' (6.4 MB)

    Export complete (8.1s) Results saved to /Users/doublepeng/Desktop Predict: yolo predict task=segment model=/Users/doublepeng/Desktop/best.mlpackage imgsz=640 Validate: yolo val task=segment model=/Users/doublepeng/Desktop/best.mlpackage imgsz=640 data=/home/yujialin/Documents/xiaotong/corn/data/corn.yaml Visualize: https://netron.app In the run mlpackage file, the class label is still missing in General, and there is no preview. Since I am only doing corn segmentation, if possible, can I send you my .pt file?

    1. Glenn JocherGlenn JocherUltralytics

      @ChristalZhu hello,

      Thank you for providing the detailed output from your terminal. It looks like the CoreML export process completed successfully, but you're experiencing issues with missing class labels and preview in the .mlpackage file.

      To assist you better, could you please confirm the following:

      1. Are you using the latest versions of torch and ultralytics? If not, please upgrade and try the export process again.
      2. Could you provide a minimum reproducible example of your code? This will help us understand the context and reproduce the issue on our end. You can refer to our minimum reproducible example guide for more details.

      Regarding your .pt file, we cannot accept direct file submissions. However, you can share the relevant code snippets and configurations you used for training and exporting the model.

      Here's a quick example of how to export a YOLOv8 model to CoreML and run inference:

      from ultralytics import YOLO
      
      # Load the YOLOv8 model
      model = YOLO("yolov8n.pt")
      
      # Export the model to CoreML format
      model.export(format="coreml")  # creates 'yolov8n.mlpackage'
      
      # Load the exported CoreML model
      coreml_model = YOLO("yolov8n.mlpackage")
      
      # Run inference
      results = coreml_model("https://ultralytics.com/images/bus.jpg")

      For more detailed instructions, you can visit our CoreML integration guide.

      Looking forward to your response so we can help resolve this issue.

  6. ChristalZhuChristalZhuGitHub

    我按照https://harshavardhanyellanki.github.io/YOLOV8_GUI/tasks/segmentation/的方法,将我自己训练的分割模型进行导出成mlpackage,但是出现了问题就是打开这个mlpackage之后,缺少class label文件和缺少了preview,请问这个有什么办法解决,如果可以的话,麻烦发送到我的email账号:wenpeng.zhu@foxmail.com万分感谢。 I followed the method at https://harshavardhanyellanki.github.io/YOLOV8_GUI/tasks/segmentation/ to export the segmentation model I trained myself into mlpackage, but the problem is that after opening this mlpackage, the class label file and the preview are missing. Is there any way to solve this problem? If possible, please send it to my email account: wenpeng.zhu@foxmail.com. Thank you very much.

    1. Paula DerrengerPaula DerrengerUltralytics

      Hello @ChristalZhu,

      Thank you for reaching out and providing details about the issue you're facing with exporting your YOLOv8 segmentation model to CoreML. Let's work together to resolve this.

      Firstly, please ensure that you are using the latest versions of torch and ultralytics. You can update them using the following commands:

      pip install --upgrade torch ultralytics

      If the issue persists, could you please provide a minimum reproducible code example? This will help us better understand the problem and investigate a solution. You can refer to our guide on creating a minimum reproducible example here: Minimum Reproducible Example.

      Regarding the missing class label file and preview in the .mlpackage, this can sometimes occur if the export process does not include all necessary metadata. Here is a Python example to ensure the export includes all required components:

      from ultralytics import YOLO
      
      # Load your trained YOLOv8 model
      model = YOLO("path/to/your/custom_model.pt")
      
      # Export the model to CoreML format
      model.export(format="coreml", nms=True)  # Ensure NMS is included for proper detection

      After exporting, you can manually check the .mlpackage to ensure it contains the necessary class labels and preview files. If they are still missing, please let us know, and we can further investigate.

      For more detailed instructions on exporting to CoreML, you can visit our documentation here: CoreML Export Guide.

      Feel free to share any additional details or errors you encounter. We're here to help!

    2. ChristalZhuChristalZhuGitHub

      Still the same problem, this is the result of running in the terminal: PyTorch: starting from '/Users/doublepeng/Desktop/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) ((1, 37, 8400), (1, 32, 160, 160)) (6.5 MB)

      CoreML: starting export with coremltools 7.2... CoreML: WARNING ⚠️ 'nms=True' is only available for Detect models like 'yolov8n.pt'. Tuple detected at graph output. This will be flattened in the converted model. Converting PyTorch Frontend ==> MIL Ops: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▌| 679/681 [00:00<00:00, 8273.25 ops/s] Running MIL frontend_pytorch pipeline: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00<00:00, 157.94 passes/s] Running MIL default pipeline: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 78/78 [00:00<00:00, 82.56 passes/s] Running MIL backend_mlprogram pipeline: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 12/12 [00:00<00:00, 160.71 passes/s] CoreML: export success ✅ 7.7s, saved as '/Users/doublepeng/Desktop/best.mlpackage' (6.4 MB)

      Export complete (8.1s) Results saved to /Users/doublepeng/Desktop Predict: yolo predict task=segment model=/Users/doublepeng/Desktop/best.mlpackage imgsz=640
      Validate: yolo val task=segment model=/Users/doublepeng/Desktop/best.mlpackage imgsz=640 data=/home/yujialin/Documents/xiaotong/corn/data/corn.yaml
      Visualize: https://netron.app In the run mlpackage file, the class label is still missing in General, and there is no preview. Since I am only doing corn segmentation, if possible, can I send you my .pt file?

    3. Paula DerrengerPaula DerrengerUltralytics

      Hello @ChristalZhu,

      Thank you for providing the detailed output from your terminal. It looks like the CoreML export process completed successfully, but you're encountering issues with missing class labels and preview in the .mlpackage.

      To address this, please ensure you are using the latest versions of torch and ultralytics. You can update them using the following commands:

      pip install --upgrade torch ultralytics

      If the issue persists, could you please provide a minimum reproducible code example? This will help us better understand the problem and investigate a solution. You can refer to our guide on creating a minimum reproducible example here: Minimum Reproducible Example.

      Regarding the missing class label file and preview in the .mlpackage, this can sometimes occur if the export process does not include all necessary metadata. Here is a Python example to ensure the export includes all required components:

      from ultralytics import YOLO
      
      # Load your trained YOLOv8 model
      model = YOLO("path/to/your/custom_model.pt")
      
      # Export the model to CoreML format
      model.export(format="coreml", nms=True)  # Ensure NMS is included for proper detection

      After exporting, you can manually check the .mlpackage to ensure it contains the necessary class labels and preview files. If they are still missing, please let us know, and we can further investigate.

      For more detailed instructions on exporting to CoreML, you can visit our documentation here: CoreML Export Guide.

      Feel free to share any additional details or errors you encounter. We're here to help! 😊