Repository: ultralytics/ultralytics

Issue:
custom model yaml load overriding the customer provided name.
### Search before asking

- [X] I have searched the YOLOv8 [issues](https://github.com/ultralytics/ultralytics/issues) and found no similar bug report.


### YOLOv8 Component

Other

### Bug

version: Ultralytics YOLOv8.1.34 🚀 Python-3.10.13 torch-2.1.2+cpu CPU (Intel Xeon 2.20GHz)
Reproduction code snippet. can rename yolov8n.yaml file to the name below
```
import os
datasetpath='/kaggle/working/datasets/spaceship.yaml'
mdlyaml = '/kaggle/working/yolov8n-smallship.yaml'
lastGoldWts = '/kaggle/input/custom_n640/pytorch/march16/1/custom_n640_1_best.pt'
print(f"result of fileExists {os.path.exists(mdlyaml)}")
model = YOLO(mdlyaml).load(lastGoldWts)
```

Input is  '/kaggle/working/yolov8n-smallship.yaml'  but the YOLO is looking for '/kaggle/working/yolov8-smallship.yaml'
Why is user input overwritten and 'n' removed before '-' in the model configuration file when trying to load?
Seems like some bad assumptions in model names for load.
Same code used to work before , breaking with the current version shown above.

> result of fileExists True
> 
> FileNotFoundError                         Traceback (most recent call last)
> Cell In[41], line 6
>       4 lastGoldWts = '/kaggle/input/custom_n640/pytorch/march16/1/custom_n640_1_best.pt'
>       5 print(f"result of fileExists {os.path.exists(mdlyaml)}")
> ----> 6 model = YOLO(mdlyaml).load(lastGoldWts)
> 
> File /opt/conda/lib/python3.10/site-packages/ultralytics/models/yolo/model.py:23, in YOLO.__init__(self, model, task, verbose)
>      20     self.__dict__ = new_instance.__dict__
>      21 else:
>      22     # Continue with default YOLO initialization
> ---> 23     super().__init__(model=model, task=task, verbose=verbose)
> 
> File /opt/conda/lib/python3.10/site-packages/ultralytics/engine/model.py:139, in Model.__init__(self, model, task, verbose)
>     137 # Load or create new YOLO model
>     138 if Path(model).suffix in (".yaml", ".yml"):
> --> 139     self._new(model, task=task, verbose=verbose)
>     140 else:
>     141     self._load(model, task=task)
> 
> File /opt/conda/lib/python3.10/site-packages/ultralytics/engine/model.py:205, in Model._new(self, cfg, task, model, verbose)
>     195 def _new(self, cfg: str, task=None, model=None, verbose=False) -> None:
>     196     """
>     197     Initializes a new model and infers the task type from the model definitions.
>     198 
>    (...)
>     203         verbose (bool): display model info on load
>     204     """
> --> 205     cfg_dict = yaml_model_load(cfg)
>     206     self.cfg = cfg
>     207     self.task = task or guess_model_task(cfg_dict)
> 
> File /opt/conda/lib/python3.10/site-packages/ultralytics/nn/tasks.py:941, in yaml_model_load(path)
>     939 unified_path = re.sub(r"(\d+)([nslmx])(.+)?$", r"\1\3", str(path))  # i.e. yolov8x.yaml -> yolov8.yaml
>     940 yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)
> --> 941 d = yaml_load(yaml_file)  # model dict
>     942 d["scale"] = guess_model_scale(path)
>     943 d["yaml_file"] = str(path)
> 
> File /opt/conda/lib/python3.10/site-packages/ultralytics/utils/__init__.py:362, in yaml_load(file, append_filename)
>     351 """
>     352 Load YAML data from a file.
>     353 
>    (...)
>     359     (dict): YAML data and file name.
>     360 """
>     361 assert Path(file).suffix in (".yaml", ".yml"), f"Attempting to load non-YAML file {file} with yaml_load()"
> --> 362 with open(file, errors="ignore", encoding="utf-8") as f:
>     363     s = f.read()  # string
>     365     # Remove special characters
> 
> FileNotFoundError: [Errno 2] No such file or directory: '/kaggle/working/yolov8-smallship.yaml'

### Environment

_No response_

### Minimal Reproducible Example

_No response_

### Additional

_No response_

### Are you willing to submit a PR?

- [ ] Yes I'd like to help by submitting a PR!


Discussion:
👋 Hello @parajav, thank you for your interest in Ultralytics YOLOv8 🚀! We recommend a visit to the [Docs](https://docs.ultralytics.com) for new users where you can find many [Python](https://docs.ultralytics.com/usage/python/) and [CLI](https://docs.ultralytics.com/usage/cli/) usage examples and where many of the most common questions may already be answered.

If this is a 🐛 Bug Report, please provide a [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/) to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our [Tips for Best Training Results](https://docs.ultralytics.com/yolov5/tutorials/tips_for_best_training_results/).

Join the vibrant [Ultralytics Discord](https://ultralytics.com/discord) 🎧 community for real-time conversations and collaborations. This platform offers a perfect space to inquire, showcase your work, and connect with fellow Ultralytics users.

## Install

Pip install the `ultralytics` package including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml) in a [**Python>=3.8**](https://www.python.org/) environment with [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/).

```bash
pip install ultralytics
```

## Environments

YOLOv8 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):

- **Notebooks** with free GPU: <a href="https://console.paperspace.com/github/ultralytics/ultralytics"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"/></a> <a href="https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <a href="https://www.kaggle.com/ultralytics/yolov8"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)
- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)
- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href="https://hub.docker.com/r/ultralytics/ultralytics"><img src="https://img.shields.io/docker/pulls/ultralytics/ultralytics?logo=docker" alt="Docker Pulls"></a>

## Status

<a href="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule"><img src="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml/badge.svg" alt="Ultralytics CI"></a>

If this badge is green, all [Ultralytics CI](https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule) tests are currently passing. CI tests verify correct operation of all YOLOv8 [Modes](https://docs.ultralytics.com/modes/) and [Tasks](https://docs.ultralytics.com/tasks/) on macOS, Windows, and Ubuntu every 24 hours and on every commit.
@parajav hey there! 🚀 It looks like there might be an issue with the filename parsing leading to the removal of 'n' from your custom model name. This behavior seems unintended, and we appreciate you bringing it to our attention. 

As a temporary workaround, could you try renaming your YAML file to match the expected pattern (without the 'n' before '-') and see if that resolves the issue? Meanwhile, we'll look into why this specific naming convention impacts the loading process.

```python
# Rename yolov8n-smallship.yaml to yolov8-smallship.yaml
mdlyaml = '/kaggle/working/yolov8-smallship.yaml'
# Then load as usual
model = YOLO(mdlyaml).load(lastGoldWts)
```

Thanks for sharing this with us, and sorry for any inconvenience this might have caused.

Resolving patch:
diff --git a/ultralytics/utils/checks.py b/ultralytics/utils/checks.py
--- a/ultralytics/utils/checks.py
+++ b/ultralytics/utils/checks.py
@@ -500,7 +500,7 @@ def check_file(file, suffix="", download=True, hard=True):
             raise FileNotFoundError(f"'{file}' does not exist")
         elif len(files) > 1 and hard:
             raise FileNotFoundError(f"Multiple files match '{file}', specify exact path: {files}")
-        return files[0] if len(files) else [] if hard else file  # return file
+        return files[0] if len(files) else []  # return file
 
 
 def check_yaml(file, suffix=(".yaml", ".yml"), hard=True):


Test patch: