diff --git a/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py b/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
index 0dcd8539a..212157549 100644
--- a/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
+++ b/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
@@ -1271,6 +1271,7 @@ def package_python_app(self):
         assert self.options
         assert self.get_pyproject
         assert self.python_app_path
+        assert self.package_app_path
         assert self.build_dir
         assert self.flutter_dir

@@ -1282,7 +1283,7 @@ def package_python_app(self):
             "run",
             "serious_python:main",
             "package",
-            str(self.python_app_path),
+            str(self.package_app_path),
             "--platform",
             self.package_platform,
         ]

`flet build` creates bundle but running it gives `ImportError: No module named main` error
### Duplicate Check

- [X] I have searched the [opened issues](https://github.com/flet-dev/flet/issues) and there are no duplicates

### Describe the bug

Traceback (most recent call last):
  File "<string>", line 47, in <module>
  File "<frozen runpy>", line 222, in run_module
  File "<frozen runpy>", line 142, in _get_module_details
ImportError: No module named main

### Code sample

Code

```python
print(error)
```

### To reproduce

...

### Expected behavior

_No response_

### Screenshots / Videos

Captures

![Screenshot_2024-11-28-23-36-20-36_92b64b2a7aa6eb3771ed6e18d0029815](https://github.com/user-attachments/assets/e22fcd4a-eaa1-448f-8c61-51164c6cbae7)

### Operating System

Windows

### Operating system details

11

### Flet version

0.25

### Regression

No, it isn't

### Suggestions

_No response_

### Logs

Logs

```console
[Paste your logs here]
```

### Additional details

_No response_

What do you have in pyproject.toml and what is the file structure of your project?

### `pyproject.toml`

```toml
[project]
name = "weather-app"
version = "0.1.0"
description = ""
readme = "README.md"
requires-python = ">=3.8"
dependencies = [
  "flet"
]

[tool.flet]
# org name in reverse domain name notation, e.g. "com.mycompany".
# Combined with project.name to build bundle ID for iOS and Android apps
org = "com.mycompany"

# project display name that is used as an app title on Android and iOS home screens,
# shown in window titles and about app dialogs on desktop.
product = "Weather Forcast"

# company name to display in about app dialogs
company = "Flet"

# copyright text to display in about app dialogs
copyright = "Copyright (C) 2024 by Flet"

[tool.flet.app]
path = "src"
```
### `Structure`
```
W:\dev-mobile\dev mobile (flet)\api-app\weather-app>flet build apk
[09:17:25] Created Flutter bootstrap project from gh:flet-dev/flet-build-template with ref 0.25.0 ✅
           Customized app icons and splash images ✅
[09:18:41] Generated app icons ✅
[09:18:51] Generated splash screens ✅
[09:21:48] Packaged Python app ✅
[09:30:39] Built .apk for Android ✅
           Copied build to build\apk directory ✅
           Successfully built your .apk for Android! 🥳 Find it in build\apk directory. 📁
```

![Screenshot 2024-11-29 091419](https://github.com/user-attachments/assets/784e36c1-4450-4269-b8f7-a42cf28c11b4)

![Screenshot 2024-11-29 091455](https://github.com/user-attachments/assets/3bcecb4c-51b6-4b33-a2f6-7259916c2477)
![Screenshot 2024-11-29 091512](https://github.com/user-attachments/assets/332c1a6d-4b46-484f-974f-ea914158c952)

I'm having the same problem.
I created a basic project and built it right away, and it runs fine with flet run, but I get an error after building.

win11, 0.25.0

Commands used
```
mkdir flet-test
cd flet-test
flet create .
flet run
flet build windows -vv
cd flet build/windows
flet-test.exe
```

Error Description
```
Traceback (most recent call last):
  File "<string>", line 47, in <module>
  File "<frozen runpy>", line 222, in run_module
  File "<frozen runpy>", line 142, in _get_module_details
ImportError: No module named main
```

I filmed a video of the process.

https://github.com/user-attachments/assets/c6033991-4dbb-4967-9206-2f8833cd2640

The terminal log is here.
[ps-log.txt](https://github.com/user-attachments/files/17961394/ps-log.txt)

Also, apps written with existing FLETs are experiencing the same error after updating from 0.24.1 to 0.25.0.
Thanks for the additional details. I'm on it.


diff --git a/sdk/python/packages/flet/src/flet/core/date_picker.py b/sdk/python/packages/flet/src/flet/core/date_picker.py
index 4abb8122d..09d735f86 100644
--- a/sdk/python/packages/flet/src/flet/core/date_picker.py
+++ b/sdk/python/packages/flet/src/flet/core/date_picker.py
@@ -173,24 +173,6 @@ def __init__(
     def _get_control_name(self):
         return "datepicker"

-    def before_update(self):
-        super().before_update()
-        assert (
-            self.__first_date is None
-            or self.__last_date is None
-            or self.__first_date <= self.__last_date
-        ), "last_date must be on or after first_date"
-        assert (
-            self.__first_date is None
-            or self.__current_date is None
-            or self.__first_date <= self.__current_date
-        ), "current_date must be on or after first_date"
-        assert (
-            self.__last_date is None
-            or self.__current_date is None
-            or self.__last_date >= self.__current_date
-        ), "last_date must be on or after current_date"
-
     @deprecated(
         reason="Use Page.open() method instead.",
         version="0.23.0",

Opening DatePicker returns AssertionError
### Duplicate Check

- [X] I have searched the [opened issues](https://github.com/flet-dev/flet/issues) and there are no duplicates

### Describe the bug

When running example from docs, clicking on Pick Date button, which opens DatePicker, returns an error:

Future exception was never retrieved
future: <Future finished exception=AssertionError('last_date must be on or after current_date')>
Traceback (most recent call last):
  File "/Users/inesa/.pyenv/versions/3.12.6/lib/python3.12/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/page.py", line 948, in wrapper
    handler(*args)
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/playground/date-picker-test.py", line 19, in <lambda>
    on_click=lambda e: page.open(
                       ^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/page.py", line 1429, in open
    self.__offstage.update()
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/control.py", line 324, in update
    self.__page.update(self)
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/page.py", line 723, in update
    r = self.__update(*controls)
        ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/page.py", line 835, in __update
    commands, added_controls, removed_controls = self.__prepare_update(*controls)
                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/page.py", line 851, in __prepare_update
    control.build_update_commands(
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/control.py", line 498, in build_update_commands
    innerCmds = ctrl._build_add_commands(
                ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/control.py", line 552, in _build_add_commands
    command = self._build_command(False)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/control.py", line 579, in _build_command
    self.before_update()
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/date_picker.py", line 189, in before_update
    self.__last_date is None

### Code sample

Code

```python
import datetime
import flet as ft

def main(page: ft.Page):
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    def handle_change(e):
        page.add(ft.Text(f"Date changed: {e.control.value.strftime('%Y-%m-%d')}"))

    def handle_dismissal(e):
        page.add(ft.Text(f"DatePicker dismissed"))

    page.add(
        ft.ElevatedButton(
            "Pick date",
            icon=ft.icons.CALENDAR_MONTH,
            on_click=lambda e: page.open(
                ft.DatePicker(
                    first_date=datetime.datetime(year=2023, month=10, day=1),
                    last_date=datetime.datetime(year=2024, month=10, day=1),
                    on_change=handle_change,
                    on_dismiss=handle_dismissal,
                )
            ),
        )
    )

ft.app(main)
```

### To reproduce

1. Run Code sample
2. Click on "Pick date" button -> see the error in output

### Expected behavior

expected to see the DatePicker

### Screenshots / Videos

Captures

[Upload media here]

### Operating System

macOS

### Operating system details

macOs

### Flet version

flet==0.25.0.dev3750

### Regression

Yes, it used to work in a previous Flet version (please specify the version in additional details)

### Suggestions

_No response_

### Logs

Logs

```console
[Paste your logs here]
```

### Additional details

_No response_


diff --git a/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py b/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
index a61657801..a097bb454 100644
--- a/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
+++ b/sdk/python/packages/flet-cli/src/flet_cli/commands/build.py
@@ -14,6 +14,12 @@
 from flet.utils import copy_tree, is_windows, slugify
 from flet.utils.platform_utils import get_bool_env_var
 from flet.version import update_version
+from packaging import version
+from rich.console import Console
+from rich.style import Style
+from rich.table import Column, Table
+from rich.theme import Theme
+
 from flet_cli.commands.base import BaseCommand
 from flet_cli.utils.merge import merge_dict
 from flet_cli.utils.project_dependencies import (
@@ -21,11 +27,6 @@
     get_project_dependencies,
 )
 from flet_cli.utils.pyproject_toml import load_pyproject_toml
-from packaging import version
-from rich.console import Console
-from rich.style import Style
-from rich.table import Column, Table
-from rich.theme import Theme

 if is_windows():
     from ctypes import windll
@@ -55,6 +56,8 @@ def __init__(self, parser: argparse.ArgumentParser) -> None:
         self.build_dir = None
         self.flutter_dir: Optional[Path] = None
         self.flutter_exe = None
+        self.skip_flutter_doctor = get_bool_env_var("FLET_CLI_SKIP_FLUTTER_DOCTOR")
+        self.no_rich_output = get_bool_env_var("FLET_CLI_NO_RICH_OUTPUT")
         self.current_platform = platform.system()
         self.platforms = {
             "windows": {
@@ -511,58 +514,65 @@ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
             default=False,
             help="disables rich output and uses plain text instead",
         )
+        parser.add_argument(
+            "--skip-flutter-doctor",
+            action="store_true",
+            default=False,
+            help="whether to skip running Flutter doctor in failed builds",
+        )

     def handle(self, options: argparse.Namespace) -> None:
-        self.verbose = options.verbose
-
-        # get `flutter` and `dart` executables from PATH
-        self.flutter_exe = self.find_flutter_batch("flutter")
-        self.dart_exe = self.find_flutter_batch("dart")
-
-        if self.verbose > 1:
-            console.log("Flutter executable:", self.flutter_exe)
-            console.log("Dart executable:", self.dart_exe)
-
-        self.no_rich_output = options.no_rich_output or get_bool_env_var(
-            "FLET_CLI_NO_RICH_OUTPUT"
-        )
-        self.emojis = {
-            "checkmark": "[green]OK[/]" if self.no_rich_output else "✅",
-            "loading": "" if self.no_rich_output else "⏳",
-            "success": "" if self.no_rich_output else "🥳",
-            "directory": "" if self.no_rich_output else "📁",
-        }
         target_platform = options.target_platform.lower()
-        # platform check
-        if (
-            self.current_platform
-            not in self.platforms[target_platform]["can_be_run_on"]
-            or options.show_platform_matrix
-        ):
-            can_build_message = (
-                "can't"
-                if self.current_platform
-                not in self.platforms[target_platform]["can_be_run_on"]
-                else "can"
-            )
-            # replace "Darwin" with "macOS" for user-friendliness
-            self.current_platform = (
-                "macOS" if self.current_platform == "Darwin" else self.current_platform
-            )
-            # highlight the current platform in the build matrix table
-            self.platform_matrix_table.rows[
-                list(self.platforms.keys()).index(target_platform)
-            ].style = "bold red1"
-            console.log(self.platform_matrix_table)
-
-            message = f"You {can_build_message} build [cyan]{target_platform}[/] on [magenta]{self.current_platform}[/]."
-            self.cleanup(1, message)
-
         with console.status(
             f"[bold blue]Initializing {target_platform} build... ",
             spinner="bouncingBall",
         ) as self.status:
-            from cookiecutter.main import cookiecutter
+            # get `flutter` and `dart` executables from PATH
+            self.flutter_exe = self.find_flutter_batch("flutter")
+            self.dart_exe = self.find_flutter_batch("dart")
+
+            self.verbose = options.verbose
+            if self.verbose > 1:
+                console.log("Flutter executable:", self.flutter_exe)
+                console.log("Dart executable:", self.dart_exe)
+
+            self.no_rich_output = self.no_rich_output or options.no_rich_output
+            self.skip_flutter_doctor = (
+                self.skip_flutter_doctor or options.skip_flutter_doctor
+            )
+            self.emojis = {
+                "checkmark": "[green]OK[/]" if self.no_rich_output else "✅",
+                "loading": "" if self.no_rich_output else "⏳",
+                "success": "" if self.no_rich_output else "🥳",
+                "directory": "" if self.no_rich_output else "📁",
+            }
+
+            # platform check
+            if (
+                self.current_platform
+                not in self.platforms[target_platform]["can_be_run_on"]
+                or options.show_platform_matrix
+            ):
+                can_build_message = (
+                    "can't"
+                    if self.current_platform
+                    not in self.platforms[target_platform]["can_be_run_on"]
+                    else "can"
+                )
+                # replace "Darwin" with "macOS" for user-friendliness
+                self.current_platform = (
+                    "macOS"
+                    if self.current_platform == "Darwin"
+                    else self.current_platform
+                )
+                # highlight the current platform in the build matrix table
+                self.platform_matrix_table.rows[
+                    list(self.platforms.keys()).index(target_platform)
+                ].style = "bold red1"
+                console.log(self.platform_matrix_table)
+
+                message = f"You {can_build_message} build [cyan]{target_platform}[/] on [magenta]{self.current_platform}[/]."
+                self.cleanup(1, message)

             package_platform = self.platforms[target_platform]["package_platform"]

@@ -874,6 +884,8 @@ def handle(self, options: argparse.Namespace) -> None:
                 f"[bold blue]Creating Flutter bootstrap project from {template_url} with ref {template_ref} {self.emojis['loading']}... ",
             )
             try:
+                from cookiecutter.main import cookiecutter
+
                 cookiecutter(
                     template=template_url,
                     checkout=template_ref,
@@ -1516,8 +1528,11 @@ def cleanup(
                             console.log(flutter_msg, style=error_style)

             # windows has been reported to raise encoding errors when running `flutter doctor`
-            # so skip running `flutter doctor` if no_rich_output is True and platform is Windows
-            if not (self.no_rich_output and self.current_platform == "Windows"):
+            # so skip running it if no_rich_output is True
+            if not (
+                (self.no_rich_output and self.current_platform == "Windows")
+                or self.skip_flutter_doctor
+            ):
                 self.run_flutter_doctor()

         sys.exit(exit_code)

Add an option to skip the running `flutter doctor` when `flet build` fails
### Discussed in https://github.com/flet-dev/flet/discussions/4359

Originally posted by **DFNJKD-98** November 13, 2024
### Question

Due to some reasons, my country cannot freely access GitHub, so Flutter Doctor always reports errors. This hinders me from using Fleet to build Windows applications. Can I skip the Flutter Doctor phase using the 'flex build windows' command? I'm not sure if this is necessary.

### Code sample

_No response_

### Error message

```bash
As shown below, the Flutter Doctor command may encounter some issues, but building a Windows application directly using Flutter is not a problem. I can use Flutter normally in VSCode.
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.22.1, on Microsoft Windows [version 1.0.19045.4046], local zh CN)
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Chrome - develop for the web
[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.7.3)
[!] Flutter IDE Support (No supported IDEs installed)
[√] Connected device (3 available)
[!] Network resources
X An HTTP error occurred while checking " https://github.com/ ": Connection closed before full header was received

! Doctor found issues in 2 categories.
```


diff --git a/sdk/python/packages/flet/src/flet/core/icon.py b/sdk/python/packages/flet/src/flet/core/icon.py
index 8944f28bf..5af67aa7b 100644
--- a/sdk/python/packages/flet/src/flet/core/icon.py
+++ b/sdk/python/packages/flet/src/flet/core/icon.py
@@ -130,6 +130,7 @@ def _get_control_name(self):
         return "icon"

     def before_update(self):
+        super().before_update()
         self._set_attr_json("shadows", self.__shadows)

     # name

Icon rotation doesn't work with flet-0.25.0.dev3711
### Duplicate Check

- [X] I have searched the [opened issues](https://github.com/flet-dev/flet/issues) and there are no duplicates

### Describe the bug

Icon rotation doesn't work anymore with flet 0.25
IconButton and other controls are OK

### Code sample

Code

flet 0.24.1 :
```python
import flet as ft
import math

def main(page: ft.Page):
    page.add(
        ft.Icon(
            name=ft.icons.FAVORITE,
        ),
        ft.Icon(
            name=ft.icons.FAVORITE,
            size=60,
            rotate=ft.Rotate(0.5*math.pi)
        ),
    )

ft.app(target=main)
```

flet-0.25.0.dev3711 :
```python
import flet as ft
import math

def main(page: ft.Page):
    page.add(
        ft.Icon(
            name=ft.Icons.FAVORITE,
        ),
        ft.Icon(
            name=ft.Icons.FAVORITE,
            size=60,
            rotate=ft.Rotate(0.5*math.pi)
        ),
    )

ft.app(target=main)
```

### To reproduce

Nothing particular :
With the same code, icon is rotated with flet 0.24.1 and lower, not rotated with 0.25

### Expected behavior

Icon rotate..

### Screenshots / Videos

Captures

0.24.1 :
![image](https://github.com/user-attachments/assets/620d5cd8-c867-4cd7-8ecf-73837665cb68)

flet-0.25.0.dev3711
![image](https://github.com/user-attachments/assets/25a13b91-3de3-4831-86cf-06b201c28312)

### Operating System

Windows

### Operating system details

windows 11 24H2

### Flet version

flet-0.25.0.dev3711

### Regression

Yes, it used to work in a previous Flet version (please specify the version in additional details)

### Suggestions

_No response_

### Logs

Logs

```console
[Paste your logs here]
```

### Additional details

_No response_

There is a lot of issues we are facing after 0.24.1


diff --git a/sdk/python/packages/flet/src/flet/core/markdown.py b/sdk/python/packages/flet/src/flet/core/markdown.py
index 118e4e1c4..77a761c88 100644
--- a/sdk/python/packages/flet/src/flet/core/markdown.py
+++ b/sdk/python/packages/flet/src/flet/core/markdown.py
@@ -400,7 +400,12 @@ def before_update(self):
         self._set_attr_json("codeStyle", self.__code_style)
         self._set_attr_json("codeStyleSheet", self.__code_style_sheet)
         self._set_attr_json("mdStyleSheet", self.__md_style_sheet)
-        self._set_attr_json("codeTheme", self.__code_theme)
+        self._set_attr_json(
+            "codeTheme",
+            self.__code_theme.value
+            if isinstance(self.__code_theme, MarkdownCodeTheme)
+            else self.__code_theme,
+        )

     def _get_children(self):
         if self.__img_error_content is not None:
@@ -483,11 +488,13 @@ def md_style_sheet(self, value: Optional[MarkdownStyleSheet]):

     # code_theme
     @property
-    def code_theme(self) -> Optional[MarkdownCodeTheme]:
+    def code_theme(self) -> Optional[Union[MarkdownCodeTheme, MarkdownCustomCodeTheme]]:
         return self.__code_theme

     @code_theme.setter
-    def code_theme(self, value: Optional[MarkdownCodeTheme]):
+    def code_theme(
+        self, value: Optional[Union[MarkdownCodeTheme, MarkdownCustomCodeTheme]]
+    ):
         self.__code_theme = value

     # code_style

Regression in `Markdown.code_theme` when using `MarkdownCodeTheme` enum
A custom theme works great although the only issue I faced was setting `code_theme` with `ft.MarkdownCodeTheme.ATOM_ONE_DARK` or any other value but **only** using `ft.MarkdownTheme` class the error it throws is:

# Code
```python
import flet as ft

data = """
```python
class MyClass(object):
    def __init__(self):
        pass

    def greet(self):
        print("Hello World")
    ```
"""
def main(page: ft.Page):
    page.add(
        ft.Markdown(
            value=data,
            code_theme=ft.MarkdownCodeTheme.ATOM_ONE_DARK,
            extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
        )
    )
ft.app(main)
```
<details>
  <summary>Error</summary>

  ```bash
  (.venv) PS D:\CodingFolder\myCodingFilesPy\Flet\leraning> flet run .\theme\ --web
  http://127.0.0.1:54949
  D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\websockets\legacy\server.py:1185: DeprecationWarning: remove second argument of ws_handler
    warnings.warn("remove second argument of ws_handler", DeprecationWarning)
  Unhandled error processing page session 49apGh5JlJ9Wkk0V: Traceback (most recent call last):
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet_web\fastapi\flet_app.py", line 141, in __on_session_created
      await asyncio.get_running_loop().run_in_executor(
    File "C:\ProgramData\anaconda3\Lib\concurrent\futures\thread.py", line 58, in run
      result = self.fn(*self.args, **self.kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\theme\main.py", line 12, in main
      page.add(
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\page.py", line 737, in add
      r = self.__update(self)
          ^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\page.py", line 835, in __update
      commands, added_controls, removed_controls = self.__prepare_update(*controls)
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\page.py", line 851, in __prepare_update
      control.build_update_commands(
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 497, in build_update_commands
      innerCmds = ctrl._build_add_commands(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 562, in _build_add_commands
      childCmd = control._build_add_commands(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 551, in _build_add_commands
      command = self._build_command(False)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 578, in _build_command
      self.before_update()
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\markdown.py", line 403, in before_update
      self._set_attr_json("codeTheme", self.__code_theme)
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 189, in _set_attr_json
      nv = self._convert_attr_json(
           ^^^^^^^^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\control.py", line 197, in _convert_attr_json
      json.dumps(value, cls=EmbedJsonEncoder, separators=(",", ":"))
    File "C:\ProgramData\anaconda3\Lib\json\__init__.py", line 238, in dumps
      **kw).encode(obj)
            ^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\embed_json_encoder.py", line 59, in encode
      return super().encode(self._convert_enums(o))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\ProgramData\anaconda3\Lib\json\encoder.py", line 200, in encode
      chunks = self.iterencode(o, _one_shot=True)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\ProgramData\anaconda3\Lib\json\encoder.py", line 258, in iterencode
      return _iterencode(o, 0)
             ^^^^^^^^^^^^^^^^^
    File "D:\CodingFolder\myCodingFilesPy\Flet\leraning\.venv\Lib\site-packages\flet\core\embed_json_encoder.py", line 49, in default
      obj_as_dict = self._convert_enums(obj.__dict__)
                                        ^^^^^^^^^^^^
  AttributeError: 'mappingproxy' object has no attribute '__dict__'
  ```
</details>

 ![image](https://github.com/user-attachments/assets/79ad892b-aa1b-4e68-9570-108835a23f54)

### I think there's something wrong with `ft.MarkdownTheme` class because when I used `"atom-one-dark"` it worked. When I run the same code but with `flet` version, `0.24.1` it worked as expected. Kindly raise issue regarding this.

_Originally posted by @tanmay-bhatgare in https://github.com/flet-dev/flet/issues/4342#issuecomment-2476781933_


diff --git a/sdk/python/packages/flet/src/flet/core/colors.py b/sdk/python/packages/flet/src/flet/core/colors.py
index 0fb695878..66b4293e8 100644
--- a/sdk/python/packages/flet/src/flet/core/colors.py
+++ b/sdk/python/packages/flet/src/flet/core/colors.py
@@ -37,9 +37,12 @@

 import random
 from enum import Enum, EnumMeta
-from typing import Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Dict, List, Optional, Union
 from warnings import warn

+if TYPE_CHECKING:
+    from flet.core.types import ColorValue
+
 from flet.utils import deprecated

@@ -56,9 +59,16 @@ def __getattribute__(self, item):

 class colors(str, Enum, metaclass=ColorsDeprecated):
-    def with_opacity(self, opacity: Union[int, float]) -> str:
+    @staticmethod
+    @deprecated(
+        reason="Use Colors.with_opacity() method instead.",
+        version="0.25.0",
+        delete_version="0.28.0",
+    )
+    def with_opacity(opacity: Union[int, float], color: "ColorValue") -> str:
         assert 0 <= opacity <= 1, "opacity must be between 0 and 1"
-        return f"{self.value},{opacity}"
+        color_str = color.value if isinstance(color, Enum) else color
+        return f"{color_str},{opacity}"

     @staticmethod
     def random():
@@ -416,21 +426,11 @@ def random_color():

 class Colors(str, Enum):
-    def with_opacity(self, opacity: Union[int, float]) -> str:
-        """
-        Returns the color with the specified opacity.
-
-        Args:
-            opacity: The opacity value, which must be between 0 and 1.
-
-        Returns:
-            A string representing the color value with the specified opacity appended.
-
-        Raises:
-            AssertionError: If the opacity is not between 0 and 1 (inclusive).
-        """
+    @staticmethod
+    def with_opacity(opacity: Union[int, float], color: "ColorValue") -> str:
         assert 0 <= opacity <= 1, "opacity must be between 0 and 1"
-        return f"{self.value},{opacity}"
+        color_str = color.value if isinstance(color, Enum) else color
+        return f"{color_str},{opacity}"

     @staticmethod
     def random(

Using `ft.colors.with_opacity` returns exception, should be warning
### Duplicate Check

- [X] I have searched the [opened issues](https://github.com/flet-dev/flet/issues) and there are no duplicates

### Describe the bug

This code used to work before:
```
tooltip_bgcolor=ft.Colors.with_opacity(0.5, ft.Colors.GREY_300)
```
Now it returns exception:

ERROR:asyncio:Future exception was never retrieved
future: <Future finished exception=TypeError("'<=' not supported between instances of 'int' and 'Colors'")>
Traceback (most recent call last):
  File "/Users/inesa/.pyenv/versions/3.12.6/lib/python3.12/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/Library/Caches/pypoetry/virtualenvs/controls-gallery-WumZyC-d-py3.12/lib/python3.12/site-packages/flet/core/page.py", line 944, in wrapper
    handler(*args)
  File "/Users/inesa/projects/flet-dev/examples/python/apps/controls-gallery/main.py", line 36, in route_change
    gallery_view.display_control_examples(route_list[0], route_list[1])
  File "/Users/inesa/projects/flet-dev/examples/python/apps/controls-gallery/components/gallery_view.py", line 30, in display_control_examples
    self.examples_view.display(
  File "/Users/inesa/projects/flet-dev/examples/python/apps/controls-gallery/components/examples_view.py", line 55, in display
    content=example.example(),
            ^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/examples/python/apps/controls-gallery/examples/charts/barchart/01_barchart_1.py", line 87, in example
    tooltip_bgcolor=ft.colors.with_opacity(0.5, ft.Colors.GREY_300),
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/Library/Caches/pypoetry/virtualenvs/controls-gallery-WumZyC-d-py3.12/lib/python3.12/site-packages/flet/core/colors.py", line 60, in with_opacity
    assert 0 <= opacity <= 1, "opacity must be between 0 and 1"

### Code sample

Code

```python
import flet as ft

def main(page: ft.Page):
    chart = ft.BarChart(
        bar_groups=[
            ft.BarChartGroup(
                x=0,
                bar_rods=[
                    ft.BarChartRod(
                        from_y=0,
                        to_y=40,
                        width=40,
                        color=ft.colors.AMBER,
                        tooltip="Apple",
                        border_radius=0,
                    ),
                ],
            ),
            ft.BarChartGroup(
                x=1,
                bar_rods=[
                    ft.BarChartRod(
                        from_y=0,
                        to_y=100,
                        width=40,
                        color=ft.colors.BLUE,
                        tooltip="Blueberry",
                        border_radius=0,
                    ),
                ],
            ),
            ft.BarChartGroup(
                x=2,
                bar_rods=[
                    ft.BarChartRod(
                        from_y=0,
                        to_y=30,
                        width=40,
                        color=ft.colors.RED,
                        tooltip="Cherry",
                        border_radius=0,
                    ),
                ],
            ),
            ft.BarChartGroup(
                x=3,
                bar_rods=[
                    ft.BarChartRod(
                        from_y=0,
                        to_y=60,
                        width=40,
                        color=ft.colors.ORANGE,
                        tooltip="Orange",
                        border_radius=0,
                    ),
                ],
            ),
        ],
        border=ft.border.all(1, ft.colors.GREY_400),
        left_axis=ft.ChartAxis(
            labels_size=40, title=ft.Text("Fruit supply"), title_size=40
        ),
        bottom_axis=ft.ChartAxis(
            labels=[
                ft.ChartAxisLabel(
                    value=0, label=ft.Container(ft.Text("Apple"), padding=10)
                ),
                ft.ChartAxisLabel(
                    value=1, label=ft.Container(ft.Text("Blueberry"), padding=10)
                ),
                ft.ChartAxisLabel(
                    value=2, label=ft.Container(ft.Text("Cherry"), padding=10)
                ),
                ft.ChartAxisLabel(
                    value=3, label=ft.Container(ft.Text("Orange"), padding=10)
                ),
            ],
            labels_size=40,
        ),
        horizontal_grid_lines=ft.ChartGridLines(
            color=ft.colors.GREY_300, width=1, dash_pattern=[3, 3]
        ),
        tooltip_bgcolor=ft.colors.with_opacity(0.5, ft.colors.GREY_300),
        max_y=110,
        interactive=True,
        expand=True,
    )

    page.add(chart)

ft.app(main)
```

### To reproduce

Run the repro code -> BarChart is not displayed, error in in log:
Unhandled error processing page session : Traceback (most recent call last):
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/app.py", line 247, in on_session_created
    await asyncio.get_running_loop().run_in_executor(
  File "/Users/inesa/.pyenv/versions/3.12.6/lib/python3.12/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/playground/bar_chart_test.py", line 84, in main
    tooltip_bgcolor=ft.colors.with_opacity(0.5, ft.colors.GREY_300),
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/inesa/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/core/colors.py", line 60, in with_opacity
    assert 0 <= opacity <= 1, "opacity must be between 0 and 1"
           ^^^^^^^^^^^^^^^^^
TypeError: '<=' not supported between instances of 'int' and 'colors`

### Expected behavior

Expected to see a warning

### Screenshots / Videos

Captures

[Upload media here]

### Operating System

macOS

### Operating system details

15

### Flet version

0.25.0.dev3679

### Regression

Yes, it used to work in a previous Flet version (please specify the version in additional details)

### Suggestions

_No response_

### Logs

Logs

```console
[Paste your logs here]
```

### Additional details

_No response_


diff --git a/sdk/python/packages/flet/src/flet/core/segmented_button.py b/sdk/python/packages/flet/src/flet/core/segmented_button.py
index 01f303af6..7c1934834 100644
--- a/sdk/python/packages/flet/src/flet/core/segmented_button.py
+++ b/sdk/python/packages/flet/src/flet/core/segmented_button.py
@@ -203,12 +203,11 @@ def before_update(self):
         assert (
             len(self.selected) < 2 or self.allow_multiple_selection
         ), "allow_multiple_selection must be True for selected to have more than one item"
-        if self.__style is None:
-            self.__style = ButtonStyle()
-            self.__style.side = self._wrap_attr_dict(self.__style.side)
-            self.__style.shape = self._wrap_attr_dict(self.__style.shape)
-            self.__style.padding = self._wrap_attr_dict(self.__style.padding)
-        self._set_attr_json("style", self.__style)
+        style = self.__style or ButtonStyle()
+        style.side = self._wrap_attr_dict(style.side)
+        style.shape = self._wrap_attr_dict(style.shape)
+        style.padding = self._wrap_attr_dict(style.padding)
+        self._set_attr_json("style", style)

     def _get_children(self):
         for segment in self.segments:

user customized style for SegmentedButton not wrapped
### Duplicate Check

- [X] I have searched the [opened issues](https://github.com/flet-dev/flet/issues) and there are no duplicates

### Describe the bug

user cutomized style is not working in SegmentButton
![image](https://github.com/user-attachments/assets/7c5f6f9c-9c29-43b5-a4d4-87f52d0d420d)

### Code sample

Code

```python
import flet as ft

def main(page: ft.Page):
    page.window.width = 800
    page.window.height = 500
    page.window.alignment = ft.alignment.center

    def handle_change(e):
        print("on_change data : " + str(e.data))

    def on_error(e) -> None:
        print("error: ", e.data)

    page.on_error = on_error

    style = ft.ButtonStyle(shape=ft.RoundedRectangleBorder(radius=5))
    page.add(
        ft.SegmentedButton(
            on_change=handle_change,
            selected_icon=ft.Icon(ft.icons.ONETWOTHREE),
            selected={"1", "4"},
            allow_multiple_selection=True,
            style=style,
            segments=[
                ft.Segment(
                    value="1",
                    label=ft.Text("1"),
                    icon=ft.Icon(ft.icons.LOOKS_ONE),
                ),
                ft.Segment(
                    value="2",
                    label=ft.Text("2"),
                    icon=ft.Icon(ft.icons.LOOKS_TWO),
                ),
                ft.Segment(
                    value="3",
                    label=ft.Text("3"),
                    icon=ft.Icon(ft.icons.LOOKS_3),
                ),
                ft.Segment(
                    value="4",
                    label=ft.Text("4"),
                    icon=ft.Icon(ft.icons.LOOKS_4),
                ),
            ],
        )
    )

ft.app(main)

```

### To reproduce

pass customized style to SegmentedButton (style has customized attribute value, e.g. `style = ft.ButtonStyle(shape=ft.RoundedRectangleBorder(radius=5))`)

### Expected behavior

SegmentedButton has RoundedRectangleBorder

### Screenshots / Videos

Captures

[Upload media here]
![Code_2eBKOg7ESB](https://github.com/user-attachments/assets/e8389abd-23e6-4328-89b4-0ebbb9ac0200)

### Operating System

Windows

### Operating system details

Windows 11 24H2

### Flet version

0.24.1

### Regression

No, it isn't

### Suggestions

_No response_

### Logs

Logs

```console
[Paste your logs here]
```

### Additional details

_No response_


diff --git a/src/ragas/metrics/_noise_sensitivity.py b/src/ragas/metrics/_noise_sensitivity.py
index a6a903b68..4074d0edc 100644
--- a/src/ragas/metrics/_noise_sensitivity.py
+++ b/src/ragas/metrics/_noise_sensitivity.py
@@ -101,7 +101,6 @@ async def _decompose_answer_into_statements(
         sentences_with_index = {
             i: sentence
             for i, sentence in enumerate(sentences)
-            if sentence.strip().endswith(".")
         }

         statements_simplified = await self.statement_prompt.generate(

In NoiseSensitivity, the `.` should be deleted as the split condition.
[ ] I checked the [documentation](https://docs.ragas.io/) and related resources and couldn't find an answer to my question.

**Your Question**
After the sentence is split, i think the `.` should no longer be used as a split condition. Many other languages do not use `.` as a split condition. Just follow the result of `sentence_segmenter`.

**Code Examples**
https://github.com/explodinggradients/ragas/blob/main/src/ragas/metrics/_noise_sensitivity.py#L104C13-L104C46

**Additional context**
I will provide a pr.


diff --git a/sklearn/utils/estimator_checks.py b/sklearn/utils/estimator_checks.py
index f5d542d9a59fc..da1300817b148 100644
--- a/sklearn/utils/estimator_checks.py
+++ b/sklearn/utils/estimator_checks.py
@@ -2076,11 +2076,11 @@ def check_regressor_multioutput(name, estimator):

     assert y_pred.dtype == np.dtype("float64"), (
         "Multioutput predictions by a regressor are expected to be"
-        " floating-point precision. Got {} instead".format(y_pred.dtype)
+        f" floating-point precision. Got {y_pred.dtype} instead"
     )
     assert y_pred.shape == y.shape, (
         "The shape of the prediction for multioutput data is incorrect."
-        " Expected {}, got {}."
+        f" Expected {y_pred.shape}, got {y.shape}."
     )

Missing format string arguments
This assertion error string is not properly formatted as the 2 format arguments `y_pred.shape` and `y.shape` are missing:

https://github.com/scikit-learn/scikit-learn/blob/551d56c254197c4b6ad63974d749824ed2c7bc58/sklearn/utils/estimator_checks.py#L2139

```python
assert y_pred.shape == y.shape, (
    "The shape of the prediction for multioutput data is incorrect."
    " Expected {}, got {}."
)
```

should become

```python
assert y_pred.shape == y.shape, (
    "The shape of the prediction for multioutput data is incorrect."
    " Expected {}, got {}.".format(y_pred.shape, y.shape)
)
```

Please feel free to directly submit a PR with the fix in the future in such cases :)


diff --git a/src/lightning/pytorch/loops/prediction_loop.py b/src/lightning/pytorch/loops/prediction_loop.py
index 7044ccea87a7f..dcfd873a28b4b 100644
--- a/src/lightning/pytorch/loops/prediction_loop.py
+++ b/src/lightning/pytorch/loops/prediction_loop.py
@@ -233,8 +233,9 @@ def _predict_step(

         self.batch_progress.increment_ready()

-        if not using_dataloader_iter:
-            any_on_epoch = self._store_data_for_prediction_writer(batch_idx, dataloader_idx)
+        any_on_epoch = (
+            self._store_data_for_prediction_writer(batch_idx, dataloader_idx) if not using_dataloader_iter else False
+        )

         # the `_step` methods don't take a batch_idx when `dataloader_iter` is used, but all other hooks still do,
         # so we need different kwargs

UnboundLocalError: local variable 'any_on_epoch' referenced before assignment in prediction loop
### Bug description

`UnboundLocalError` raises when using the predict method with `return_predictions=False`.

This is due to `any_on_epoch` [not being defined](https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/loops/prediction_loop.py#L236) if `data_fetcher` is [an instance](https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/loops/prediction_loop.py#L229) of `_DataLoaderIterDataFetcher`.

### What version are you seeing the problem on?

v2.4

### How to reproduce the bug

_No response_

### Error messages and logs

```
UnboundLocalError: local variable 'any_on_epoch' referenced before assignment
```

### Environment

<details>
  <summary>Current environment</summary>

```
#- PyTorch Lightning Version (e.g., 2.4.0):
#- PyTorch Version (e.g., 2.4):
#- Python version (e.g., 3.12):
#- OS (e.g., Linux):
#- CUDA/cuDNN version:
#- GPU models and configuration:
#- How you installed Lightning(`conda`, `pip`, source):
```

</details>

### More info

_No response_

nice catch

> This is due to any_on_epoch [not being defined](https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/loops/prediction_loop.py#L236) if data_fetcher is [not an instance](https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/loops/prediction_loop.py#L229) of _DataLoaderIterDataFetcher.

it's actually the other way around, it errors out when it *is* an instance of `_DataLoaderIterDataFetcher`

the solution is to replace lines 236 and 237:
https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/loops/prediction_loop.py#L236-L237

with

```python
any_on_epoch = self._store_data_for_prediction_writer(batch_idx, dataloader_idx) if not using_dataloader_iter else False
```

Would you like to volunteer for a quick PR?


diff --git a/examples/fabric/build_your_own_trainer/run.py b/examples/fabric/build_your_own_trainer/run.py
index 01044f5d94fa8..c0c2ff28ddc41 100644
--- a/examples/fabric/build_your_own_trainer/run.py
+++ b/examples/fabric/build_your_own_trainer/run.py
@@ -41,7 +41,8 @@ def training_step(self, batch, batch_idx: int):

     def configure_optimizers(self):
         optim = torch.optim.Adam(self.parameters(), lr=1e-4)
-        return optim, {
+        return {
+            "optimizer": optim,
             "scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau(optim, mode="max", verbose=True),
             "monitor": "val_accuracy",
             "interval": "epoch",

OptimizerLRScheduler typing does not fit examples
### Bug description

The return type of `LightningModule.configure_optimizers()` is `OptimizerLRScheduler`, see the [source code](https://github.com/Lightning-AI/pytorch-lightning/blob/e6c26d2d22fc4678b2cf47d57697ebae68b09529/src/lightning/pytorch/core/module.py#L954). However, the examples give return types not fitting this return type. See e.g. the example [here](https://github.com/Lightning-AI/pytorch-lightning/blob/e6c26d2d22fc4678b2cf47d57697ebae68b09529/examples/fabric/build_your_own_trainer/run.py#L42-L49).

Furthermore, the `OptimizerLRScheduler` is only used as a return type, but I don't see where it is actually used, i.e. the other part of the typed interface. A [search for it](https://github.com/search?q=repo%3ALightning-AI%2Fpytorch-lightning%20OptimizerLRScheduler&type=code) does not reveal it.

### What version are you seeing the problem on?

2.3.1

### How to reproduce the bug

Just run mypy on an example, e.g. https://github.com/Lightning-AI/pytorch-lightning/blob/e6c26d2d22fc4678b2cf47d57697ebae68b09529/examples/fabric/build_your_own_trainer/run.py#L42-L49.

### Error messages and logs

Running mypy on this causes a bug:
```
Error: Incompatible return value type (got "tuple[Adam, dict[str, object]]", expected "Optimizer | Sequence[Optimizer] | tuple[Sequence[Optimizer], Sequence[LRScheduler | ReduceLROnPlateau | LRSchedulerConfig]] | OptimizerLRSchedulerConfig | Sequence[OptimizerLRSchedulerConfig] | None")
```

### Environment

<details>
  <summary>Current environment</summary>

* CUDA:
        - GPU:               None
        - available:         False
        - version:           None
* Lightning:
        - lightning-utilities: 0.11.3.post0
        - pytorch-lightning: 2.3.1
        - torch:             2.3.1
        - torchmetrics:      0.8.0
        - torchvision:       0.18.1
* Packages:
        - absl-py:           2.1.0
        - aenum:             3.1.15
        - aiohttp:           3.9.5
        - aiosignal:         1.3.1
        - alabaster:         0.7.16
        - albumentations:    1.3.1
        - antlr4-python3-runtime: 4.9.3
        - arabic-reshaper:   3.0.0
        - asn1crypto:        1.5.1
        - async-timeout:     4.0.3
        - attrs:             23.2.0
        - babel:             2.15.0
        - boto3:             1.34.137
        - botocore:          1.34.137
        - build:             1.2.1
        - certifi:           2024.6.2
        - cffi:              1.16.0
        - charset-normalizer: 3.3.2
        - click:             8.1.7
        - coloredlogs:       15.0.1
        - contourpy:         1.2.1
        - coverage:          5.3.1
        - cryptography:      42.0.8
        - cssselect2:        0.7.0
        - cycler:            0.12.1
        - data-gradients:    0.3.2
        - deprecated:        1.2.14
        - docutils:          0.17.1
        - einops:            0.3.2
        - exceptiongroup:    1.2.1
        - filelock:          3.15.4
        - flatbuffers:       24.3.25
        - fonttools:         4.53.0
        - frozenlist:        1.4.1
        - fsspec:            2024.6.1
        - future:            1.0.0
        - grpcio:            1.64.1
        - html5lib:          1.1
        - huggingface-hub:   0.23.4
        - humanfriendly:     10.0
        - hydra-core:        1.3.2
        - idna:              3.7
        - imagededup:        0.3.1
        - imageio:           2.34.2
        - imagesize:         1.4.1
        - iniconfig:         2.0.0
        - jinja2:            3.1.4
        - jmespath:          1.0.1
        - joblib:            1.4.2
        - json-tricks:       3.16.1
        - jsonschema:        4.22.0
        - jsonschema-specifications: 2023.12.1
        - kiwisolver:        1.4.5
        - lazy-loader:       0.4
        - lightly:           1.5.8
        - lightly-train:     0.1.0
        - lightly-utils:     0.0.2
        - lightning-utilities: 0.11.3.post0
        - lxml:              5.2.2
        - markdown:          3.6
        - markdown-it-py:    3.0.0
        - markupsafe:        2.1.5
        - matplotlib:        3.9.0
        - mdurl:             0.1.2
        - mpmath:            1.3.0
        - multidict:         6.0.5
        - mypy:              1.10.1
        - mypy-extensions:   1.0.0
        - networkx:          3.3
        - numpy:             1.23.0
        - omegaconf:         2.3.0
        - onnx:              1.15.0
        - onnxruntime:       1.15.0
        - onnxsim:           0.4.36
        - opencv-python:     4.10.0.84
        - opencv-python-headless: 4.10.0.84
        - oscrypto:          1.3.0
        - packaging:         24.1
        - pandas:            2.2.2
        - pillow:            10.4.0
        - pip:               24.1.1
        - pip-tools:         7.4.1
        - platformdirs:      4.2.2
        - pluggy:            1.5.0
        - protobuf:          3.20.3
        - psutil:            6.0.0
        - pycparser:         2.22
        - pydantic:          1.10.17
        - pydeprecate:       0.3.2
        - pygments:          2.18.0
        - pyhanko:           0.25.0
        - pyhanko-certvalidator: 0.26.3
        - pyparsing:         3.1.2
        - pypdf:             4.2.0
        - pypng:             0.20220715.0
        - pyproject-hooks:   1.1.0
        - pytest:            8.2.2
        - pytest-mock:       3.14.0
        - python-bidi:       0.4.2
        - python-dateutil:   2.9.0.post0
        - pytorch-lightning: 2.3.1
        - pytz:              2024.1
        - pywavelets:        1.6.0
        - pyyaml:            6.0.1
        - qrcode:            7.4.2
        - qudida:            0.0.4
        - rapidfuzz:         3.9.3
        - referencing:       0.35.1
        - reportlab:         3.6.13
        - requests:          2.32.3
        - rich:              13.7.1
        - rpds-py:           0.18.1
        - ruff:              0.5.0
        - s3transfer:        0.10.2
        - safetensors:       0.4.3
        - scikit-image:      0.24.0
        - scikit-learn:      1.5.0
        - scipy:             1.13.1
        - seaborn:           0.13.2
        - selftrain:         0.1.0
        - setuptools:        70.2.0
        - six:               1.16.0
        - snowballstemmer:   2.2.0
        - sphinx:            4.0.3
        - sphinx-rtd-theme:  1.3.0
        - sphinxcontrib-applehelp: 1.0.8
        - sphinxcontrib-devhelp: 1.0.6
        - sphinxcontrib-htmlhelp: 2.0.5
        - sphinxcontrib-jquery: 4.1
        - sphinxcontrib-jsmath: 1.0.1
        - sphinxcontrib-qthelp: 1.0.7
        - sphinxcontrib-serializinghtml: 1.1.10
        - stringcase:        1.2.0
        - super-gradients:   3.7.1
        - svglib:            1.5.1
        - sympy:             1.12.1
        - tensorboard:       2.17.0
        - tensorboard-data-server: 0.7.2
        - termcolor:         1.1.0
        - threadpoolctl:     3.5.0
        - tifffile:          2024.6.18
        - timm:              1.0.7
        - tinycss2:          1.3.0
        - tomli:             2.0.1
        - torch:             2.3.1
        - torchmetrics:      0.8.0
        - torchvision:       0.18.1
        - tqdm:              4.66.4
        - treelib:           1.6.1
        - typing-extensions: 4.12.2
        - tzdata:            2024.1
        - tzlocal:           5.2
        - uritools:          4.0.3
        - urllib3:           2.2.2
        - webencodings:      0.5.1
        - werkzeug:          3.0.3
        - wheel:             0.43.0
        - wrapt:             1.16.0
        - xhtml2pdf:         0.2.11
        - yarl:              1.9.4
* System:
        - OS:                Darwin
        - architecture:
                - 64bit
                -
        - processor:         arm
        - python:            3.10.8
        - release:           23.5.0
        - version:           Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000

### More info

_No response_

Hey @MalteEbner
The optimizer should be inside the dict in that example. Thank you for noticing it. Would you like to send a PR with this quick fix? Would be much appreciated 😃
> Hey @MalteEbner The optimizer should be inside the dict in that example. Thank you for noticing it. Would you like to send a PR with this quick fix? Would be much appreciated 😃

Unfortunately, the problem is not that the example is wrong. This is just a symptom of an underlying problem. The problem is that the `LightningModule.configure_optimizers() -> OptimizerLRScheduler` and its usage don't fit.

Toe see why, have a look at where `configure_optimizers()` is used, see the source code [here](https://github.com/Lightning-AI/pytorch-lightning/blob/f91349c961103af48091654775248789b6e03bd1/src/lightning/pytorch/core/optimizer.py#L179-L200): The output of it is stored under the variable name `optim_conf` and then passed to the function
```python
def _configure_optimizers(
    optim_conf: Union[Dict[str, Any], List, Optimizer, Tuple],
)
```

However, these definition type `OptimizerLRScheduler` and the usage type `Union[Dict[str, Any], List, Optimizer, Tuple]  `don't align. To fix this, more is needed

1. Change it to `optim_conf: OptimizerLRScheduler`, so that the usage of `configure_optimizers()` has the same type as its definition.
2. Redefine the `OptimizerLRScheduler` such that it fits the supported types in `_configure_optimizers`.
I'm not seeing any mypy errors regarding this. Which version did you use and what was the command you ran? The version we test with you can see here: https://github.com/Lightning-AI/pytorch-lightning/blob/master/requirements/typing.txt

We typically bump it together when an new torch version comes out (which is soon again). Maybe your issue will show up, but I'm not seeing it locally.

Yes sure, the internal `_configure_optimizers` uses a bit more generic typing. Feel free to update it to be more specific 👍 . The return type of `LightningModule.configure_optimizers()` should not be changed, this looks all good to me still.


diff --git a/src/lightning/pytorch/cli.py b/src/lightning/pytorch/cli.py
index 26af335f7be93..e0de8a24b38f5 100644
--- a/src/lightning/pytorch/cli.py
+++ b/src/lightning/pytorch/cli.py
@@ -389,6 +389,7 @@ def __init__(
         self._add_instantiators()
         self.before_instantiate_classes()
         self.instantiate_classes()
+        self.after_instantiate_classes()

         if self.subcommand is not None:
             self._run_subcommand(self.subcommand)
@@ -560,6 +561,9 @@ def instantiate_classes(self) -> None:
         self._add_configure_optimizers_method_to_model(self.subcommand)
         self.trainer = self.instantiate_trainer()

+    def after_instantiate_classes(self) -> None:
+        """Implement to run some code after instantiating the classes."""
+
     def instantiate_trainer(self, **kwargs: Any) -> Trainer:
         """Instantiates the trainer.

Proposal(CLI): after_instantiate_classes hook
### Description & Motivation

Adds a `after_instantiate_classes` hook to the Lightning CLI, called after `self.instantiate_classes()` during the initalization of `LightningCLI`.

### Pitch

While having the Lightning CLI is great, it is not perfect for each use case out-of-the-box. Hence, you included hooks like `before_instantiate_classes` and describe in the docs how to extend the CLI. Problem is, you cannot extend this feature without hacks or substantial copy-pasta.

I think, to further improve the CLI, without adding any complexity, it makes sense to add a `after_instantiate_classes` hook, too.

### Alternatives

1. Hacks
 - Extend the Lightning CLI and run the `after_instantiate_classes` function before the `self._run_subcommand` function.
 - Problems: it's not intuitive that the function is called there, won't be called if `self.subcommand is None`
2. Copy-Pasta
 - Extend the Lightning CLI and replace the original `__init__` with the proposed one.
 - Problems: could break with any update, lots of code duplication

### Additional context

_No response_

cc @borda @tchaton @justusschock @awaelchli @mauvilsa


diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index a9cad91924..ebd892bf17 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -507,11 +507,9 @@ def __call__(
                 if output_type == "tensor":
                     self._output_image = _output_image
                     if isinstance(_output_image, dict):
-                        self._output_image[original_keys[idx]] = self._detach_tensor_to_cpu(
-                            _output_image[original_keys[idx]]
-                        )
+                        self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
                     else:
-                        self._output_image[idx] = self._detach_tensor_to_cpu(_output_image[idx])
+                        self._output_image[idx] = _output_image[idx]
                 elif isinstance(_output_image, dict):
                     self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
                 else:

AugmentationSequential explicitly moves the output to the CPU if data_keys is given
### Describe the bug

With the 0.7.4 release, augmentations on the GPU are not possible anymore because the output of the input tensor is always explicitly moved to the CPU.

The problem is that `_detach_tensor_to_cpu` is called explicitly on every tensor in [augment.py](https://github.com/kornia/kornia/blob/main/kornia/augmentation/container/augment.py#L507).

### Reproduction steps
The augmented version of the input gets moved to the CPU:

```python
import torch
import kornia

input = torch.randn(1, 3, 10, 10, device="cuda")
mask = torch.randn(1, 10, 10, device="cuda")
aug_list = kornia.augmentation.AugmentationSequential(kornia.augmentation.RandomHorizontalFlip(p=1))

for a in aug_list(input, mask, data_keys=["input", "mask"]):
    print(a.dtype, a.device)
# torch.float32 cpu
# torch.float32 cuda:0
```

Without `data_keys` and only one input, the output device is as expected:
```python
for a in aug_list(input):
    print(a.dtype, a.device)
# torch.float32 cuda:0
```

### Expected behavior

I would expect the augmented version of the input tensor to reside on the GPU.

### Environment

- PyTorch Version (e.g., 1.0): 2.5.1
- OS (e.g., Linux): Ubuntu
- How you installed PyTorch (`conda`, `pip`, source): pip
- Build command you used (if compiling from source):
- Python version: 3.12
- CUDA/cuDNN version: 12.4
- GPU models and configuration: NVIDIA 4090 RTX
- Any other relevant information:

### Additional context

Reverting back to 0.7.3 fixes the problem.

i can see that this was touched in https://github.com/kornia/kornia/pull/2979 @ashnair1 @shijianjian @johnnv1 do you recall why we need here  `_detach_tensor_to_cpu` instead of something like `_detach_tensor_to_device` ?
It was mainly for passing the tests, due to the randomness handling for CUDA and CPU are different.

I think the bug is because the dict tensors are not handled properly to be move back to CUDA. @ashnair1, can you fix this? We may need to do a patch release after this.

BTW, I think we may need a pre-merge action to run CUDA tests. At least to run it for one-time for each merge. It has happened many times I think that some CUDA errors after all CPU tests passed.
> BTW, I think we may need a pre-merge action to run CUDA tests. At least to run it for one-time for each merge. It has happened many times I think that some CUDA errors after all CPU tests passed.

For that, we need someone to sponsor with access to a machine that has a cuda device.
Will the meta device be helpful? So we mock cuda instead?

https://pytorch.org/docs/stable/meta.html

https://github.com/pytorch/pytorch/issues/61654#issuecomment-879989145
we can try yes
One of Kornia's biggest strengths is fast GPU augmentations. This bug makes 0.7.4 unusable for many including me - are there any updates on a fix?
hey @ashnair1, can you help fix this issue?


diff --git a/wandb/apis/public/runs.py b/wandb/apis/public/runs.py
index c605630e079..b29b5109f91 100644
--- a/wandb/apis/public/runs.py
+++ b/wandb/apis/public/runs.py
@@ -236,7 +236,6 @@ def histories(
             if not histories:
                 return pd.DataFrame()
             combined_df = pd.concat(histories)
-            combined_df.sort_values("run_id", inplace=True)
             combined_df.reset_index(drop=True, inplace=True)
             # sort columns for consistency
             combined_df = combined_df[(sorted(combined_df.columns))]
@@ -262,9 +261,9 @@ def histories(
                 histories.append(df)
             if not histories:
                 return pl.DataFrame()
-            combined_df = pl.concat(histories, how="align")
+            combined_df = pl.concat(histories, how="vertical")
             # sort columns for consistency
-            combined_df = combined_df.select(sorted(combined_df.columns)).sort("run_id")
+            combined_df = combined_df.select(sorted(combined_df.columns))

             return combined_df

[Bug]: Incorrect order in `runs.histories()`
### Describe the bug

`Runs` have a `order` attribute. However in the `Runs.histories()` method the order is not respected and the `runid` is used to sort instead (see [Relevant code](https://github.com/wandb/wandb/blob/v0.18.7/wandb/apis/public/runs.py#L236). I don't think this is desirable and also is undocumented behavior. I would recommend that the order specified in the `Runs` object is used or to not reorder  all so that it is preserved to match the order obtained when iterating over the `runs` object via the iterator interface.

wandb: 0.17.3
python 3.11.8
operating system: Ubuntu 22.04


diff --git a/wandb/sdk/data_types/video.py b/wandb/sdk/data_types/video.py
index 54e338ef2a5..41310640d6f 100644
--- a/wandb/sdk/data_types/video.py
+++ b/wandb/sdk/data_types/video.py
@@ -138,10 +138,21 @@ def __init__(
             self.encode(fps=fps)

     def encode(self, fps: int = 4) -> None:
-        mpy = util.get_module(
-            "moviepy.editor",
-            required='wandb.Video requires moviepy when passing raw data.  Install with "pip install wandb[media]"',
-        )
+        # Try to import ImageSequenceClip from the appropriate MoviePy module
+        mpy = None
+        try:
+            # Attempt to load moviepy.editor for MoviePy < 2.0
+            mpy = util.get_module(
+                "moviepy.editor",
+                required='wandb.Video requires moviepy when passing raw data. Install with "pip install wandb[media]"',
+            )
+        except wandb.Error:
+            # Fallback to moviepy for MoviePy >= 2.0
+            mpy = util.get_module(
+                "moviepy",
+                required='wandb.Video requires moviepy when passing raw data. Install with "pip install wandb[media]"',
+            )
+
         tensor = self._prepare_video(self.data)
         _, self._height, self._width, self._channels = tensor.shape  # type: ignore

[Bug]: "wandb.Video requires moviepy when passing raw data" Error due to new moviepy version
### Describe the bug

The moviepy package was updated to 2.x and removed the `moviepy.editor` namespace (see [here](https://zulko.github.io/moviepy/getting_started/updating_to_v2.html)), breaking the `Video.encode` method.
Fixing by either migrating to moviepy 2.x or pinning the earlier version.

Version info:
NixOS 24.05
Python 3.11.10
wandb 0.18.7
moviepy 2.1.1


diff --git a/speechbrain/lobes/models/huggingface_transformers/weighted_ssl.py b/speechbrain/lobes/models/huggingface_transformers/weighted_ssl.py
index 1507f85093..2dad9e1e46 100644
--- a/speechbrain/lobes/models/huggingface_transformers/weighted_ssl.py
+++ b/speechbrain/lobes/models/huggingface_transformers/weighted_ssl.py
@@ -42,6 +42,8 @@ class WeightedSSLModel(HFTransformersInterface):
     freeze : bool (default: True)
         If True, the model is frozen. If False, the model will be trained
         alongside with the rest of the pipeline.
+    **kwargs : dict
+        Additional arguments to pass to HFTransformersInterface

     Example
     -------
@@ -52,14 +54,19 @@ class WeightedSSLModel(HFTransformersInterface):
     >>> outputs = model(inputs)
     """

-    def __init__(self, hub, save_path="", layernorm=False, freeze=False):
-        super().__init__(source=hub, save_path=save_path, freeze=freeze)
+    def __init__(
+        self, hub, save_path="", layernorm=False, freeze=False, **kwargs
+    ):
+        super().__init__(
+            source=hub, save_path=save_path, freeze=freeze, **kwargs
+        )
         self.model.eval()
+        self.layernorm = layernorm
+        self.freeze = freeze
         self.num_layers = self.config.num_hidden_layers + 1
         # Initializing the learnable weights
         zero_init = torch.cat([torch.zeros(self.num_layers)])
         self.weights = torch.nn.Parameter(zero_init, requires_grad=True)
-        self.layernorm = layernorm

     def forward(self, wav, wav_lens=None):
         """This method outputs a weighted sum of the layer representations of the SSL encoder
@@ -78,21 +85,25 @@ def forward(self, wav, wav_lens=None):
         """

         feats = self.model(wav)
-        hidden_states = torch.stack(feats.hidden_states, dim=0).detach()
+        if self.freeze:
+            hidden_states = torch.stack(feats.hidden_states, dim=0).detach()
+        else:
+            hidden_states = torch.stack(feats.hidden_states, dim=0)
+
         # First dimension should be equal to the number of layers in the hparams
         assert (
             self.num_layers == hidden_states.shape[0]
         ), "Num layers not equal to num hidden states"
-        norm_weights = torch.nn.functional.softmax(self.weights, dim=-1)
+
         # Layernorming the layers representations if asked
         if self.layernorm:
-            hidden_states = [
-                F.layer_norm(t, (t.shape[-1],)) for t in hidden_states
-            ]
+            normalized_shape = (hidden_states.size(-1),)
+            hidden_states = F.layer_norm(hidden_states, normalized_shape)
+
         # Summing the weighted layers
-        weighted_feats = (
-            hidden_states * norm_weights[:, None, None, None]
-        ).sum(axis=0)
+        norm_weights = F.softmax(self.weights, dim=-1).view(-1, 1, 1, 1)
+        weighted_feats = (hidden_states * norm_weights).sum(axis=0)
+
         return weighted_feats

     def override_config(self, config):

Weighted SSL model not unfreezable
### Describe the bug

In our HF Weighted SSL model implementation, we `detach()` the hidden states, meaning weights are not updated.

Relevant code:
https://github.com/speechbrain/speechbrain/blob/develop/speechbrain/lobes/models/huggingface_transformers/weighted_ssl.py#L81

```
hidden_states = torch.stack(feats.hidden_states, dim=0).detach()
```

### Expected behaviour

If passing `freeze=False` I'd expect the weights to get updated.

### To Reproduce

_No response_

### Environment Details

_No response_

### Relevant Log Output

_No response_

### Additional Context

_No response_

Also if `layernorm=True` then the hidden states are converted to a list which causes a program crash. They should be re-stacked into a tensor.


diff --git a/recipes/LibriSpeech/ASR/transformer/train_with_whisper.py b/recipes/LibriSpeech/ASR/transformer/train_with_whisper.py
index 5c65a49682..90e0d118d3 100644
--- a/recipes/LibriSpeech/ASR/transformer/train_with_whisper.py
+++ b/recipes/LibriSpeech/ASR/transformer/train_with_whisper.py
@@ -107,7 +107,6 @@ def compute_objectives(self, predictions, batch, stage):
             target_words = self.tokenizer.batch_decode(
                 target_words, skip_special_tokens=True
             )
-
             if hasattr(self.hparams, "normalized_transcripts"):

                 if hasattr(self.tokenizer, "normalize"):
@@ -237,7 +236,10 @@ def audio_pipeline(wav):
         "wrd", "tokens_list", "tokens_bos", "tokens_eos", "tokens"
     )
     def text_pipeline(wrd):
-        if "normalized_transcripts" in hparams:
+        if (
+            "normalized_transcripts" in hparams
+            and hparams["normalized_transcripts"]
+        ):
             wrd = tokenizer.normalize(wrd)
         yield wrd
         tokens_list = tokenizer.encode(wrd, add_special_tokens=False)

Syntax Bug in Librispeech Whisper Recipe
### Describe the bug

These bugs listed below are related to whisper specifically following this [recipe](recipes/LibriSpeech/ASR/transformer/train_with_whisper.py)
1) line 228 in dataio_prepare, hparams is a dictionary so `hasattr(hparams, "normalized_transcripts")` does not work as intended.

2) line 50. I've gotten some rounding issues for some batches where the .long() rounds down rather than to the nearest int. (i.e. 12.998 gets rounded down to 12, excluding the last token).

### Expected behaviour

1) just change syntax to check keys in dictionary
2) use torch.round() to ensure proper mask computation

### To Reproduce

_No response_

### Environment Details

_No response_

### Relevant Log Output

_No response_

### Additional Context

_No response_

Hi @matthewkperez, thanks for opening this issue! Would you like to open a PR to fix it? It would be a very welcome contribution :)
Just submitted PR #2737 for this. Cheers!


diff --git a/mesonbuild/backend/ninjabackend.py b/mesonbuild/backend/ninjabackend.py
index cb3552d7f0c1..7b573e4e4d8a 100644
--- a/mesonbuild/backend/ninjabackend.py
+++ b/mesonbuild/backend/ninjabackend.py
@@ -2369,7 +2369,7 @@ def generate_dynamic_link_rules(self) -> None:

                 options = self._rsp_options(compiler)
                 self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool))
-            if self.environment.machines[for_machine].is_aix():
+            if self.environment.machines[for_machine].is_aix() and complist:
                 rule = 'AIX_LINKER{}'.format(self.get_rule_suffix(for_machine))
                 description = 'Archiving AIX shared library'
                 cmdlist = compiler.get_command_to_archive_shlib()

Building meson-python fails in AIX
When I tried to meson-python master branch in AIX using meson, I get the below error
```
Traceback (most recent call last):
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/mesonmain.py", line 193, in run
    return options.run_func(options)
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/msetup.py", line 365, in run
    app.generate()
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/msetup.py", line 188, in generate
    return self._generate(env, capture, vslite_ctx)
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/msetup.py", line 253, in _generate
    captured_compile_args = intr.backend.generate(capture, vslite_ctx)
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/backend/ninjabackend.py", line 642, in generate
    self.generate_rules()
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/backend/ninjabackend.py", line 1354, in generate_rules
    self.generate_dynamic_link_rules()
  File "/meson/install/opt/freeware/lib/python3.9/site-packages/mesonbuild/backend/ninjabackend.py", line 2376, in generate_dynamic_link_rules
    cmdlist = compiler.get_command_to_archive_shlib()
UnboundLocalError: local variable 'compiler' referenced before assignment
```

For this I would like to propose a simple fix that handles the scenario when compiler is empty
```
diff --git a/mesonbuild/backend/ninjabackend.py b/mesonbuild/backend/ninjabackend.py
index cb3552d7f..7b573e4e4 100644
--- a/mesonbuild/backend/ninjabackend.py
+++ b/mesonbuild/backend/ninjabackend.py
@@ -2369,7 +2369,7 @@ class NinjaBackend(backends.Backend):

                 options = self._rsp_options(compiler)
                 self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool))
-            if self.environment.machines[for_machine].is_aix():
+            if self.environment.machines[for_machine].is_aix() and complist:
                 rule = 'AIX_LINKER{}'.format(self.get_rule_suffix(for_machine))
                 description = 'Archiving AIX shared library'
                 cmdlist = compiler.get_command_to_archive_shlib()
```

Kindly let me know if can I raise a PR and you're okay with this.

cc: @eli-schwartz

I can confirm this bug exists and the fix solves the issue.
Ah hmm, right. This happens because we only iterate over all configured project languages that also support using a linker, and then create AIX_LINKER for the last one basically. This fails for projects that don't have any configured languages, which is okay since they also do not need to run the AIX_LINKER archiving rule.

The fix seems reasonable...


diff --git a/ultralytics/engine/model.py b/ultralytics/engine/model.py
index db8d87ebc2..8affd958f2 100644
--- a/ultralytics/engine/model.py
+++ b/ultralytics/engine/model.py
@@ -115,7 +115,7 @@ def __init__(
         self.predictor = None  # reuse predictor
         self.model = None  # model object
         self.trainer = None  # trainer object
-        self.ckpt = None  # if loaded from *.pt
+        self.ckpt = {}  # if loaded from *.pt
         self.cfg = None  # if loaded from *.yaml
         self.ckpt_path = None
         self.overrides = {}  # overrides for trainer object
@@ -807,7 +807,7 @@ def train(
         # Update model and cfg after training
         if RANK in {-1, 0}:
             ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
-            self.model, _ = attempt_load_one_weight(ckpt)
+            self.model, self.ckpt = attempt_load_one_weight(ckpt)
             self.overrides = self.model.args
             self.metrics = getattr(self.trainer.validator, "metrics", None)  # TODO: no metrics returned by DDP
         return self.metrics

Saving yolov6n crashes
### Search before asking

- [X] I have searched the Ultralytics YOLO [issues](https://github.com/ultralytics/ultralytics/issues) and found no similar bug report.

### Ultralytics YOLO Component

Export

### Bug

Crash on "yolov6n.yaml" save.

```
New https://pypi.org/project/ultralytics/8.3.49 available 😃 Update with 'pip install -U ultralytics'
Ultralytics 8.3.44 🚀 Python-3.10.12 torch-2.5.1+cu124 CPU (AMD Ryzen 3 3200G with Radeon Vega Graphics)
engine/trainer: task=detect, mode=train, model=yolov6n.yaml, data=coco8.yaml, epochs=1, time=None, patience=100, batch=16, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=train11, exist_ok=False, pretrained=True, optimizer=auto, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, multi_scale=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, embed=None, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=True, opset=None, workspace=None, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, bgr=0.0, mosaic=1.0, mixup=0.0, copy_paste=0.0, copy_paste_mode=flip, auto_augment=randaugment, erasing=0.4, crop_fraction=1.0, cfg=None, tracker=botsort.yaml, save_dir=runs/detect/train11
activation: nn.ReLU()

                   from  n    params  module                                       arguments
  0                  -1  1       464  ultralytics.nn.modules.conv.Conv             [3, 16, 3, 2]
  1                  -1  1      4672  ultralytics.nn.modules.conv.Conv             [16, 32, 3, 2]
  2                  -1  2     18560  ultralytics.nn.modules.conv.Conv             [32, 32, 3, 1]
  3                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]
  4                  -1  4    147968  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 1]
  5                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]
  6                  -1  6    886272  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 1]
  7                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]
  8                  -1  2   1180672  ultralytics.nn.modules.conv.Conv             [256, 256, 3, 1]
  9                  -1  1    164608  ultralytics.nn.modules.block.SPPF            [256, 256, 5]
 10                  -1  1     16512  ultralytics.nn.modules.conv.Conv             [256, 64, 1, 1]
 11                  -1  1     16448  torch.nn.modules.conv.ConvTranspose2d        [64, 64, 2, 2, 0]
 12             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 13                  -1  1    110720  ultralytics.nn.modules.conv.Conv             [192, 64, 3, 1]
 14                  -1  3    110976  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 1]
 15                  -1  1      2112  ultralytics.nn.modules.conv.Conv             [64, 32, 1, 1]
 16                  -1  1      4128  torch.nn.modules.conv.ConvTranspose2d        [32, 32, 2, 2, 0]
 17             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 18                  -1  1     27712  ultralytics.nn.modules.conv.Conv             [96, 32, 3, 1]
 19                  -1  3     27840  ultralytics.nn.modules.conv.Conv             [32, 32, 3, 1]
 20                  -1  1      9280  ultralytics.nn.modules.conv.Conv             [32, 32, 3, 2]
 21            [-1, 15]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 22                  -1  1     36992  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 1]
 23                  -1  3    110976  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 1]
 24                  -1  1     36992  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 2]
 25            [-1, 10]  1         0  ultralytics.nn.modules.conv.Concat           [1]
 26                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 1]
 27                  -1  3    443136  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 1]
 28        [19, 23, 27]  1    607360  ultralytics.nn.modules.head.Detect           [80, [32, 64, 128]]
YOLOv6n summary: 195 layers, 4,500,080 parameters, 4,500,064 gradients, 13.1 GFLOPs

TensorBoard: Start with 'tensorboard --logdir runs/detect/train11', view at http://localhost:6006/
Freezing layer 'model.28.dfl.conv.weight'
train: Scanning datasets/coco8/labels/train.cache... 4 images, 0 backgrounds, 0 corrupt: 100%|██████████| 4/4 [00:00<?, ?it/s]
val: Scanning datasets/coco8/labels/val.cache... 4 images, 0 backgrounds, 0 corrupt: 100%|██████████| 4/4 [00:00<?, ?it/s]
Plotting labels to runs/detect/train11/labels.jpg...
optimizer: 'optimizer=auto' found, ignoring 'lr0=0.01' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically...
optimizer: AdamW(lr=0.000119, momentum=0.9) with parameter groups 53 weight(decay=0.0), 62 weight(decay=0.0005), 61 bias(decay=0.0)
TensorBoard: model graph visualization added ✅
Image sizes 640 train, 640 val
Using 0 dataloader workers
Logging results to runs/detect/train11
Starting training for 1 epochs...

      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size
        1/1         0G      3.483      5.686      4.311         22        640: 100%|██████████| 1/1 [00:05<00:00,  5.91s/it]
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 1/1 [00:02<00:00,  2.16s/it]
                   all          4         17          0          0          0          0

1 epochs completed in 0.006 hours.
Optimizer stripped from runs/detect/train11/weights/last.pt, 9.2MB
Optimizer stripped from runs/detect/train11/weights/best.pt, 9.2MB

Validating runs/detect/train11/weights/best.pt...
WARNING ⚠ validating an untrained model YAML will result in 0 mAP.
Ultralytics 8.3.44 🚀 Python-3.10.12 torch-2.5.1+cu124 CPU (AMD Ryzen 3 3200G with Radeon Vega Graphics)
YOLOv6n summary (fused): 142 layers, 4,495,392 parameters, 0 gradients, 13.0 GFLOPs
                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 1/1 [00:01<00:00,  1.31s/it]
                   all          4         17          0          0          0          0
Speed: 4.7ms preprocess, 314.3ms inference, 0.0ms loss, 2.3ms postprocess per image
Results saved to runs/detect/train11
Traceback (most recent call last):
  File "main.py", line 91, in <module>
    detectImageWithYolo()
  File "main.py", line 70, in detectImageWithYolo
    model.save("yolov6coco.pt")
  File ".venv/lib/python3.10/site-packages/ultralytics/engine/model.py", line 414, in save
    torch.save({**self.ckpt, **updates}, filename)
TypeError: 'NoneType' object is not a mapping
```

### Environment

Ultralytics 8.3.44 🚀 Python-3.10.12 torch-2.5.1+cu124 CPU (AMD Ryzen 3 3200G with Radeon Vega Graphics)
Setup complete ✅ (4 CPUs, 23.3 GB RAM, 2769.5/3185.4 GB disk)
OS                  Linux-6.8.0-49-generic-x86_64-with-glibc2.35
Environment         Linux
Python              3.10.12
Install             pip
RAM                 23.35 GB
Disk                2769.5/3185.4 GB
CPU                 AMD Ryzen 3 3200G with Radeon Vega Graphics
CPU count           4
GPU                 None
GPU count           None
CUDA                None
numpy               ✅ 2.0.2>=1.23.0
numpy               ✅ 2.0.2<2.0.0; sys_platform == "darwin"
matplotlib          ✅ 3.9.2>=3.3.0
opencv-python       ✅ 4.10.0.84>=4.6.0
pillow              ✅ 11.0.0>=7.1.2
pyyaml              ✅ 6.0.2>=5.3.1
requests            ✅ 2.32.3>=2.23.0
scipy               ✅ 1.14.1>=1.4.1
torch               ✅ 2.5.1>=1.8.0
torch               ✅ 2.5.1!=2.4.0,>=1.8.0; sys_platform == "win32"
torchvision         ✅ 0.20.1>=0.9.0
tqdm                ✅ 4.67.1>=4.64.0
psutil              ✅ 6.1.0
py-cpuinfo          ✅ 9.0.0
pandas              ✅ 2.2.3>=1.1.4
seaborn             ✅ 0.13.2>=0.11.0
ultralytics-thop    ✅ 2.0.12>=2.0.0
{'OS': 'Linux-6.8.0-49-generic-x86_64-with-glibc2.35', 'Environment': 'Linux', 'Python': '3.10.12', 'Install': 'pip', 'RAM': '23.35 GB', 'Disk': '2769.5/3185.4 GB', 'CPU': 'AMD Ryzen 3 3200G with Radeon Vega Graphics', 'CPU count': 4, 'GPU': None, 'GPU count': None, 'CUDA': None, 'Package Info': {'numpy': '✅ 2.0.2<2.0.0; sys_platform == "darwin"', 'matplotlib': '✅ 3.9.2>=3.3.0', 'opencv-python': '✅ 4.10.0.84>=4.6.0', 'pillow': '✅ 11.0.0>=7.1.2', 'pyyaml': '✅ 6.0.2>=5.3.1', 'requests': '✅ 2.32.3>=2.23.0', 'scipy': '✅ 1.14.1>=1.4.1', 'torch': '✅ 2.5.1!=2.4.0,>=1.8.0; sys_platform == "win32"', 'torchvision': '✅ 0.20.1>=0.9.0', 'tqdm': '✅ 4.67.1>=4.64.0', 'psutil': '✅ 6.1.0', 'py-cpuinfo': '✅ 9.0.0', 'pandas': '✅ 2.2.3>=1.1.4', 'seaborn': '✅ 0.13.2>=0.11.0', 'ultralytics-thop': '✅ 2.0.12>=2.0.0'}}

### Minimal Reproducible Example

```
model = YOLO("yolov6n.yaml")
model.train(data="coco8.yaml", epochs=1, imgsz=640)
model.save("yolov6coco.pt")
```

### Additional

_No response_

### Are you willing to submit a PR?

- [ ] Yes I'd like to help by submitting a PR!

👋 Hello @EmmanuelMess, thank you for your interest in Ultralytics 🚀! We appreciate you taking the time to report this issue.

To help us investigate further, could you please confirm the reproducibility of this issue using the latest version of Ultralytics? You can upgrade with the command below:

```bash
pip install -U ultralytics
```

We also noticed that you've shared a reproducible example (thank you for that!). If the issue persists in the most recent version, this example will be very helpful for us to debug. Please also ensure that your `ultralytics` environment is aligned with our recommended setups:

### Environments

YOLO can be run in any of the following up-to-date verified environments (pre-installed with all necessary dependencies such as [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/)):

- **Notebooks** with free GPU:
- **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/)

### Join the Community

- For real-time debugging or discussions, join our [Discord](https://discord.com/invite/ultralytics) server 🎧.
- Share your insights or questions on [Discourse](https://community.ultralytics.com) or [Reddit](https://reddit.com/r/Ultralytics) to interact with the thriving community.

### Helpful Resources

If you'd like to further explore concepts or troubleshoot other issues, check out our comprehensive [Docs](https://docs.ultralytics.com), including:
- [Model Training Tips](https://docs.ultralytics.com/guides/model-training-tips/)
- [Minimum Reproducible Example Guide](https://docs.ultralytics.com/help/minimum_reproducible_example/)

If this is a 🐛 bug as appears to be the case, an Ultralytics engineer will assist you soon to look deeper into the root cause. We'll stay on top of resolving this for you! 🔍😊

## Status

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 run on macOS, Windows, and Ubuntu frequently to maintain performance and reliability.

Let us know how it goes! 🚀
The model is automatically saved during training inside the runs/detect folder. You don't need to use `model.save()`.
> The model is automatically saved during training inside the runs/detect folder. You don't need to use `model.save()`.

But I want to explicitly save it to a file. It works with YOLOv11, why not with v6?
It doesn't work if you load from yaml.
> It doesn't work if you load from yaml.

Thanks for the explanation, but it probably shouldn't crash. Maybe add an error message?


diff --git a/ultralytics/engine/predictor.py b/ultralytics/engine/predictor.py
index c28e1895d07..c5250166e9e 100644
--- a/ultralytics/engine/predictor.py
+++ b/ultralytics/engine/predictor.py
@@ -155,7 +155,7 @@ def pre_transform(self, im):
         same_shapes = len({x.shape for x in im}) == 1
         letterbox = LetterBox(
             self.imgsz,
-            auto=same_shapes and (self.model.pt or getattr(self.model, "dynamic", False)),
+            auto=same_shapes and (self.model.pt or (getattr(self.model, "dynamic", False) and not self.model.imx)),
             stride=self.model.stride,
         )
         return [letterbox(image=x) for x in im]

Imx500 usage example error
### Search before asking

- [X] I have searched the Ultralytics YOLO [issues](https://github.com/ultralytics/ultralytics/issues) and found no similar bug report.

### Ultralytics YOLO Component

Export

### Bug

I encountered an error when running the example code from the [Sony IMX500 usage examples](https://docs.ultralytics.com/integrations/sony-imx500/#usage-examples). The image is resized to 480x640 instead of the expected 640x640, despite both the ONNX model input and the packerOut description specifying a 640x640 input.

The model is exported successfully, but unable to run the inference.

```
Export complete (298.0s)
Results saved to /home/magi/mido/ultralytics
Predict:         yolo predict task=detect model=yolov8n_imx_model imgsz=640 int8
Validate:        yolo val task=detect model=yolov8n_imx_model imgsz=640 data=coco.yaml int8
Visualize:       https://netron.app
WARNING ⚠ Unable to automatically guess model task, assuming 'task=detect'. Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify','pose' or 'obb'.
Loading yolov8n_imx_model for ONNX Runtime inference...
Preferring ONNX Runtime AzureExecutionProvider
Loading yolov8n_imx_model/yolov8n_imx.onnx for ONNX IMX inference...

Found https://ultralytics.com/images/bus.jpg locally at bus.jpg
Traceback (most recent call last):
  File "/home/magi/mido/ultralytics/yolo_v8_playground.py", line 13, in <module>
    results = imx_model("https://ultralytics.com/images/bus.jpg")
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/engine/model.py", line 176, in __call__
    return self.predict(source, stream, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/engine/model.py", line 554, in predict
    return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 173, in __call__
    return list(self.stream_inference(source, model, *args, **kwargs))  # merge list of Result into one
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 36, in generator_context
    response = gen.send(None)
               ^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 259, in stream_inference
    preds = self.inference(im, *args, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 143, in inference
    return self.model(im, augment=self.args.augment, visualize=visualize, embed=self.args.embed, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1736, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1747, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/ultralytics/nn/autobackend.py", line 542, in forward
    y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/magi/mido/ultralytics/.venv/lib/python3.11/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 220, in run
    return self._sess.run(output_names, input_feed, run_options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
onnxruntime.capi.onnxruntime_pybind11_state.InvalidArgument: [ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Got invalid dimensions for input: input for the following indices
 index: 3 Got: 480 Expected: 640
 Please fix either the inputs/outputs or the model.
```

I tested resizing the image to 640x640 before inference, and it worked properly. However, I assume that the inference call should handle the resizing automatically without requiring manual adjustment beforehand.

### Environment

Ultralytics 8.3.37 🚀 Python-3.11.10 torch-2.5.1+cu124 CUDA:0 (NVIDIA GeForce GTX 1650 Ti, 3906MiB)
Setup complete ✅ (12 CPUs, 31.0 GB RAM, 444.7/913.8 GB disk)

OS                  Linux-6.8.0-49-generic-x86_64-with-glibc2.35
Environment         Linux
Python              3.11.10
Install             pip
RAM                 30.97 GB
Disk                444.7/913.8 GB
CPU                 Intel Core(TM) i7-10750H 2.60GHz
CPU count           12
GPU                 NVIDIA GeForce GTX 1650 Ti, 3906MiB
GPU count           1
CUDA                12.4

numpy               ✅ 1.26.4>=1.23.0
numpy               ✅ 1.26.4<2.0.0; sys_platform == "darwin"
matplotlib          ✅ 3.9.2>=3.3.0
opencv-python       ✅ 4.10.0.84>=4.6.0
pillow              ✅ 11.0.0>=7.1.2
pyyaml              ✅ 6.0.2>=5.3.1
requests            ✅ 2.32.3>=2.23.0
scipy               ✅ 1.14.1>=1.4.1
torch               ✅ 2.5.1>=1.8.0
torch               ✅ 2.5.1!=2.4.0,>=1.8.0; sys_platform == "win32"
torchvision         ✅ 0.20.1>=0.9.0
tqdm                ✅ 4.67.1>=4.64.0
psutil              ✅ 6.1.0
py-cpuinfo          ✅ 9.0.0
pandas              ✅ 2.2.3>=1.1.4
seaborn             ✅ 0.13.2>=0.11.0
ultralytics-thop    ✅ 2.0.12>=2.0.0
{'OS': 'Linux-6.8.0-49-generic-x86_64-with-glibc2.35', 'Environment': 'Linux', 'Python': '3.11.10', 'Install': 'pip', 'RAM': '30.97 GB', 'Disk': '444.7/913.8 GB', 'CPU': 'Intel Core(TM) i7-10750H 2.60GHz', 'CPU count': 12, 'GPU': 'NVIDIA GeForce GTX 1650 Ti, 3906MiB', 'GPU count': 1, 'CUDA': '12.4', 'Package Info': {'numpy': '✅ 1.26.4<2.0.0; sys_platform == "darwin"', 'matplotlib': '✅ 3.9.2>=3.3.0', 'opencv-python': '✅ 4.10.0.84>=4.6.0', 'pillow': '✅ 11.0.0>=7.1.2', 'pyyaml': '✅ 6.0.2>=5.3.1', 'requests': '✅ 2.32.3>=2.23.0', 'scipy': '✅ 1.14.1>=1.4.1', 'torch': '✅ 2.5.1!=2.4.0,>=1.8.0; sys_platform == "win32"', 'torchvision': '✅ 0.20.1>=0.9.0', 'tqdm': '✅ 4.67.1>=4.64.0', 'psutil': '✅ 6.1.0', 'py-cpuinfo': '✅ 9.0.0', 'pandas': '✅ 2.2.3>=1.1.4', 'seaborn': '✅ 0.13.2>=0.11.0', 'ultralytics-thop': '✅ 2.0.12>=2.0.0'}}

### Minimal Reproducible Example

```python
from ultralytics import YOLO

# Load a YOLOv8n PyTorch model
model = YOLO("yolov8n.pt")

# # # Export the model
model.export(format="imx")  # exports with PTQ quantization by default

# Load the exported model
imx_model = YOLO("yolov8n_imx_model")

# Run inference
results = imx_model("https://ultralytics.com/images/bus.jpg")

```

### Additional

_No response_

### Are you willing to submit a PR?

- [ ] Yes I'd like to help by submitting a PR!

👋 Hello @Magitoneu, thank you for your interest in Ultralytics 🚀! We appreciate you taking the time to report this issue. Here’s a quick guide to help us investigate this further:

It seems like you’re experiencing an error related to image resizing when running the Sony IMX500 example. If this is indeed a 🐛 Bug Report, we kindly request you to confirm the behavior by sharing a [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/). This will help ensure we can reproduce and debug the issue effectively.

In the meantime, please ensure that you’ve updated to the latest version of the `ultralytics` package and all related requirements. You can do so by running the following command in your terminal:

```bash
pip install -U ultralytics
```

We also recommend reviewing the [Sony IMX500 integration documentation](https://docs.ultralytics.com/integrations/sony-imx500/#usage-examples) to double-check the expected behavior of the example code. It’s possible that some additional steps may be required for handling image preprocessing.

## Resources

For troubleshooting tips and to learn more ways of using the library, visit the [Ultralytics Docs](https://docs.ultralytics.com). Additional examples for Python and CLI-based workflows are available to guide you:
- [Python](https://docs.ultralytics.com/usage/python/)
- [CLI](https://docs.ultralytics.com/usage/cli/)

If you’re trying to improve your training results or explore new features, don’t miss our [Tips for Best Training Results](https://docs.ultralytics.com/guides/model-training-tips/).

## Join the Community

For real-time discussions with other Ultralytics users, join our [Discord](https://discord.com/invite/ultralytics) server 🎧. We also host conversations on [Discourse](https://community.ultralytics.com) and our [Subreddit](https://reddit.com/r/Ultralytics) for deeper discussions.

## Verified Environments

If possible, try running your code in one of our tested environments for a consistent experience:
- **Notebooks** with free GPU:
- **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**. Check the [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/)

## Status

If this badge is green, all [Ultralytics CI](https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml?query=event%3Aschedule) tests are currently passing, verifying that core functionalities across different environments are operating correctly.

This is an automated response 💡. An Ultralytics engineer will review your report and reach out with further assistance soon. Thank you for helping us improve! 😊
@Magitoneu thank you for reporting this issue. It seems that the input dimensions mismatch is due to the image size not being adjusted automatically during inference with the IMX500 export. While resizing the input image to 640x640 manually resolves the issue, automatic resizing is currently not implemented for IMX500-exported models.

As a workaround, ensure your input images are pre-processed to 640x640 before inference. For improvements in this behavior, feel free to provide additional insights, or you can open a feature request. Let us know if you need further assistance!