From 9cdff5f5c30570d7b99ced39e2ab923490b2398d Mon Sep 17 00:00:00 2001 From: Tobias Fuchs Date: Wed, 18 Nov 2026 15:57:27 +0000 Subject: [PATCH 1/2] [Python] Add the configuration objects to iree.core Add `iree.core.config`, the configuration that is recorded with an imported or compiled model: * `CompileConfig` describes how a model is compiled (target device, flags, flag templates, conditional flags) and what running the compiled artifact requires (drivers, lead allocator, runtime flags). It loads from and saves to JSON. Loading rejects unknown keys, so that a misspelled key does not go unnoticed. * `ImportConfig` is the importer-side configuration. An importer subclasses it to record its own settings and the files it needs at runtime, and registers the subclass for its framework with `register_import_config`, so that the right class can be rebuilt when saved metadata is loaded. A framework has exactly one class: registering a second one is an error instead of depending on import order. Nothing uses these classes yet: the compiler and runtime layers built on them follow. The classes are loaded with dacite, which becomes the first third-party dependency of the iree-base-core wheel. `pyproject.toml` declares it as a version range; builds and CI install it pinned to an exact version with hashes (`requirements.txt`). The requirements of the Bazel pip hub become a generated lock with hashes as well. It pins the dependencies of the wheel and the other packages that Bazel targets use, which `build_tools/bazel/requirements.in` lists: so far only numpy, which the hub already had without a pin. The pkgci unit test job now runs every test of the package against the installed wheel. Assisted-by: Claude Code Signed-off-by: Tobias Fuchs --- .github/workflows/pkgci_unit_test.yml | 4 +- build_tools/bazel/requirements.in | 13 + build_tools/bazel/requirements.txt | 149 +++++++++- core/python/BUILD.bazel | 22 ++ core/python/CMakeLists.txt | 9 + core/python/iree/core/_paths.py | 23 ++ core/python/iree/core/config.py | 222 +++++++++++++++ core/python/pyproject.toml | 4 +- core/python/requirements.txt | 4 + core/python/test/config_test.py | 382 ++++++++++++++++++++++++++ 10 files changed, 829 insertions(+), 3 deletions(-) create mode 100644 build_tools/bazel/requirements.in create mode 100644 core/python/iree/core/_paths.py create mode 100644 core/python/iree/core/config.py create mode 100644 core/python/test/config_test.py diff --git a/.github/workflows/pkgci_unit_test.yml b/.github/workflows/pkgci_unit_test.yml index 44de2c883bd3..eb0e281d2526 100644 --- a/.github/workflows/pkgci_unit_test.yml +++ b/.github/workflows/pkgci_unit_test.yml @@ -66,7 +66,9 @@ jobs: echo "This run has no iree-base-core wheel, skipping its tests" exit 0 fi - python core/python/test/package_test.py + for test in core/python/test/*_test.py; do + python "${test}" + done - name: Validate runtime wheel run: | source ${VENV_DIR}/bin/activate diff --git a/build_tools/bazel/requirements.in b/build_tools/bazel/requirements.in new file mode 100644 index 000000000000..8b4661f6308f --- /dev/null +++ b/build_tools/bazel/requirements.in @@ -0,0 +1,13 @@ +# Version ranges for the Bazel pip hub (@pip, see MODULE.bazel). Bazel reads +# only requirements.txt: a lock file generated from this file and +# core/python/pyproject.toml that pins every package to an exact version with +# hashes. +# +# List here each package that a Bazel target uses through @pip and that +# core/python/pyproject.toml does not declare. After a change here or in that +# pyproject.toml, regenerate requirements.txt with the command at its top, from +# this directory. + +# Used by runtime/bindings/python for the numpy headers, which numpy 2 moved to +# numpy/_core/include, and by tools/test. +numpy>=2.0.0 diff --git a/build_tools/bazel/requirements.txt b/build_tools/bazel/requirements.txt index 24ce15ab7ead..50b32644bbdf 100644 --- a/build_tools/bazel/requirements.txt +++ b/build_tools/bazel/requirements.txt @@ -1 +1,148 @@ -numpy +# This file was autogenerated by uv via the following command: +# uv pip compile --universal --generate-hashes --python-version 3.11 --only-binary :all: requirements.in ../../core/python/pyproject.toml -o requirements.txt +dacite==1.9.2 \ + --hash=sha256:053f7c3f5128ca2e9aceb66892b1a3c8936d02c686e707bee96e19deef4bc4a0 \ + --hash=sha256:6ccc3b299727c7aa17582f0021f6ae14d5de47c7227932c47fec4cdfefd26f09 + # via iree-base-core (../../core/python/pyproject.toml) +numpy==2.4.6 ; python_full_version < '3.12' \ + --hash=sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1 \ + --hash=sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4 \ + --hash=sha256:043191bfa8eab18c776647b62723ac9dddece59743b13f49b2016094129c2b3f \ + --hash=sha256:06ca2f61ec4385a07a6977c55ba998a4466c123642b4a32694d3128fce18c079 \ + --hash=sha256:0a041d3d761dc3c35cc56ce0351506a02bcbc25f7b169f652435141a17db9096 \ + --hash=sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47 \ + --hash=sha256:0c9136e14ed34a9e343a31c533d78a9813a69a3148332bce5e9821cb2f996e66 \ + --hash=sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d \ + --hash=sha256:112b06a867b235ef466ed3508ddf0238050df9c727cafb5301ac385b899189a1 \ + --hash=sha256:17f9ade344e7d9b464a084d69bcf18fc691cb1db67c62ed80820bf4926d78f0e \ + --hash=sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147 \ + --hash=sha256:1e978ec1e8bd0e0e4de6bb75de9d30cbb74db6b6a2bb727618613703ca0167dd \ + --hash=sha256:25c692919ac5a01f170a3bfcd62d745b24fd095c353d50812637d6fcab442e75 \ + --hash=sha256:260a5d70215b61ab4fadf5c7baacd64821842975eea312125ed3c39a6391b063 \ + --hash=sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73 \ + --hash=sha256:29a287e0cf63ff528da061de6b9f64a4618da591ca1046aafc54062e40ca7eab \ + --hash=sha256:29cb7f67d10b479ff07c17d33e39f78c07f71c40ef30d63c153d340e96cd3fb4 \ + --hash=sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41 \ + --hash=sha256:33111801a01c12a8a1e3721f0a9232f8cfc8ae2c6b7098167e6f623c6073f402 \ + --hash=sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698 \ + --hash=sha256:38efbc8de75c7a0fc1ac190162d892787f3f47b57cc291231aafee36b80982b7 \ + --hash=sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8 \ + --hash=sha256:40fdc1ae7125e518ea98e53e69a4ebc27e1fd50510c47b7ea130cf21e5e1d42b \ + --hash=sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8 \ + --hash=sha256:511dbaf848decaaaf4b4ca48032619fb3138710c4bf7da7617765edad1ef96b0 \ + --hash=sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662 \ + --hash=sha256:56b39e5e0622a09a25bf5baf62f4bcf0cb8a41ae6e2819cf49bbc5a74c083f91 \ + --hash=sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0 \ + --hash=sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f \ + --hash=sha256:6180d8b35af935aed8ece3a85e0a43f87393ae0ac87c8d2c8bd2c993f7270ef3 \ + --hash=sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f \ + --hash=sha256:68bb27509ac1b9a3443094260f6326150663b06abe40b73a2f81160623da5b67 \ + --hash=sha256:6f41ae150c4e32db4f3310cdaf64b1593a03dbabe29eec77fc9b50fe64061df6 \ + --hash=sha256:7265a2f3d436e54ef9f2b52b5c937e6be778781bd97a590319d7348f1c1ca997 \ + --hash=sha256:72fbe16c6fac95aedf5937fa873445cec2110be35d8a4e9433d7501fd98dae6b \ + --hash=sha256:7d92c3819208a60205a12a245c91ad70cb0a85336659b19b834205573ac8456e \ + --hash=sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538 \ + --hash=sha256:81a1cca95ed5bb92aa8b10dd2cdc9a0d3853a50fad926c28b5d7e8ea54389627 \ + --hash=sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93 \ + --hash=sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02 \ + --hash=sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853 \ + --hash=sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c \ + --hash=sha256:9cd5ffd25db4e7ba6a375693b3fc0fc1791ec636c17db3720da19bde7180ec43 \ + --hash=sha256:a0df0043bdb289bde1f62da130d20df23d58b45429f752bc7a8fc5325a225ecd \ + --hash=sha256:a2c306dea656c12c68f51f4cea133cbe78ca7435eb28c735eac1d3ebe73be6e8 \ + --hash=sha256:a7830bab239b79cda9c08c2da014761cafb48da6150e1da17ac06283f43b6089 \ + --hash=sha256:a7c711e21628b52034bb5ab8d1bce291f752fcc5e92accc615778acee1ff4778 \ + --hash=sha256:aaf159caa35993cb1f56fb9b8e4610d35758e7ca005412eb1daa856a78c9c4b1 \ + --hash=sha256:ae506e6902902557576a26ff33eda8695e7ecb3cb36c3b573a0765dee114ebdb \ + --hash=sha256:b507f5c4c1d508876d1819b6bf9a49d365b96320b5d4993426b33a23ca4b8261 \ + --hash=sha256:bf162abab1c1a736333192707cef898e735a5ca00f38f27eeedf44b39d9e85eb \ + --hash=sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a \ + --hash=sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8 \ + --hash=sha256:c4fc99836233ea196540b17ab0983aff60ed07941751930f5f4d05bc3b3b7359 \ + --hash=sha256:d581b735e177fdcdce6fed8e7e8880a3fb6ee4e3653a3ac6af01c6f4c03effc5 \ + --hash=sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7 \ + --hash=sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751 \ + --hash=sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8 \ + --hash=sha256:dfa20cc6ca228e6b155b11da03825975ce66aea520985dbbddf0f2a5a495c605 \ + --hash=sha256:e3e5193ef5a3dc73bceee50f7fdc2c90dbb76c42df8d8fae3d1067a583df579e \ + --hash=sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45 \ + --hash=sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2 \ + --hash=sha256:e85b752a1e912b70eaad4fafbd4d1238007ab221de2009b9a2f5ae7461239895 \ + --hash=sha256:eaf7fa2de5c0be8ae6ff8e9bea2ccd725e980541244521d8d4b5f3354a27babe \ + --hash=sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb \ + --hash=sha256:ece3d2cfe132e7d51f44a832b303895e6f2d499c5e74dfbdb06ee246147a304a \ + --hash=sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577 \ + --hash=sha256:ede83e07a75dd06bc501566c1eca2afc0d61677c1472ac9ad93fdee6e638a48d \ + --hash=sha256:ef4aea96ce4d3b074422cb4f2f64e216bf9e213004bb58ecfdf50ea02ea8eb9a \ + --hash=sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda \ + --hash=sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6 \ + --hash=sha256:f74a575920ab21fe304421a3fc28793d82e299cae9eccb37084e9fc7f3617c20 + # via -r requirements.in +numpy==2.5.5 ; python_full_version >= '3.12' \ + --hash=sha256:08f1b9abf1707fa89c125aaa17e78389c063fb20ce37a141b47821e996f4a1db \ + --hash=sha256:095113ee2ceab6a9501b184eff5ea806973d3a63d74a8cbc15e4911e754da9c1 \ + --hash=sha256:10396f7c5ebc37d8f3cbdec44e3313912ccc2dc5841cc905de5de54ebbe8e2d3 \ + --hash=sha256:178cb1eaed819b2cb4e398c554b0776d1499f307e30cb58b9bae1921de35dae6 \ + --hash=sha256:1c24be6a82f5f257afc4dbefde4c3b56dee02146dfed2be2811940e79576b237 \ + --hash=sha256:20145b11776d2f7570cd61351b156a51d3a341822282095baa819d87272bc710 \ + --hash=sha256:228e3d90e967495d61ddc79dd64e95267aae3bcf1b1c516a6186429106a0b444 \ + --hash=sha256:229743571f901a082f031f511dc4f926b4b4a714075d98b1ff2af62d836365ac \ + --hash=sha256:263b2aa236d752b18f90c5107137d24b2e3856d7db37725609f0ab5bcdb58881 \ + --hash=sha256:2a9c502cdb9a3050ac1686774624cc278658b11f72e11b971a3a8542d6ded357 \ + --hash=sha256:2abd39cfbb3d2af11e9bc8cc92b08cd089b0975fe9b1a30c8b7c740c67d397ce \ + --hash=sha256:2efb2ae4e0414b6bd636dde7235c158cd65dd52891ff64a320a4847a8ce7400f \ + --hash=sha256:31e5be6cd4b896004cb9e416741612ade530fc9a04bceca5219cf66a675113b4 \ + --hash=sha256:32dce94d74bb4d5bb058d65b0d9dad7fa61d07ff9375fd7695d8aa7ea82ee73d \ + --hash=sha256:3cedc2980b45794a6a2cfee9c8c3a80f04517082cc1d387e4cc895506c481696 \ + --hash=sha256:3d59ab8f6bfc4ffd29b0f558450e17922c1bc88459882e37726fbcd5834afbfd \ + --hash=sha256:410eab02c6718cb42d06ccbb8604659f3522d2ce06ae70cacd5042092659f5af \ + --hash=sha256:4302902ebf82d37f446664757be59db53587822c8b35f16368ca69fe66ec4315 \ + --hash=sha256:479e43c183049ec1a820eeb36549e493924f56b3e893a1d5865d0fff12abad47 \ + --hash=sha256:567994389edd2963b643d63d826138402a63401176f1daf84dbb3204eb838b39 \ + --hash=sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf \ + --hash=sha256:5e202d5facc9c0681834018062466d0b3eabd48c540c3570f72905c97f641a90 \ + --hash=sha256:704d819265e5d1064d932968e9ee85fff2103ccc78c05b878c06943ba27b8507 \ + --hash=sha256:7ca51125c76817de53473dae31ddc17213776472761bea9cca68a1a0037a4827 \ + --hash=sha256:7da9a248f149cfbb220c6da964a59c8d051d516704f7758acfb81eb382a05d97 \ + --hash=sha256:7e71ac4284c700afa654e2d15b1b174166710dca932f24045e5dc92001b5bda0 \ + --hash=sha256:7fb87c4bcc73850ef433a0c42f096b010d3d3d284e9d00028bb030b43df3d078 \ + --hash=sha256:824025655df929268bfe6b47ed91a00d14209a6f760847cf150be446829e1ce4 \ + --hash=sha256:84dfb1611993a3525b250c955b1e2ebab6ce0ed36e4ab4dd5746432dd362fb5d \ + --hash=sha256:86868185bf4b6c4e5a8628ac42cfa165cd9530266c731f7dd1d11b4ad7e7cd1c \ + --hash=sha256:919eb420662b0b4ba34889df503f3d5329775b0c1d5f7e5f5af4fba8315b1e30 \ + --hash=sha256:9c3e1ac3cd5d3329f4d38709ff4c21f0621bbe8779c094d6de8ec8347246fcdc \ + --hash=sha256:9f44875964889bd9088cf838d191b58c04088d10b4dc9b140e9da2431ecfbb60 \ + --hash=sha256:a0750f2156d53446caca85663d0b65d67214e1664b9050454a731ea1418d176a \ + --hash=sha256:a207eb88a18e30add597c366c1db7e79f48fc94084b8e7dbd0eefb95a645db12 \ + --hash=sha256:a3856a97e48ed8371c680fb04120b99fbcc29f2076ebe6dc3deb34f77947c5ca \ + --hash=sha256:ab3ff087826c49d07953d0219eb00663ce5b1a0ef0a6b757e1ac041b09387428 \ + --hash=sha256:ac910558645a4b006f70596b450712b8564730c1b2ac10291fcedd656d321ec0 \ + --hash=sha256:ad0c8b963f9281f2eb118e283eb61964c716c8e344ed8e8c309b49c586d41ed1 \ + --hash=sha256:ae2b8285d0b4eed24739c3ca9ec0fa424a0247489c01e1d5fe2815a599e11d33 \ + --hash=sha256:ae9cfe4e985139c5f2db69d4310de7348bd0abc02cfdc06991c4419065f6fdca \ + --hash=sha256:b3d328eebe0056c634878c251131d73d74e0c4af317a3aea718816d6fa0bb963 \ + --hash=sha256:b5d08742de581c9eb61102768ccca125a2982913de399611b56981a07278de74 \ + --hash=sha256:b6e30929e3443f46aa7be2749fb003fefbbad6b6a1e2168bf8850a55b657914a \ + --hash=sha256:b6ecbc1ff292c6799067d8064a4dd35cd25ba9d1a24aa41dd635d701691a49b5 \ + --hash=sha256:b7dd0287b6cdd35a27d5678a56b1bc508ff206c2b78b30b4821dd5c3197b393a \ + --hash=sha256:b96e9ee49ccbdb5676359f852a4497f7a9c5df6c377d8877f5330d6fd3ff42e4 \ + --hash=sha256:bea7de36bb304a850710c1dfbb35e7cdb9a005928106a3adfc6dc3a753469dec \ + --hash=sha256:bf6fa5a4d73b3a9699a57b8824d4863acde7241808a5305882222843537f02a2 \ + --hash=sha256:c48960d420e90cf305cb1fde0d4e6082cc90512cda87a9acf0b6e04e91cf4abe \ + --hash=sha256:cc6eb7502facce90349b4097a26821af224aaa0ab36e78304711cdb544352882 \ + --hash=sha256:d0c7c0dfabdcb7cde080b7c9ef301c7533e90110198b39965141a903c7dddcf8 \ + --hash=sha256:d64daa409e9b1ac818b0c59e47b005f802e130c8281e40c6a2f7e70c43f75e0f \ + --hash=sha256:d7d9be35d50366fe5ac28188364154c9e1e22ad1b977a06c9465c0680c8eeefe \ + --hash=sha256:dec156cda7322bcb1479ca992794705fe226a911b0ffebe13bff97fa1f3be63c \ + --hash=sha256:e0608d1585557b68dcb6a70a41654f7536567960afad79d91752d2863b242b68 \ + --hash=sha256:e0b87886bb45621d9279dad4ab9f2d154b5db0b019d378c107b8f71527b06a4a \ + --hash=sha256:e0cf407a83118faf0463ade48a4533982f1737c7c58aac29e08855f7d9ad2977 \ + --hash=sha256:e10e81d1db6c8fa507f61bebfd1ea383971dbc40c2005ed4db88fac5538b1ef6 \ + --hash=sha256:e99bf8a3d54693f2063fa6c7d13955d460a9f543d9dbc80e69a92da288259b28 \ + --hash=sha256:ef2a874cc70e2132c1c499268bdc34e211a715e481bc33c97b8a0190f2559295 \ + --hash=sha256:f5e8603f0892d1b848e12124863b5b29af72383ee9b25ddc6fe4967d4c1ee6ef \ + --hash=sha256:f6622e32cb46c60bee3b2c7dd7f5c22bdc86fcb8630336b4822ec81c3986111a \ + --hash=sha256:f82a7567c590ff266f8c18fd527a0662edde074de11be256541a656e274f2b05 \ + --hash=sha256:fd47c92e0d1e53f9498b1a30305072434fbae6b5a305cbcab514f959e9ce0fab \ + --hash=sha256:ff5c1ab54a637c0adcdbb69ad10e5c4f1c4dedba69c0d1de383249b70c36908f + # via -r requirements.in diff --git a/core/python/BUILD.bazel b/core/python/BUILD.bazel index b9cc9ca57ed0..3cb749fea607 100644 --- a/core/python/BUILD.bazel +++ b/core/python/BUILD.bazel @@ -18,12 +18,15 @@ package( PY_SRCS = enforce_glob( [ "iree/core/__init__.py", + "iree/core/_paths.py", + "iree/core/config.py", ], include = ["iree/core/**/*.py"], ) PY_TESTS = enforce_glob( [ + "test/config_test.py", "test/package_test.py", ], include = ["test/**/*.py"], @@ -35,6 +38,16 @@ py_library( name = "core", srcs = PY_SRCS, imports = ["."], + deps = ["@pip//dacite"], +) + +py_test( + name = "config_test", + size = "small", + srcs = ["test/config_test.py"], + legacy_create_init = False, + main = "test/config_test.py", + deps = [":core"], ) py_test( @@ -63,6 +76,15 @@ if(IREE_BUILD_TESTS) ERROR_STRIP_TRAILING_WHITESPACE ) if(_IREE_CORE_REQUIREMENTS_RESULT EQUAL 0) + iree_local_py_test( + NAME + config_test + SRC + "test/config_test.py" + PACKAGE_DIRS + "${CMAKE_CURRENT_SOURCE_DIR}" + ) + iree_local_py_test( NAME package_test diff --git a/core/python/CMakeLists.txt b/core/python/CMakeLists.txt index 189c899b7127..e27dec6adfcc 100644 --- a/core/python/CMakeLists.txt +++ b/core/python/CMakeLists.txt @@ -20,6 +20,15 @@ if(IREE_BUILD_TESTS) ERROR_STRIP_TRAILING_WHITESPACE ) if(_IREE_CORE_REQUIREMENTS_RESULT EQUAL 0) + iree_local_py_test( + NAME + config_test + SRC + "test/config_test.py" + PACKAGE_DIRS + "${CMAKE_CURRENT_SOURCE_DIR}" + ) + iree_local_py_test( NAME package_test diff --git a/core/python/iree/core/_paths.py b/core/python/iree/core/_paths.py new file mode 100644 index 000000000000..2e8c8eb909c1 --- /dev/null +++ b/core/python/iree/core/_paths.py @@ -0,0 +1,23 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Helpers for the paths held by configuration and result objects.""" + +from pathlib import Path + + +def collect_paths(data: object) -> tuple[Path, ...]: + """Collect every ``Path`` in a nested structure of dicts, lists and tuples. + + Meant for the result of ``dataclasses.asdict``. + """ + if isinstance(data, Path): + return (data,) + if isinstance(data, dict): + return tuple(path for value in data.values() for path in collect_paths(value)) + if isinstance(data, (list, tuple)): + return tuple(path for item in data for path in collect_paths(item)) + return () diff --git a/core/python/iree/core/config.py b/core/python/iree/core/config.py new file mode 100644 index 000000000000..91d3fb003029 --- /dev/null +++ b/core/python/iree/core/config.py @@ -0,0 +1,222 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Configuration objects recorded with an imported or compiled model.""" + +import dataclasses +import json +import shutil +from collections.abc import Callable +from pathlib import Path +from typing import Self, TypeVar + +from dacite import Config, DaciteError, from_dict + +from ._paths import collect_paths + +__all__ = [ + "CompileConfig", + "ConditionalRule", + "ImportConfig", + "register_import_config", + "resolve_import_config_class", +] + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class ConditionalRule: + """Flags that are only added when a condition holds. + + ``when`` maps the name of a condition to its arguments, for example + ``{"arch_in": ["aarch64", "arm64"]}``. ``add`` lists the flags to add when + the condition holds. + """ + + when: dict[str, list[str]] + add: list[str] = dataclasses.field(default_factory=list) + + +def _copy_path_into(src: Path, dst_dir: Path) -> Path: + """Copy a file or directory into ``dst_dir`` and return the copied path.""" + if src.name in ("", ".."): + # Copying "." or ".." would copy a whole directory tree under no name. + raise ValueError(f"cannot copy {src!r}: it does not name a file or directory") + dst = dst_dir / src.name + if src.resolve() == dst.resolve(): + return dst + if src.is_dir(): + shutil.copytree(src, dst, dirs_exist_ok=True) + else: + shutil.copy2(src, dst) + return dst + + +def _iter_direct_path_fields(obj: object) -> tuple[tuple[str, Path], ...]: + """Return the ``(field_name, path)`` pairs for each direct ``Path`` field.""" + assert dataclasses.is_dataclass(obj) and not isinstance(obj, type) + fields: list[tuple[str, Path]] = [] + for field in dataclasses.fields(obj): + value = getattr(obj, field.name) + if isinstance(value, Path): + fields.append((field.name, value)) + return tuple(fields) + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class ImportConfig: + """ + Importer-side configuration recorded alongside an imported model. + """ + + framework: str + + def get_artifacts(self) -> tuple[Path, ...]: + """Return importer-owned files or directories needed at runtime.""" + return collect_paths(dataclasses.asdict(self)) + + def copy_to(self, dst_dir: Path) -> Self: + """Copy the files that the ``Path`` fields refer to into ``dst_dir``. + + Only fields that are a ``Path`` themselves are copied, not paths inside + lists or nested objects. + + Raises: + ValueError: If two different files would get the same name in + ``dst_dir``, ignoring case. + """ + path_fields = _iter_direct_path_fields(self) + first_with_name: dict[str, tuple[str, Path]] = {} + for field_name, path in path_fields: + # Names that differ only in case are one file on the file systems + # that macOS and Windows use by default. + other_field, other = first_with_name.setdefault( + path.name.casefold(), (field_name, path) + ) + if other.resolve() != path.resolve(): + raise ValueError( + f"cannot copy {other_field}={other} and {field_name}={path} " + f"into {dst_dir}: both would be named {path.name}, " + "ignoring case" + ) + updates = { + field_name: _copy_path_into(path, dst_dir) + for field_name, path in path_fields + } + if not updates: + return self + return dataclasses.replace(self, **updates) + + +_ImportConfigT = TypeVar("_ImportConfigT", bound=ImportConfig) + + +# Maps ``ImportConfig.framework`` string to the concrete subclass. +_IMPORT_CONFIG_CLASSES: dict[str, type[ImportConfig]] = {} + + +def register_import_config( + framework: str | list[str], +) -> Callable[[type[_ImportConfigT]], type[_ImportConfigT]]: + """ + Decorator to register a concrete ImportConfig subclass for a given + framework or list of frameworks. + + Raises: + TypeError: If the decorated class is not an ImportConfig subclass. + ValueError: If a framework is already registered to another class. + """ + frameworks = [framework] if isinstance(framework, str) else framework + + def decorator(cls: type[_ImportConfigT]) -> type[_ImportConfigT]: + if not (isinstance(cls, type) and issubclass(cls, ImportConfig)): + raise TypeError(f"{cls!r} is not a subclass of ImportConfig") + for fw in frameworks: + registered = _IMPORT_CONFIG_CLASSES.get(fw) + if registered is not None and registered is not cls: + raise ValueError( + f"framework {fw!r} is already registered to " + f"{registered.__qualname__}" + ) + for fw in frameworks: + _IMPORT_CONFIG_CLASSES[fw] = cls + return cls + + return decorator + + +def resolve_import_config_class(framework: str) -> type[ImportConfig]: + """Return the concrete subclass for ``framework``, or the base class.""" + return _IMPORT_CONFIG_CLASSES.get(framework, ImportConfig) + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class CompileConfig: + """Configuration for compiling a model and for running the compiled artifact.""" + + # Target device to use by iree-compile + target_device: list[str] + + # Static flags to pass to iree-compile + flags: list[str] = dataclasses.field(default_factory=list) + + # Flag templates: placeholders such as {target_triple} are filled in when + # the model is compiled + dynamic_flags: list[str] = dataclasses.field(default_factory=list) + + # Conditional flags are rules for adding flags only in certain cases + conditional_flags: list[ConditionalRule] = dataclasses.field(default_factory=list) + + # Whether this compilation pipeline can compile IR whose parameters live in + # an archive instead of the module. When false, the importer has to leave + # the weights in the module. + supports_external_parameters: bool = True + + # Runtime configuration: the drivers to create devices for, one device per + # driver, in this order + drivers: list[str] + + # Index into `drivers` of the lead device, which makes the allocations that + # may be placed on any of the devices. Only used with more than one driver. + # The runtime tools take it as `--device_lead_allocator`. + device_lead_allocator: int = 0 + + # Extra flags to be passed to the runtime + runtime_flags: list[str] = dataclasses.field(default_factory=list) + + # Importer to use for a framework instead of its default one, by framework + # name + custom_importers: dict[str, str] = dataclasses.field(default_factory=dict) + + @classmethod + def load(cls, file: str | Path) -> Self: + """Load a configuration from a JSON file. + + A key that matches no field is an error. + """ + file = Path(file) + try: + # utf-8-sig also reads files that start with a byte order mark. + with file.open("r", encoding="utf-8-sig") as f: + data = json.load(f) + if not isinstance(data, dict): + raise ValueError("expected a JSON object") + return from_dict( + data_class=cls, data=data, config=Config(cast=[tuple], strict=True) + ) + except (DaciteError, ValueError) as e: + # Errors in the JSON and in its encoding are ValueErrors. + e.add_note(f"while loading compile config from {file}") + raise + + def to_dict(self) -> dict: + """Return the configuration as JSON-serializable data.""" + return dataclasses.asdict(self) + + def save(self, file: str | Path) -> None: + """Write the configuration to a JSON file that ``load`` reads back.""" + # Serialize first: a failure must not leave a truncated file behind. + text = json.dumps(self.to_dict(), indent=4) + Path(file).write_text(text, encoding="utf-8") diff --git a/core/python/pyproject.toml b/core/python/pyproject.toml index 04d7975a2e1c..6c9eb46ce28d 100644 --- a/core/python/pyproject.toml +++ b/core/python/pyproject.toml @@ -19,7 +19,9 @@ classifiers = [ ] # Version ranges. requirements.txt pins them with hashes for builds and CI: # regenerate it after a change here, with the command at its top. -dependencies = [] +dependencies = [ + "dacite>=1.9.2", +] # Computed by setup.py. dynamic = ["version"] diff --git a/core/python/requirements.txt b/core/python/requirements.txt index 8e92fe031234..e1551faa7e88 100644 --- a/core/python/requirements.txt +++ b/core/python/requirements.txt @@ -1,2 +1,6 @@ # This file was autogenerated by uv via the following command: # uv pip compile --universal --generate-hashes --python-version 3.11 --only-binary :all: pyproject.toml -o requirements.txt +dacite==1.9.2 \ + --hash=sha256:053f7c3f5128ca2e9aceb66892b1a3c8936d02c686e707bee96e19deef4bc4a0 \ + --hash=sha256:6ccc3b299727c7aa17582f0021f6ae14d5de47c7227932c47fec4cdfefd26f09 + # via iree-base-core (pyproject.toml) diff --git a/core/python/test/config_test.py b/core/python/test/config_test.py new file mode 100644 index 000000000000..5ebfa0b07fe7 --- /dev/null +++ b/core/python/test/config_test.py @@ -0,0 +1,382 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Tests for iree.core.config.""" + +import dataclasses +import json +import tempfile +import unittest +import uuid +from pathlib import Path +from typing import Any + +from dacite import DaciteError, UnexpectedDataError + +from iree.core.config import ( + CompileConfig, + ConditionalRule, + ImportConfig, + register_import_config, + resolve_import_config_class, +) + +DUMMY_FRAMEWORK = "dummy" + + +@register_import_config(DUMMY_FRAMEWORK) +@dataclasses.dataclass(frozen=True, kw_only=True) +class DummyImportConfig(ImportConfig): + """Subclass that adds fields, including ``Path`` ones.""" + + tokenizer: Path + generation_config_dir: Path + extra_setting: str = "default" + + +class TempDirTestCase(unittest.TestCase): + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.tmp_path = Path(temp_dir.name) + + +class ImportConfigTest(TempDirTestCase): + def test_get_artifacts_is_empty_without_path_fields(self): + self.assertEqual(ImportConfig(framework="onnx").get_artifacts(), ()) + + def test_get_artifacts_collects_path_fields(self): + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "tokenizer", + generation_config_dir=self.tmp_path / "generation_config", + ) + self.assertEqual( + config.get_artifacts(), + (self.tmp_path / "tokenizer", self.tmp_path / "generation_config"), + ) + + def test_copy_to_returns_self_without_path_fields(self): + config = ImportConfig(framework="onnx") + self.assertIs(config.copy_to(self.tmp_path), config) + + def test_copy_to_copies_files_and_directories(self): + src_dir = self.tmp_path / "src" + dst_dir = self.tmp_path / "dst" + (src_dir / "generation_config").mkdir(parents=True) + (src_dir / "generation_config" / "config.json").write_text("{}") + (src_dir / "tokenizer.json").write_text("tokens") + dst_dir.mkdir() + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=src_dir / "tokenizer.json", + generation_config_dir=src_dir / "generation_config", + extra_setting="kept", + ) + + copied = config.copy_to(dst_dir) + + self.assertEqual( + copied, + DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=dst_dir / "tokenizer.json", + generation_config_dir=dst_dir / "generation_config", + extra_setting="kept", + ), + ) + self.assertEqual((dst_dir / "tokenizer.json").read_text(), "tokens") + self.assertTrue((dst_dir / "generation_config" / "config.json").is_file()) + # The source config and its files are left as they were. + self.assertEqual(config.tokenizer, src_dir / "tokenizer.json") + self.assertTrue((src_dir / "tokenizer.json").is_file()) + + def test_copy_to_keeps_files_that_are_already_in_place(self): + (self.tmp_path / "generation_config").mkdir() + (self.tmp_path / "tokenizer.json").write_text("tokens") + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "tokenizer.json", + generation_config_dir=self.tmp_path / "generation_config", + ) + + self.assertEqual(config.copy_to(self.tmp_path), config) + self.assertEqual((self.tmp_path / "tokenizer.json").read_text(), "tokens") + + def test_copy_to_rejects_two_files_with_the_same_name(self): + for directory in ("first", "second"): + (self.tmp_path / directory).mkdir() + (self.tmp_path / directory / "config.json").write_text(directory) + dst_dir = self.tmp_path / "dst" + dst_dir.mkdir() + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "first" / "config.json", + generation_config_dir=self.tmp_path / "second" / "config.json", + ) + + with self.assertRaisesRegex(ValueError, "both would be named config.json"): + config.copy_to(dst_dir) + + # Nothing is copied when the names clash. + self.assertEqual(list(dst_dir.iterdir()), []) + + def test_copy_to_rejects_names_that_differ_only_in_case(self): + # On a file system that ignores case, the second copy would replace + # the first. + for directory, name in ( + ("first", "Tokenizer.json"), + ("second", "tokenizer.json"), + ): + (self.tmp_path / directory).mkdir() + (self.tmp_path / directory / name).write_text(directory) + dst_dir = self.tmp_path / "dst" + dst_dir.mkdir() + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "first" / "Tokenizer.json", + generation_config_dir=self.tmp_path / "second" / "tokenizer.json", + ) + + with self.assertRaisesRegex(ValueError, "ignoring case"): + config.copy_to(dst_dir) + + self.assertEqual(list(dst_dir.iterdir()), []) + + def test_copy_to_accepts_the_same_file_in_two_fields(self): + (self.tmp_path / "src").mkdir() + (self.tmp_path / "src" / "shared.json").write_text("{}") + dst_dir = self.tmp_path / "dst" + dst_dir.mkdir() + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "src" / "shared.json", + generation_config_dir=self.tmp_path / "src" / "shared.json", + ) + + copied = config.copy_to(dst_dir) + + self.assertEqual(copied.tokenizer, dst_dir / "shared.json") + self.assertEqual(copied.generation_config_dir, dst_dir / "shared.json") + + def test_copy_to_rejects_a_path_without_a_name(self): + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=Path(".."), + generation_config_dir=self.tmp_path / "generation_config", + ) + + with self.assertRaisesRegex(ValueError, "does not name a file"): + config.copy_to(self.tmp_path) + + +class ImportConfigRegistryTest(unittest.TestCase): + def test_resolve_returns_registered_subclass(self): + self.assertIs(resolve_import_config_class(DUMMY_FRAMEWORK), DummyImportConfig) + + def test_resolve_falls_back_to_base_class(self): + self.assertIs(resolve_import_config_class("not-registered"), ImportConfig) + + def test_register_accepts_several_frameworks(self): + # The registry lives as long as the process: use names of this run. + first, second = f"first-{uuid.uuid4()}", f"second-{uuid.uuid4()}" + + @register_import_config([first, second]) + @dataclasses.dataclass(frozen=True, kw_only=True) + class SharedImportConfig(ImportConfig): + pass + + self.assertIs(resolve_import_config_class(first), SharedImportConfig) + self.assertIs(resolve_import_config_class(second), SharedImportConfig) + + def test_register_rejects_a_second_class_for_a_framework(self): + with self.assertRaisesRegex(ValueError, "already registered to Dummy"): + + @register_import_config(["not-taken-yet", DUMMY_FRAMEWORK]) + @dataclasses.dataclass(frozen=True, kw_only=True) + class OtherImportConfig(ImportConfig): + pass + + # Nothing was registered, not even the framework that was still free. + self.assertIs(resolve_import_config_class(DUMMY_FRAMEWORK), DummyImportConfig) + self.assertIs(resolve_import_config_class("not-taken-yet"), ImportConfig) + + def test_register_accepts_the_same_class_again(self): + self.assertIs( + register_import_config(DUMMY_FRAMEWORK)(DummyImportConfig), + DummyImportConfig, + ) + + def test_register_rejects_a_class_that_is_not_an_import_config(self): + # Typed loosely, so that the mistake is only caught when it runs. + not_a_config: Any = dict + with self.assertRaisesRegex(TypeError, "not a subclass of ImportConfig"): + register_import_config("not-a-config")(not_a_config) + + self.assertIs(resolve_import_config_class("not-a-config"), ImportConfig) + + +class CompileConfigTest(TempDirTestCase): + def test_load_applies_defaults(self): + config_path = self.tmp_path / "config.json" + config_path.write_text( + json.dumps({"target_device": ["local"], "drivers": ["local-task"]}) + ) + + config = CompileConfig.load(config_path) + + self.assertEqual( + config, CompileConfig(target_device=["local"], drivers=["local-task"]) + ) + self.assertEqual(config.flags, []) + self.assertEqual(config.conditional_flags, []) + self.assertTrue(config.supports_external_parameters) + self.assertEqual(config.device_lead_allocator, 0) + + def test_load_builds_conditional_rules(self): + config_path = self.tmp_path / "config.json" + config_path.write_text( + json.dumps( + { + "target_device": ["local"], + "drivers": ["local-task"], + "conditional_flags": [ + {"when": {"arch_in": ["aarch64"]}, "add": ["--flag"]}, + {"when": {"arch_in": ["x86_64"]}}, + ], + } + ) + ) + + config = CompileConfig.load(config_path) + + self.assertEqual( + config.conditional_flags, + [ + ConditionalRule(when={"arch_in": ["aarch64"]}, add=["--flag"]), + ConditionalRule(when={"arch_in": ["x86_64"]}, add=[]), + ], + ) + + def test_save_and_load_roundtrip(self): + config = CompileConfig( + target_device=["local"], + flags=["--static"], + dynamic_flags=["--triple={target_triple}"], + conditional_flags=[ + ConditionalRule(when={"arch_in": ["aarch64"]}, add=["--flag"]) + ], + supports_external_parameters=False, + drivers=["local-sync", "local-task"], + device_lead_allocator=1, + runtime_flags=["--runtime"], + custom_importers={"onnx": "custom-onnx"}, + ) + config_path = self.tmp_path / "config.json" + + config.save(config_path) + + self.assertEqual(CompileConfig.load(config_path), config) + self.assertEqual(json.loads(config_path.read_text()), config.to_dict()) + + def test_load_accepts_a_string_path(self): + config = CompileConfig(target_device=["local"], drivers=["local-task"]) + config_path = self.tmp_path / "config.json" + config.save(str(config_path)) + + self.assertEqual(CompileConfig.load(str(config_path)), config) + + def test_load_rejects_an_unknown_key(self): + config_path = self.tmp_path / "config.json" + config_path.write_text( + json.dumps( + { + "target_device": ["local"], + "drivers": ["local-task"], + "flag": ["--misspelled-key"], + } + ) + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileConfig.load(config_path) + + self.assertEqual(raised.exception.keys, {"flag"}) + self.assertIn(str(config_path), "\n".join(raised.exception.__notes__)) + + def test_load_rejects_an_unknown_key_in_a_conditional_rule(self): + config_path = self.tmp_path / "config.json" + config_path.write_text( + json.dumps( + { + "target_device": ["local"], + "drivers": ["local-task"], + "conditional_flags": [ + {"when": {}}, + {"when": {}, "ad": ["--misspelled-key"]}, + ], + } + ) + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileConfig.load(config_path) + + self.assertEqual(raised.exception.keys, {"ad"}) + + def test_load_reads_a_file_with_a_byte_order_mark(self): + config = CompileConfig(target_device=["local"], drivers=["local-task"]) + config_path = self.tmp_path / "config.json" + config_path.write_text(json.dumps(config.to_dict()), encoding="utf-8-sig") + + self.assertEqual(CompileConfig.load(config_path), config) + + def test_load_rejects_a_file_that_is_not_a_json_object(self): + config_path = self.tmp_path / "config.json" + for content in ("[]", "null", '"text"'): + with self.subTest(content=content): + config_path.write_text(content) + + with self.assertRaisesRegex(ValueError, "JSON object") as raised: + CompileConfig.load(config_path) + + self.assertIn(str(config_path), "\n".join(raised.exception.__notes__)) + + def test_save_keeps_the_file_when_the_config_cannot_be_serialized(self): + config_path = self.tmp_path / "config.json" + config_path.write_text("kept") + unserializable: Any = object() + config = CompileConfig( + target_device=["local"], drivers=["local-task"], flags=[unserializable] + ) + + with self.assertRaises(TypeError): + config.save(config_path) + + self.assertEqual(config_path.read_text(), "kept") + + def test_load_names_the_file_when_a_field_is_missing(self): + config_path = self.tmp_path / "config.json" + config_path.write_text(json.dumps({"target_device": ["local"]})) + + with self.assertRaises(DaciteError) as raised: + CompileConfig.load(config_path) + + self.assertIn("drivers", str(raised.exception)) + self.assertIn(str(config_path), "\n".join(raised.exception.__notes__)) + + def test_load_names_the_file_when_json_is_invalid(self): + config_path = self.tmp_path / "config.json" + config_path.write_text("{not json") + + with self.assertRaises(json.JSONDecodeError) as raised: + CompileConfig.load(config_path) + + self.assertIn(str(config_path), "\n".join(raised.exception.__notes__)) + + +if __name__ == "__main__": + unittest.main() From 826a76f036dbee03be1cbcacb9daebd2e646296f Mon Sep 17 00:00:00 2001 From: Tobias Fuchs Date: Wed, 18 Nov 2026 15:58:06 +0000 Subject: [PATCH 2/2] [Python] Add the import and compile results to iree.core Add `iree.core.result`: `ImportResult` and `CompileResult` describe what importing and compiling a model produced. They are saved next to the artifacts as `metadata.json` and loaded back from it. * Artifact paths are stored as file names relative to the metadata file, so that a result directory can be moved or copied as a whole. Saving rejects an artifact that is not directly inside the output directory. * Optional fields that are not set are left out of the file. The configurations are written in full, defaults included, so that a file keeps its meaning if a default changes. * Loading rebuilds the import configuration with the class registered for its framework. If no class is registered and the file holds importer-specific settings, loading fails instead of dropping them. * Both results use the same file name, so the file states its `type`, and loading one as the other is reported as such. It also carries a `schema_version`, so that a later change of the layout is reported instead of misread. A file without these keys is read as version 1 of the requested type. * Loading rejects unknown keys, as for configuration files. Errors while loading name the file. Nothing uses these classes yet: the compiler and runtime layers built on them follow. Assisted-by: Claude Code Signed-off-by: Tobias Fuchs --- core/python/BUILD.bazel | 20 + core/python/CMakeLists.txt | 9 + core/python/iree/core/result.py | 246 ++++++++++ core/python/test/result_test.py | 779 ++++++++++++++++++++++++++++++++ 4 files changed, 1054 insertions(+) create mode 100644 core/python/iree/core/result.py create mode 100644 core/python/test/result_test.py diff --git a/core/python/BUILD.bazel b/core/python/BUILD.bazel index 3cb749fea607..bdf8361d45b2 100644 --- a/core/python/BUILD.bazel +++ b/core/python/BUILD.bazel @@ -20,6 +20,7 @@ PY_SRCS = enforce_glob( "iree/core/__init__.py", "iree/core/_paths.py", "iree/core/config.py", + "iree/core/result.py", ], include = ["iree/core/**/*.py"], ) @@ -28,6 +29,7 @@ PY_TESTS = enforce_glob( [ "test/config_test.py", "test/package_test.py", + "test/result_test.py", ], include = ["test/**/*.py"], ) @@ -50,6 +52,15 @@ py_test( deps = [":core"], ) +py_test( + name = "result_test", + size = "small", + srcs = ["test/result_test.py"], + legacy_create_init = False, + main = "test/result_test.py", + deps = [":core"], +) + py_test( name = "package_test", size = "small", @@ -85,6 +96,15 @@ if(IREE_BUILD_TESTS) "${CMAKE_CURRENT_SOURCE_DIR}" ) + iree_local_py_test( + NAME + result_test + SRC + "test/result_test.py" + PACKAGE_DIRS + "${CMAKE_CURRENT_SOURCE_DIR}" + ) + iree_local_py_test( NAME package_test diff --git a/core/python/CMakeLists.txt b/core/python/CMakeLists.txt index e27dec6adfcc..d08e7e0bfc78 100644 --- a/core/python/CMakeLists.txt +++ b/core/python/CMakeLists.txt @@ -29,6 +29,15 @@ if(IREE_BUILD_TESTS) "${CMAKE_CURRENT_SOURCE_DIR}" ) + iree_local_py_test( + NAME + result_test + SRC + "test/result_test.py" + PACKAGE_DIRS + "${CMAKE_CURRENT_SOURCE_DIR}" + ) + iree_local_py_test( NAME package_test diff --git a/core/python/iree/core/result.py b/core/python/iree/core/result.py new file mode 100644 index 000000000000..6fef3328b360 --- /dev/null +++ b/core/python/iree/core/result.py @@ -0,0 +1,246 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Results of importing and compiling a model, saved next to its artifacts.""" + +import dataclasses +import json +from pathlib import Path +from typing import Self, TypeVar + +from dacite import Config, DaciteError, UnexpectedDataError, from_dict +from dacite.exceptions import DaciteFieldError + +from ._paths import collect_paths +from .config import CompileConfig, ImportConfig, resolve_import_config_class + +__all__ = [ + "CompileResult", + "ImportResult", +] + + +_ResultT = TypeVar("_ResultT") + +# Version of the metadata.json layout. Raise it when the layout changes in a +# way that older readers would misread. +_SCHEMA_VERSION = 1 + +# What a metadata.json file describes. Both kinds of result use that file name, +# so the file says which one it holds. +_IMPORT_RESULT = "import_result" +_COMPILE_RESULT = "compile_result" + + +class _PathSerializer: + """JSON ``default`` that serializes each ``Path`` as its basename, after + checking that it lives directly inside ``base_dir``. + """ + + def __init__(self, base_dir: Path) -> None: + self._base_dir = base_dir + self._expected = base_dir.resolve() + + def __call__(self, obj: object) -> str: + if isinstance(obj, Path): + if obj.parent.resolve() != self._expected: + raise ValueError(f"{obj} not in {self._base_dir}") + if obj.name in ("", ".."): + raise ValueError(f"{obj!r} does not name a file in {self._base_dir}") + return obj.name + raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") + + +def _load_import_config(data: dict, config: Config) -> ImportConfig: + """Build the import config with the class registered for its framework.""" + framework = data.get("framework", "") + # A framework that is not a string has no class; the base class reports it. + config_class = ( + resolve_import_config_class(framework) + if isinstance(framework, str) + else ImportConfig + ) + try: + return from_dict(data_class=config_class, data=data, config=config) + except UnexpectedDataError as e: + # The base class cannot hold importer-specific settings. They usually + # belong to a class that is not registered yet. + if config_class is ImportConfig: + e.add_note( + f"no import config class is registered for framework {framework!r}: " + "import the module that defines it before loading" + ) + raise + + +def _load_metadata_json( + cls: type[_ResultT], metadata_path: Path, result_type: str +) -> _ResultT: + """Load ``metadata_path``, a file of type ``result_type``, into ``cls``. + + Relative paths in the file are resolved against its directory. + """ + base_dir = metadata_path.parent + + def resolve_path(path: object) -> Path: + if not isinstance(path, (str, Path)): + raise ValueError(f"expected a path, found {path!r}") + # Joining keeps an absolute path as it is. + return base_dir / path + + # JSON has no tuples: lists are cast to the tuple fields of a dataclass. + # A key that matches no field is an error. + config = Config(type_hooks={Path: resolve_path}, cast=[tuple], strict=True) + try: + # utf-8-sig also reads files that start with a byte order mark. + data = json.loads(metadata_path.read_text(encoding="utf-8-sig")) + if not isinstance(data, dict): + raise ValueError("expected a JSON object") + data = dict(data) + # Files written before these two keys existed have neither. Their + # layout is that of version 1. + file_type = data.pop("type", result_type) + if file_type != result_type: + raise ValueError(f"expected type {result_type!r}, found {file_type!r}") + schema_version = data.pop("schema_version", 1) + if type(schema_version) is not int or schema_version != _SCHEMA_VERSION: + raise ValueError( + f"unsupported schema_version {schema_version!r}, " + f"expected {_SCHEMA_VERSION}" + ) + # Pre-build import_config with the correct subclass; dacite passes + # pre-built instances through unchanged. + if isinstance(data.get("import_config"), dict): + try: + data["import_config"] = _load_import_config( + data["import_config"], config + ) + except DaciteFieldError as e: + e.update_path("import_config") + raise + return from_dict(data_class=cls, data=data, config=config) + except (json.JSONDecodeError, DaciteError, ValueError) as e: + e.add_note(f"while loading {metadata_path}") + raise + + +def _save_metadata_json( + result: "ImportResult | CompileResult", result_type: str, output_dir: Path +) -> Path: + """Write ``result`` of type ``result_type`` as metadata.json into ``output_dir``. + + Optional fields that are not set are left out of the file. + """ + metadata_path = result.metadata_path(output_dir) + data: dict[str, object] = {"type": result_type, "schema_version": _SCHEMA_VERSION} + data.update( + (key, value) + for key, value in dataclasses.asdict(result).items() + if value is not None + ) + # Serialize before touching the file system, so that a path outside + # output_dir is rejected without leaving a directory behind. + text = json.dumps(data, indent=2, default=_PathSerializer(output_dir)) + output_dir.mkdir(parents=True, exist_ok=True) + metadata_path.write_text(text, encoding="utf-8") + return metadata_path + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class ImportResult: + """ + Describes the artifacts produced by an importer. + """ + + imported_model: Path + import_config: ImportConfig + # The parameter archive that the imported model references but does not + # contain, for importers that keep the weights out of the module. + input_irpa: Path | None = None + entry_function_name: str | None = None + + @property + def output_dir(self) -> Path: + """Return the directory containing the import output.""" + return self.imported_model.parent + + @classmethod + def metadata_path(cls, output_dir: Path) -> Path: + """Return the path to metadata.json inside *output_dir*.""" + return output_dir / "metadata.json" + + @staticmethod + def is_metadata(path: Path) -> bool: + """Check if a path points to a metadata.json file.""" + return path == ImportResult.metadata_path(path.parent) + + def save(self, output_dir: Path) -> Path: + """Write metadata.json into output_dir. Returns path to metadata.json.""" + return _save_metadata_json(self, _IMPORT_RESULT, output_dir) + + @classmethod + def load(cls, metadata_path: Path) -> Self: + """Load from a local metadata.json file.""" + return _load_metadata_json(cls, metadata_path, _IMPORT_RESULT) + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class CompileResult: + """Describes the artifacts produced by compiling a model. + + Artifact fields are paths to files on disk. ``load`` resolves relative ones + against the directory of the metadata file. + ``compile_config`` records the compile-time backend configuration and the + runtime driver settings required to execute the artifact. + """ + + vmfb: Path + compile_config: CompileConfig + import_config: ImportConfig | None = None + encoded_irpa: Path | None = None + entry_function_name: str | None = None + + @property + def vmfb_size(self) -> int: + """Return the size of the vmfb in bytes.""" + return self.vmfb.stat().st_size + + @property + def output_dir(self) -> Path: + """Return the directory containing the compile output.""" + return self.vmfb.parent + + @classmethod + def metadata_path(cls, output_dir: Path) -> Path: + """Return the path to metadata.json inside *output_dir*.""" + return output_dir / "metadata.json" + + def get_model_artifacts(self) -> tuple[Path, ...]: + """Serialized code and weights, excluding metadata and importer assets.""" + return (self.vmfb,) + ( + (self.encoded_irpa,) if self.encoded_irpa is not None else () + ) + + def get_artifacts(self, *, include_metadata: bool = True) -> tuple[Path, ...]: + """Return every file or directory needed to run this compile result.""" + paths = list(collect_paths(dataclasses.asdict(self))) + if include_metadata: + paths.insert(0, self.metadata_path(self.output_dir)) + return tuple(paths) + + def save(self, output_dir: Path) -> Path: + """Write metadata.json into output_dir. Returns path to metadata.json.""" + return _save_metadata_json(self, _COMPILE_RESULT, output_dir) + + @staticmethod + def is_metadata(path: Path) -> bool: + """Check if a path points to a metadata.json file.""" + return path == CompileResult.metadata_path(path.parent) + + @classmethod + def load(cls, metadata_path: Path) -> Self: + """Load from a local metadata.json file.""" + return _load_metadata_json(cls, metadata_path, _COMPILE_RESULT) diff --git a/core/python/test/result_test.py b/core/python/test/result_test.py new file mode 100644 index 000000000000..c97189b894b7 --- /dev/null +++ b/core/python/test/result_test.py @@ -0,0 +1,779 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Tests for iree.core.result.""" + +import dataclasses +import json +import re +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from dacite import DaciteError, UnexpectedDataError + +from iree.core.config import CompileConfig, ImportConfig, register_import_config +from iree.core.result import CompileResult, ImportResult + +# Unique to this file: all test files may share one process and one registry. +DUMMY_FRAMEWORK = "dummy-result" + + +@register_import_config(DUMMY_FRAMEWORK) +@dataclasses.dataclass(frozen=True, kw_only=True) +class DummyImportConfig(ImportConfig): + """Subclass that adds fields, including ``Path`` ones.""" + + tokenizer: Path + generation_config_dir: Path + extra_setting: str = "default" + + +@register_import_config("tuple-result") +@dataclasses.dataclass(frozen=True, kw_only=True) +class TupleImportConfig(ImportConfig): + """Subclass with tuple fields, which JSON stores as lists.""" + + files: tuple[Path, ...] = () + names: tuple[str, ...] = () + + +class TempDirTestCase(unittest.TestCase): + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.tmp_path = Path(temp_dir.name) + + def write_metadata(self, output_dir: Path, data: object) -> Path: + """Write ``data`` as metadata.json into ``output_dir``.""" + output_dir.mkdir(parents=True, exist_ok=True) + metadata_path = output_dir / "metadata.json" + metadata_path.write_text(json.dumps(data), encoding="utf-8") + return metadata_path + + def read_metadata(self, metadata_path: Path) -> dict: + return json.loads(metadata_path.read_text(encoding="utf-8")) + + +def notes_of(exception: BaseException) -> str: + return "\n".join(getattr(exception, "__notes__", [])) + + +class ImportResultTest(TempDirTestCase): + def test_save_writes_paths_as_basenames(self): + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=ImportConfig(framework="torch"), + input_irpa=self.tmp_path / "weights.irpa", + ) + + metadata_path = result.save(self.tmp_path) + + self.assertEqual(metadata_path, ImportResult.metadata_path(self.tmp_path)) + self.assertEqual( + self.read_metadata(metadata_path), + { + "type": "import_result", + "schema_version": 1, + "imported_model": "imported_model.mlirbc", + "input_irpa": "weights.irpa", + "import_config": {"framework": "torch"}, + }, + ) + + def test_save_creates_the_output_directory(self): + output_dir = self.tmp_path / "nested" / "output" + result = ImportResult( + imported_model=output_dir / "imported_model.mlirbc", + import_config=ImportConfig(framework="torch"), + ) + + metadata_path = result.save(output_dir) + + self.assertTrue(metadata_path.is_file()) + + def test_save_and_load_roundtrip(self): + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=ImportConfig(framework="torch"), + input_irpa=self.tmp_path / "input.irpa", + entry_function_name="forward", + ) + + loaded = ImportResult.load(result.save(self.tmp_path)) + + self.assertEqual(loaded, result) + + def test_save_and_load_without_optional_fields(self): + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=ImportConfig(framework="onnx"), + ) + + metadata_path = result.save(self.tmp_path) + + # Optional fields that are not set are left out of the file. + self.assertEqual( + self.read_metadata(metadata_path), + { + "type": "import_result", + "schema_version": 1, + "imported_model": "imported_model.mlirbc", + "import_config": {"framework": "onnx"}, + }, + ) + loaded = ImportResult.load(metadata_path) + self.assertEqual(loaded, result) + self.assertIsNone(loaded.input_irpa) + self.assertIsNone(loaded.entry_function_name) + + def test_load_reads_null_as_unset(self): + # save() leaves unset fields out, but null means the same. + metadata_path = self.write_metadata( + self.tmp_path, + { + "imported_model": "imported_model.mlirbc", + "input_irpa": None, + "import_config": {"framework": "torch"}, + "entry_function_name": None, + }, + ) + + loaded = ImportResult.load(metadata_path) + + self.assertIsNone(loaded.input_irpa) + self.assertIsNone(loaded.entry_function_name) + + def test_load_uses_registered_subclass(self): + config = DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "tokenizer.json", + generation_config_dir=self.tmp_path / "generation_config", + extra_setting="custom", + ) + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=config, + ) + + loaded = ImportResult.load(result.save(self.tmp_path)) + + self.assertIsInstance(loaded.import_config, DummyImportConfig) + self.assertEqual(loaded.import_config, config) + + def test_load_resolves_relative_paths_against_metadata_dir(self): + output_dir = self.tmp_path / "output" + metadata_path = self.write_metadata( + output_dir, + { + "imported_model": "imported_model.mlirbc", + "input_irpa": "weights.irpa", + "import_config": {"framework": "torch"}, + }, + ) + + loaded = ImportResult.load(metadata_path) + + self.assertEqual(loaded.imported_model, output_dir / "imported_model.mlirbc") + self.assertEqual(loaded.input_irpa, output_dir / "weights.irpa") + + def test_load_resolves_subclass_paths_against_metadata_dir(self): + output_dir = self.tmp_path / "output" + metadata_path = self.write_metadata( + output_dir, + { + "imported_model": "imported_model.mlirbc", + "import_config": { + "framework": DUMMY_FRAMEWORK, + "tokenizer": "tokenizer.json", + "generation_config_dir": "generation_config", + "extra_setting": "x", + }, + }, + ) + + loaded = ImportResult.load(metadata_path) + + self.assertEqual( + loaded.import_config, + DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=output_dir / "tokenizer.json", + generation_config_dir=output_dir / "generation_config", + extra_setting="x", + ), + ) + + def test_load_keeps_absolute_paths(self): + # Absolute paths are never written by save(), but a hand-written file + # may point outside its own directory. + elsewhere = self.tmp_path / "elsewhere" + output_dir = self.tmp_path / "output" + metadata_path = self.write_metadata( + output_dir, + { + "imported_model": str(elsewhere / "imported_model.mlirbc"), + "input_irpa": "weights.irpa", + "import_config": {"framework": "torch"}, + }, + ) + + loaded = ImportResult.load(metadata_path) + + self.assertEqual(loaded.imported_model, elsewhere / "imported_model.mlirbc") + self.assertEqual(loaded.input_irpa, output_dir / "weights.irpa") + + def test_save_rejects_imported_model_outside_output_dir(self): + imported_model = self.tmp_path / "elsewhere" / "imported_model.mlirbc" + result = ImportResult( + imported_model=imported_model, + import_config=ImportConfig(framework="torch"), + ) + output_dir = self.tmp_path / "output" + + with self.assertRaisesRegex(ValueError, re.escape(str(imported_model))): + result.save(output_dir) + + # No metadata is written that would lose the directory of the path. + self.assertFalse(ImportResult.metadata_path(output_dir).exists()) + + def test_save_rejects_subclass_path_field_outside_output_dir(self): + # The check also covers the Path fields of import_config. + tokenizer = self.tmp_path / "elsewhere" / "tokenizer.json" + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=tokenizer, + generation_config_dir=self.tmp_path / "generation_config", + ), + ) + + with self.assertRaisesRegex(ValueError, re.escape(str(tokenizer))): + result.save(self.tmp_path) + + def test_save_rejects_values_json_cannot_represent(self): + @dataclasses.dataclass(frozen=True, kw_only=True) + class UnserializableImportConfig(ImportConfig): + setting: object + + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=UnserializableImportConfig( + framework="unserializable", setting=object() + ), + ) + + with self.assertRaisesRegex(TypeError, "is not JSON serializable"): + result.save(self.tmp_path) + + self.assertFalse(ImportResult.metadata_path(self.tmp_path).exists()) + + def test_load_names_the_file_when_a_field_is_missing(self): + metadata_path = self.write_metadata( + self.tmp_path, {"imported_model": "imported_model.mlirbc"} + ) + + with self.assertRaisesRegex(DaciteError, "import_config") as raised: + ImportResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_rejects_a_file_that_is_not_an_object(self): + metadata_path = self.write_metadata(self.tmp_path, ["imported_model.mlirbc"]) + + with self.assertRaisesRegex(ValueError, "expected a JSON object") as raised: + ImportResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_names_the_file_when_json_is_invalid(self): + metadata_path = self.tmp_path / "metadata.json" + metadata_path.write_text("{not json", encoding="utf-8") + + with self.assertRaises(json.JSONDecodeError) as raised: + ImportResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_unregistered_framework_as_base_class(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "imported_model": "imported_model.mlirbc", + "import_config": {"framework": "not-registered"}, + }, + ) + + loaded = ImportResult.load(metadata_path) + + self.assertIs(type(loaded.import_config), ImportConfig) + self.assertEqual(loaded.import_config, ImportConfig(framework="not-registered")) + + def test_load_rejects_settings_of_unregistered_framework(self): + # The base class cannot hold the extra settings, so they must not be + # dropped silently. + metadata_path = self.write_metadata( + self.tmp_path, + { + "imported_model": "imported_model.mlirbc", + "import_config": { + "framework": "not-registered", + "tokenizer": "tokenizer.json", + }, + }, + ) + + with self.assertRaises(UnexpectedDataError) as raised: + ImportResult.load(metadata_path) + + notes = notes_of(raised.exception) + self.assertIn("'not-registered'", notes) + self.assertIn(str(metadata_path), notes) + + def test_output_dir(self): + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=ImportConfig(framework="torch"), + ) + self.assertEqual(result.output_dir, self.tmp_path) + + def test_metadata_path_is_inside_output_dir(self): + self.assertEqual( + ImportResult.metadata_path(self.tmp_path), self.tmp_path / "metadata.json" + ) + + def test_is_metadata(self): + for name, expected in ( + ("metadata.json", True), + ("imported_model.mlirbc", False), + ("metadata.json.bak", False), + ): + with self.subTest(name=name): + self.assertEqual( + ImportResult.is_metadata(self.tmp_path / "dir" / name), expected + ) + + +class CompileResultTest(TempDirTestCase): + def setUp(self): + super().setUp() + self.compile_config = CompileConfig( + target_device=["local"], drivers=["local-task"] + ) + + def full_result(self) -> CompileResult: + """Return a result that sets every field.""" + return CompileResult( + vmfb=self.tmp_path / "model.vmfb", + compile_config=CompileConfig( + target_device=["local"], + flags=["--static"], + drivers=["local-sync", "local-task"], + device_lead_allocator=1, + runtime_flags=["--runtime"], + ), + import_config=DummyImportConfig( + framework=DUMMY_FRAMEWORK, + tokenizer=self.tmp_path / "tokenizer", + generation_config_dir=self.tmp_path / "generation_config", + extra_setting="custom", + ), + encoded_irpa=self.tmp_path / "output.irpa", + entry_function_name="forward", + ) + + def test_save_and_load_roundtrip_with_required_fields(self): + result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + + metadata_path = result.save(self.tmp_path) + + self.assertEqual(metadata_path, CompileResult.metadata_path(self.tmp_path)) + # Optional fields that are not set are left out of the file. + self.assertEqual( + self.read_metadata(metadata_path), + { + "type": "compile_result", + "schema_version": 1, + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + }, + ) + self.assertEqual(CompileResult.load(metadata_path), result) + + def test_save_and_load_roundtrip_with_every_field(self): + result = self.full_result() + + metadata_path = result.save(self.tmp_path) + + data = self.read_metadata(metadata_path) + self.assertEqual(data["encoded_irpa"], "output.irpa") + self.assertEqual(data["import_config"]["tokenizer"], "tokenizer") + loaded = CompileResult.load(metadata_path) + self.assertEqual(loaded, result) + self.assertIsInstance(loaded.import_config, DummyImportConfig) + + def test_save_rejects_vmfb_outside_output_dir(self): + vmfb = self.tmp_path / "elsewhere" / "model.vmfb" + result = CompileResult(vmfb=vmfb, compile_config=self.compile_config) + + with self.assertRaisesRegex(ValueError, re.escape(str(vmfb))): + result.save(self.tmp_path) + + def test_load_resolves_relative_paths_against_metadata_dir(self): + output_dir = self.tmp_path / "output" + metadata_path = self.write_metadata( + output_dir, + { + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + "encoded_irpa": "output.irpa", + }, + ) + + loaded = CompileResult.load(metadata_path) + + self.assertEqual(loaded.vmfb, output_dir / "model.vmfb") + self.assertEqual(loaded.encoded_irpa, output_dir / "output.irpa") + + def test_load_keeps_absolute_paths(self): + elsewhere = self.tmp_path / "elsewhere" + metadata_path = self.write_metadata( + self.tmp_path / "output", + { + "vmfb": str(elsewhere / "model.vmfb"), + "compile_config": self.compile_config.to_dict(), + }, + ) + + loaded = CompileResult.load(metadata_path) + + self.assertEqual(loaded.vmfb, elsewhere / "model.vmfb") + + def test_tuple_fields_of_an_import_config_roundtrip(self): + result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=TupleImportConfig( + framework="tuple-result", + files=(self.tmp_path / "a.bin", self.tmp_path / "b.bin"), + names=("a", "b"), + ), + ) + + self.assertEqual(ImportResult.load(result.save(self.tmp_path)), result) + + def test_failed_save_leaves_no_output_directory_behind(self): + output_dir = self.tmp_path / "not-created" + result = CompileResult( + vmfb=self.tmp_path / "elsewhere" / "model.vmfb", + compile_config=self.compile_config, + ) + + with self.assertRaises(ValueError): + result.save(output_dir) + + self.assertFalse(output_dir.exists()) + + def test_save_rejects_a_path_without_a_file_name(self): + result = CompileResult( + vmfb=self.tmp_path / "..", compile_config=self.compile_config + ) + + with self.assertRaisesRegex(ValueError, "does not name a file"): + result.save(self.tmp_path) + + def test_load_rejects_a_path_that_is_not_a_string(self): + for vmfb in (None, 5, ["model.vmfb"]): + with self.subTest(vmfb=vmfb): + metadata_path = self.write_metadata( + self.tmp_path, + {"vmfb": vmfb, "compile_config": self.compile_config.to_dict()}, + ) + + with self.assertRaises((ValueError, DaciteError)) as raised: + CompileResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_rejects_a_framework_that_is_not_a_string(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "imported_model": "imported_model.mlirbc", + "import_config": {"framework": ["torch"]}, + }, + ) + + with self.assertRaises(DaciteError) as raised: + ImportResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_names_the_import_config_field_that_is_missing(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "imported_model": "imported_model.mlirbc", + "import_config": {"framework": "dummy-result"}, + }, + ) + + with self.assertRaisesRegex(DaciteError, r"import_config\.tokenizer"): + ImportResult.load(metadata_path) + + def test_load_reads_a_file_with_a_byte_order_mark(self): + result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + metadata_path = result.save(self.tmp_path) + metadata_path.write_text( + metadata_path.read_text(encoding="utf-8"), encoding="utf-8-sig" + ) + + self.assertEqual(CompileResult.load(metadata_path), result) + + def test_load_rejects_an_unknown_key(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + "zzz": 1, + }, + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileResult.load(metadata_path) + + self.assertEqual(raised.exception.keys, {"zzz"}) + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_rejects_an_unknown_key_in_the_compile_config(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "vmfb": "model.vmfb", + "compile_config": {**self.compile_config.to_dict(), "flag": []}, + }, + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileResult.load(metadata_path) + + self.assertEqual(raised.exception.keys, {"flag"}) + + def test_load_rejects_an_unknown_key_in_a_registered_import_config(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + "import_config": { + "framework": "dummy-result", + "tokenizer": "tokenizer.json", + "generation_config_dir": "generation_config", + "extra": 1, + }, + }, + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileResult.load(metadata_path) + + self.assertEqual(raised.exception.keys, {"extra"}) + # The framework has a class, so the hint about a missing one would mislead. + self.assertNotIn("no import config class", notes_of(raised.exception)) + + def test_load_rejects_a_file_of_the_other_type(self): + import_result = ImportResult( + imported_model=self.tmp_path / "imported_model.mlirbc", + import_config=ImportConfig(framework="torch"), + ) + metadata_path = import_result.save(self.tmp_path) + + with self.assertRaisesRegex( + ValueError, "expected type 'compile_result', found 'import_result'" + ) as raised: + CompileResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_import_result_load_rejects_a_compile_result_file(self): + compile_result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + metadata_path = compile_result.save(self.tmp_path) + + with self.assertRaisesRegex( + ValueError, "expected type 'import_result', found 'compile_result'" + ): + ImportResult.load(metadata_path) + + def test_load_accepts_a_file_without_type_and_schema_version(self): + # Files written before these two keys existed have neither. + metadata_path = self.write_metadata( + self.tmp_path, + {"vmfb": "model.vmfb", "compile_config": self.compile_config.to_dict()}, + ) + + loaded = CompileResult.load(metadata_path) + + self.assertEqual( + loaded, + CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ), + ) + + def test_load_reads_a_file_without_schema_version_as_version_1(self): + metadata_path = self.write_metadata( + self.tmp_path, + {"vmfb": "model.vmfb", "compile_config": self.compile_config.to_dict()}, + ) + + # Stands in for a later version of the layout. + with mock.patch("iree.core.result._SCHEMA_VERSION", 2): + with self.assertRaisesRegex(ValueError, "unsupported schema_version 1,"): + CompileResult.load(metadata_path) + + def test_load_rejects_other_schema_versions(self): + for schema_version in (0, 2, "1", None): + with self.subTest(schema_version=schema_version): + metadata_path = self.write_metadata( + self.tmp_path, + { + "schema_version": schema_version, + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + }, + ) + + with self.assertRaisesRegex(ValueError, "schema_version") as raised: + CompileResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_names_the_file_when_a_field_is_missing(self): + metadata_path = self.write_metadata(self.tmp_path, {"vmfb": "model.vmfb"}) + + with self.assertRaisesRegex(DaciteError, "compile_config") as raised: + CompileResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_rejects_a_file_that_is_not_an_object(self): + metadata_path = self.write_metadata(self.tmp_path, "model.vmfb") + + with self.assertRaisesRegex(ValueError, "expected a JSON object") as raised: + CompileResult.load(metadata_path) + + self.assertIn(str(metadata_path), notes_of(raised.exception)) + + def test_load_unregistered_framework_as_base_class(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + "import_config": {"framework": "not-registered"}, + }, + ) + + loaded = CompileResult.load(metadata_path) + + self.assertIs(type(loaded.import_config), ImportConfig) + self.assertEqual(loaded.import_config, ImportConfig(framework="not-registered")) + + def test_load_rejects_settings_of_unregistered_framework(self): + metadata_path = self.write_metadata( + self.tmp_path, + { + "vmfb": "model.vmfb", + "compile_config": self.compile_config.to_dict(), + "import_config": { + "framework": "not-registered", + "extra_setting": "lost", + }, + }, + ) + + with self.assertRaises(UnexpectedDataError) as raised: + CompileResult.load(metadata_path) + + notes = notes_of(raised.exception) + self.assertIn("'not-registered'", notes) + self.assertIn(str(metadata_path), notes) + + def test_vmfb_size(self): + vmfb = self.tmp_path / "model.vmfb" + vmfb.write_bytes(b"\x00" * 16) + result = CompileResult(vmfb=vmfb, compile_config=self.compile_config) + self.assertEqual(result.vmfb_size, 16) + + def test_output_dir(self): + result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + self.assertEqual(result.output_dir, self.tmp_path) + + def test_get_model_artifacts(self): + result = self.full_result() + self.assertEqual( + result.get_model_artifacts(), + (self.tmp_path / "model.vmfb", self.tmp_path / "output.irpa"), + ) + + def test_get_model_artifacts_without_irpa(self): + result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + self.assertEqual(result.get_model_artifacts(), (self.tmp_path / "model.vmfb",)) + + def test_get_artifacts_includes_importer_paths(self): + # The tokenizer and generation config held by import_config are needed + # at runtime too. + result = self.full_result() + artifacts = ( + self.tmp_path / "model.vmfb", + self.tmp_path / "tokenizer", + self.tmp_path / "generation_config", + self.tmp_path / "output.irpa", + ) + + self.assertEqual( + result.get_artifacts(), (self.tmp_path / "metadata.json",) + artifacts + ) + self.assertEqual(result.get_artifacts(include_metadata=False), artifacts) + + def test_get_artifacts_with_required_fields(self): + result = CompileResult( + vmfb=self.tmp_path / "model.vmfb", compile_config=self.compile_config + ) + self.assertEqual( + result.get_artifacts(), + (self.tmp_path / "metadata.json", self.tmp_path / "model.vmfb"), + ) + self.assertEqual( + result.get_artifacts(include_metadata=False), + (self.tmp_path / "model.vmfb",), + ) + + def test_is_metadata(self): + for name, expected in ( + ("metadata.json", True), + ("model.vmfb", False), + ): + with self.subTest(name=name): + self.assertEqual( + CompileResult.is_metadata(self.tmp_path / "dir" / name), expected + ) + + +if __name__ == "__main__": + unittest.main()