[Runtime][Bindings] support async parameter file loading (#24988)

Add support to the parameter providers for asynchronous I/O
so HAL drivers can stream archive data without retaining a host mapping.

And preserve the existing mmap contract for callers that rely on host
allocations while making descriptor-backed loading an explicit opt-in.

Assisted-by: GPT-6-Astra
Co-authored-by: Tobias Fuchs <fuchs@roofline.ai>

---------

Co-authored-by: Tobias Fuchs <fuchs@roofline.ai>
diff --git a/runtime/bindings/python/io.cc b/runtime/bindings/python/io.cc
index d8c6d49..0b1fcd3 100644
--- a/runtime/bindings/python/io.cc
+++ b/runtime/bindings/python/io.cc
@@ -120,7 +120,19 @@
 
 void ParameterIndexLoadFile(ParameterIndex& self, std::string& file_path,
                             std::optional<std::string> format, bool readable,
-                            bool writable, bool mmap) {
+                            bool writable, std::optional<bool> mmap,
+                            std::optional<std::string> mode) {
+  if (mode) {
+    if (*mode != "file_async") {
+      throw std::invalid_argument("unsupported parameter file mode: " + *mode);
+    }
+    if (mmap) {
+      throw std::invalid_argument("mode and mmap are mutually exclusive");
+    }
+    if (!readable || writable) {
+      throw std::invalid_argument("file_async requires read-only access");
+    }
+  }
   // Default format from extension.
   if (!format) {
     iree_string_view_t path_ext = iree_file_path_extension(
@@ -128,20 +140,17 @@
     format.emplace(path_ext.data, path_ext.size);
   }
 
-  // TODO: this behavior is wrong; the python code assumes that the file handle
-  // always ends up as a host allocation, but this is the
-  // slowest/least-efficient path in most cases. The fast-path is to use
-  // iree_io_file_handle_open and get a file descriptor-backed handle as the HAL
-  // is then able to perform optimized reads/writes sometimes zero-copy. By
-  // mapping the file explicitly all accesses go down the pathologically slow
-  // path where zero-copy is not supported and we rely on the OS to fault pages
-  // and bring them in on demand instead of being able to read/write them more
-  // efficiently. The tests (and likely user code) rely on the mapping, though,
-  // so for now this remains slow.
-
-  // Open file.
+  // Preserve host allocation handles for existing mmap callers. Async file
+  // mode lets the HAL stream data without retaining a mapping of the archive.
   iree_io_file_handle_t* raw_file_handle = nullptr;
-  if (mmap) {
+  if (mode) {
+    CheckApiStatus(
+        iree_io_file_handle_open(
+            IREE_IO_FILE_MODE_READ | IREE_IO_FILE_MODE_ASYNC,
+            iree_make_string_view(file_path.data(), file_path.size()),
+            iree_allocator_system(), &raw_file_handle),
+        "Error opening parameter file (file_async)");
+  } else if (mmap.value_or(true)) {
     iree_io_file_contents_t* contents = NULL;
     CheckApiStatus(
         iree_io_file_contents_map(
@@ -248,6 +257,10 @@
                          iree_io_file_handle_primitive(self.raw_ptr());
                      return primitive.type == IREE_IO_FILE_HANDLE_TYPE_FD;
                    })
+      .def_prop_ro("is_async",
+                   [](FileHandle& self) {
+                     return iree_io_file_handle_uses_async_io(self.raw_ptr());
+                   })
       .def_prop_ro("fd",
                    [](FileHandle& self) {
                      auto primitive =
@@ -444,7 +457,12 @@
            py::arg("file_handle"), py::arg("format"))
       .def("load", ParameterIndexLoadFile, py::arg("file_path"),
            py::arg("format") = py::none(), py::arg("readable") = true,
-           py::arg("writable") = false, py::arg("mmap") = true)
+           py::arg("writable") = false, py::arg("mmap") = py::none(),
+           py::kw_only(), py::arg("mode") = py::none(),
+           "Load an archive. By default, or with mmap=True, map its contents. "
+           "mmap=False preloads the contents. mode='file_async' opens a "
+           "read-only async file handle for HAL streaming. The index retains "
+           "the handle. Explicit mode and mmap arguments cannot be combined.")
       .def(
           "create_provider",
           [](ParameterIndex& self, std::string scope,
diff --git a/runtime/bindings/python/iree/runtime/_binding.pyi b/runtime/bindings/python/iree/runtime/_binding.pyi
index 05abddd..2ceaec0 100644
--- a/runtime/bindings/python/iree/runtime/_binding.pyi
+++ b/runtime/bindings/python/iree/runtime/_binding.pyi
@@ -132,6 +132,10 @@
 
     @property
     def is_host_allocation(self) -> bool: ...
+    @property
+    def is_async(self) -> bool:
+        """Whether the handle was opened for asynchronous I/O."""
+        ...
 
 class HalAllocator:
     def allocate_buffer(
@@ -521,7 +525,7 @@
         pattern: Any,
         total_length: int,
         *,
-        metadata: Optional[Union[bytes, str]] = None
+        metadata: Optional[Union[bytes, str]] = None,
     ) -> None: ...
     def add_from_file_handle(
         self,
@@ -530,7 +534,7 @@
         length: int,
         *,
         offset: int = 0,
-        metadata: Optional[Union[bytes, str]] = None
+        metadata: Optional[Union[bytes, str]] = None,
     ) -> None: ...
     def add_buffer(
         self,
@@ -539,18 +543,25 @@
         *,
         readable: bool = True,
         writable: bool = False,
-        metadata: Optional[Union[bytes, str]] = None
+        metadata: Optional[Union[bytes, str]] = None,
     ) -> None: ...
     def load_from_file_handle(self, file_handle: FileHandle, format: str) -> None: ...
     def load(
         self,
         file_path: str,
-        *,
         format: Optional[str] = None,
         readable: bool = True,
         writable: bool = False,
-        mmap: bool = True
-    ) -> None: ...
+        mmap: Optional[bool] = None,
+        *,
+        mode: Optional[str] = None,
+    ) -> None:
+        """Load an archive using mmap (default), preload (mmap=False), or
+        read-only HAL streaming (mode="file_async"). Explicit mmap and mode
+        arguments are mutually exclusive. The index retains the file handle.
+        """
+        ...
+
     def create_archive_file(
         self,
         file_path: str,
diff --git a/runtime/bindings/python/tests/io_runtime_test.py b/runtime/bindings/python/tests/io_runtime_test.py
index 3d07e30..fc65791 100644
--- a/runtime/bindings/python/tests/io_runtime_test.py
+++ b/runtime/bindings/python/tests/io_runtime_test.py
@@ -5,6 +5,8 @@
 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 
 import array
+from collections.abc import Callable
+import gc
 import logging
 import numpy as np
 from pathlib import Path
@@ -15,7 +17,7 @@
 import iree.runtime as rt
 
 
-TEST_COMPILED = None
+TEST_COMPILED: bytes | None = None
 TEST_ASM = r"""
 util.global private @a0 = #flow.parameter.named<"a"::"a0"> : tensor<4xi64>
 util.global private @a1 = #flow.parameter.named<"a"::"a1"> : tensor<4xi64>
@@ -31,22 +33,23 @@
 """
 
 
-def compile_mm_test():
+def compile_mm_test() -> bytes:
     global TEST_COMPILED
     if not TEST_COMPILED:
         TEST_COMPILED = iree.compiler.compile_str(
             TEST_ASM,
             target_backends=iree.compiler.core.DEFAULT_TESTING_BACKENDS,
         )
+    assert TEST_COMPILED is not None, "Expected compiled module bytes"
     return TEST_COMPILED
 
 
-def create_mm_test_module(instance):
+def create_mm_test_module(instance: rt.VmInstance) -> rt.VmModule:
     binary = compile_mm_test()
     return rt.VmModule.copy_buffer(instance, binary)
 
 
-def create_index_from_arrays(**kwargs) -> rt.ParameterIndex:
+def create_index_from_arrays(**kwargs: np.ndarray) -> rt.ParameterIndex:
     idx = rt.ParameterIndex()
     for key, value in kwargs.items():
         idx.add_buffer(key, value)
@@ -54,12 +57,76 @@
 
 
 class ParameterTest(unittest.TestCase):
-    def setUp(self):
+    def setUp(self) -> None:
         self.instance = rt.VmInstance()
         self.device = rt.get_device(iree.compiler.core.DEFAULT_TESTING_DRIVER)
         self.config = rt.Config(device=self.device)
 
-    def test_index_provider_module(self):
+    def _create_async_archive_provider(
+        self, path: Path, scope: str
+    ) -> rt.ParameterProvider:
+        index = rt.ParameterIndex()
+        index.load(str(path), mode="file_async")
+        handle, _ = index.items()[0][1].file_storage
+        self.assertTrue(handle.is_async)
+        return index.create_provider(scope=scope)
+
+    def _create_archive_provider_after_caller_close(
+        self, path: Path, scope: str
+    ) -> rt.ParameterProvider:
+        index = rt.ParameterIndex()
+        with open(path, "rb") as source:
+            handle = rt.FileHandle.wrap_fd(source.fileno())
+            index.load_from_file_handle(handle, "irpa")
+        # The original Python file is closed before any parameter use.
+        return index.create_provider(scope=scope)
+
+    def _run_archive_provider_module(
+        self,
+        directory: Path,
+        expected: list[np.ndarray],
+        create_provider: Callable[[Path, str], rt.ParameterProvider],
+    ) -> None:
+        providers = []
+        for scope, arrays in (("a", expected[:2]), ("b", expected[2:])):
+            path = directory / f"{scope}.irpa"
+            rt.save_archive_file(
+                {f"{scope}{i}": value for i, value in enumerate(arrays)}, path
+            )
+            providers.append(create_provider(path, scope))
+        parameter_module = rt.create_io_parameters_module(self.instance, *providers)
+        del providers
+        gc.collect()
+        modules = rt.load_vm_modules(
+            parameter_module,
+            rt.create_hal_module(self.instance, self.device),
+            create_mm_test_module(self.instance),
+            config=self.config,
+        )
+        actual = modules[-1].echo()
+        for i, (want, got) in enumerate(zip(expected, actual)):
+            np.testing.assert_array_equal(want, got, err_msg=f"parameter {i}")
+
+    def _check_archive_provider_module(
+        self, create_provider: Callable[[Path, str], rt.ParameterProvider]
+    ) -> None:
+        expected = [
+            np.arange(n, dtype=np.int64) + i * 10 for i, n in enumerate((4, 4, 8, 8))
+        ]
+
+        with tempfile.TemporaryDirectory() as td:
+            self._run_archive_provider_module(Path(td), expected, create_provider)
+            gc.collect()
+
+    def test_async_archive_provider_module(self) -> None:
+        self._check_archive_provider_module(self._create_async_archive_provider)
+
+    def test_archive_provider_after_caller_close(self) -> None:
+        self._check_archive_provider_module(
+            self._create_archive_provider_after_caller_close
+        )
+
+    def test_index_provider_module(self) -> None:
         a0 = np.asarray([1] * 4, dtype=np.int64)
         a1 = np.asarray([2] * 4, dtype=np.int64)
         b0 = np.asarray([3] * 8, dtype=np.int64)
diff --git a/runtime/bindings/python/tests/io_test.py b/runtime/bindings/python/tests/io_test.py
index 1efe308..acce688 100644
--- a/runtime/bindings/python/tests/io_test.py
+++ b/runtime/bindings/python/tests/io_test.py
@@ -7,6 +7,7 @@
 import array
 import gc
 import logging
+import os
 import numpy as np
 from pathlib import Path
 import tempfile
@@ -157,6 +158,76 @@
             verify_archive_from_fd(file_path)
             gc.collect()
 
+    def testArchiveFileAsync(self):
+        with tempfile.TemporaryDirectory() as td:
+            path = Path(td) / "archive.irpa"
+            expected = np.arange(24, dtype=np.int64)
+            rt.save_archive_file({"array": expected}, path)
+            index = rt.ParameterIndex()
+            index.load(str(path), mode="file_async")
+            entry = dict(index.items())["array"]
+            handle, offset = entry.file_storage
+            self.assertTrue(handle.is_fd)
+            self.assertTrue(handle.is_async)
+            self.assertFalse(handle.is_host_allocation)
+            self.assertEqual(entry.length, expected.nbytes)
+            self.assertGreaterEqual(offset, 0)
+            fd = handle.fd
+            del entry, index
+            gc.collect()
+            # The Python handle keeps the descriptor alive after the index dies.
+            self.assertEqual(os.fstat(fd).st_size, path.stat().st_size)
+            del handle
+            gc.collect()
+            with self.assertRaises(OSError):
+                os.fstat(fd)
+
+    def testArchiveLegacyMmapModes(self):
+        def verify(path, expected, *args, **kwargs):
+            index = rt.ParameterIndex()
+            index.load(str(path), *args, **kwargs)
+            entry = dict(index.items())["array"]
+            handle, _ = entry.file_storage
+            self.assertTrue(handle.is_host_allocation)
+            self.assertFalse(handle.is_async)
+            np.testing.assert_array_equal(
+                index_entry_as_array(entry, expected), expected
+            )
+
+        with tempfile.TemporaryDirectory() as td:
+            path = Path(td) / "archive.irpa"
+            expected = np.arange(24, dtype=np.int64)
+            rt.save_archive_file({"array": expected}, path)
+            verify(path, expected)
+            for mmap in (True, False):
+                with self.subTest(mmap=mmap):
+                    verify(path, expected, mmap=mmap)
+                    verify(path, expected, "irpa", True, False, mmap)
+            gc.collect()
+
+    def testArchiveInvalidMode(self):
+        index = rt.ParameterIndex()
+        with self.assertRaisesRegex(ValueError, "unsupported parameter file mode"):
+            index.load("missing.irpa", mode="invalid")
+        for mmap in (True, False):
+            with self.subTest(mmap=mmap):
+                with self.assertRaisesRegex(ValueError, "mode and mmap"):
+                    index.load("missing.irpa", mode="file_async", mmap=mmap)
+        self.assertEqual(len(index), 0)
+
+    def testArchiveAsyncInvalidAccess(self):
+        index = rt.ParameterIndex()
+        for readable, writable in ((False, False), (False, True), (True, True)):
+            with self.subTest(readable=readable, writable=writable):
+                with self.assertRaisesRegex(ValueError, "requires read-only access"):
+                    index.load(
+                        "missing.irpa",
+                        mode="file_async",
+                        readable=readable,
+                        writable=writable,
+                    )
+        self.assertEqual(len(index), 0)
+
     def testParameterIndexEntryFromToNumpy(self):
         array = np.array([[1, 2], [3, 4]], dtype=np.int32)
         index = rt.ParameterIndex()