diff --git a/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c b/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c new file mode 100644 index 0000000000000000000000000000000000000000..8de4e06f475912dfc1b6c71427e57f10b76fc92f Binary files /dev/null and b/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c differ diff --git a/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body b/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body new file mode 100644 index 0000000000000000000000000000000000000000..4041c65d6b3abb1537dc8a1c6e184acbc1f89a1e --- /dev/null +++ b/.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body @@ -0,0 +1,88 @@ +Metadata-Version: 2.4 +Name: Mako +Version: 1.3.12 +Summary: A super-fast templating language that borrows the best ideas from the existing templating languages. +Home-page: https://www.makotemplates.org/ +Author: Mike Bayer +Author-email: mike@zzzcomputing.com +License: MIT +Project-URL: Documentation, https://docs.makotemplates.org +Project-URL: Issue Tracker, https://github.com/sqlalchemy/mako +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: MIT License +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: MarkupSafe>=0.9.2 +Provides-Extra: testing +Requires-Dist: pytest; extra == "testing" +Provides-Extra: babel +Requires-Dist: Babel; extra == "babel" +Provides-Extra: lingua +Requires-Dist: lingua; extra == "lingua" +Dynamic: license-file + +========================= +Mako Templates for Python +========================= + +Mako is a template library written in Python. It provides a familiar, non-XML +syntax which compiles into Python modules for maximum performance. Mako's +syntax and API borrows from the best ideas of many others, including Django +templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded +Python (i.e. Python Server Page) language, which refines the familiar ideas +of componentized layout and inheritance to produce one of the most +straightforward and flexible models available, while also maintaining close +ties to Python calling and scoping semantics. + +Nutshell +======== + +:: + + <%inherit file="base.html"/> + <% + rows = [[v for v in range(0,10)] for row in range(0,10)] + %> + + % for row in rows: + ${makerow(row)} + % endfor +
+ + <%def name="makerow(row)"> + + % for name in row: + ${name}\ + % endfor + + + +Philosophy +=========== + +Python is a great scripting language. Don't reinvent the wheel...your templates can handle it ! + +Documentation +============== + +See documentation for Mako at https://docs.makotemplates.org/en/latest/ + +License +======== + +Mako is licensed under an MIT-style license (see LICENSE). +Other incorporated projects may be licensed under different licenses. +All licenses allow for non-commercial and commercial use. diff --git a/.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa b/.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa new file mode 100644 index 0000000000000000000000000000000000000000..efd800a26324de12558877178c4528c33d21fbce Binary files /dev/null and b/.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa differ diff --git a/.cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body b/.cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body new file mode 100644 index 0000000000000000000000000000000000000000..6fe5572b7f4741f738994e8e0e3c4c222ac20d4f Binary files /dev/null and b/.cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body differ diff --git a/.cache/pip/http-v2/2/b/d/2/a/2bd2afb46be8ef29cc0dd505de4aff907384c53895a0fbbce798558e b/.cache/pip/http-v2/2/b/d/2/a/2bd2afb46be8ef29cc0dd505de4aff907384c53895a0fbbce798558e new file mode 100644 index 0000000000000000000000000000000000000000..5923fd4c966c0983b1951eadb85cd179fc4b22bd Binary files /dev/null and b/.cache/pip/http-v2/2/b/d/2/a/2bd2afb46be8ef29cc0dd505de4aff907384c53895a0fbbce798558e differ diff --git a/.cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e b/.cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e new file mode 100644 index 0000000000000000000000000000000000000000..6e8a3ad9abb906f52501ace90512d45ebb0a8aff Binary files /dev/null and b/.cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e differ diff --git a/.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875.body b/.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875.body new file mode 100644 index 0000000000000000000000000000000000000000..be8a576c3bf4e1e0eeb64e94327b12b4887234bb --- /dev/null +++ b/.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db78c39c83d6279daddc98e2238f373ab8980685556d42472b4ec51abcf03e8c +size 4428006 diff --git a/.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body b/.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body new file mode 100644 index 0000000000000000000000000000000000000000..52a7eecaf4c9067dd2c0053da9b2a5080a29d696 Binary files /dev/null and b/.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body differ diff --git a/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 b/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 new file mode 100644 index 0000000000000000000000000000000000000000..6dbe6cba5dafd734034417288eddf01aa52ad01c Binary files /dev/null and b/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 differ diff --git a/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4.body b/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4.body new file mode 100644 index 0000000000000000000000000000000000000000..a35bf66c041e94c85e8c87ca328f534e3c7ff758 --- /dev/null +++ b/.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:840a36ba7d60efdaf3ac0d4e6edecec318724286033ac51bb825a7fdb3c6d981 +size 123031 diff --git a/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28 b/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28 new file mode 100644 index 0000000000000000000000000000000000000000..ed8f33fb40191388e99f4ab3a761de4bbdbef6d0 Binary files /dev/null and b/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28 differ diff --git a/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28.body b/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28.body new file mode 100644 index 0000000000000000000000000000000000000000..7757c23918738f77859b5cbea21c1bbcfcee9dd2 --- /dev/null +++ b/.cache/pip/http-v2/7/5/1/d/d/751ddfa98a60b6475798efa337438e34cb9e1ccfb51f0ff0c13f3a28.body @@ -0,0 +1,373 @@ +Metadata-Version: 2.4 +Name: huggingface_hub +Version: 1.26.0 +Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub +Home-page: https://github.com/huggingface/huggingface_hub +Author: Hugging Face, Inc. +Author-email: julien@huggingface.co +License: Apache-2.0 +Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.10.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: click<9.0.0,>=8.4.2 +Requires-Dist: filelock>=3.10.0 +Requires-Dist: fsspec>=2023.5.0 +Requires-Dist: hf-xet<2.0.0,>=1.5.1; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64" +Requires-Dist: httpx<1,>=0.23.0 +Requires-Dist: packaging>=20.9 +Requires-Dist: pyyaml>=5.1 +Requires-Dist: tqdm>=4.42.1 +Requires-Dist: typing-extensions>=4.1.0 +Provides-Extra: oauth +Requires-Dist: authlib>=1.3.2; extra == "oauth" +Requires-Dist: fastapi; extra == "oauth" +Requires-Dist: httpx; extra == "oauth" +Requires-Dist: itsdangerous; extra == "oauth" +Provides-Extra: torch +Requires-Dist: torch; extra == "torch" +Requires-Dist: safetensors[torch]; extra == "torch" +Provides-Extra: fastai +Requires-Dist: toml; extra == "fastai" +Requires-Dist: fastai>=2.4; extra == "fastai" +Requires-Dist: fastcore>=1.3.27; extra == "fastai" +Provides-Extra: hf-xet +Requires-Dist: hf-xet<2.0.0,>=1.5.1; extra == "hf-xet" +Provides-Extra: mcp +Requires-Dist: mcp>=1.8.0; extra == "mcp" +Provides-Extra: testing +Requires-Dist: authlib>=1.3.2; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Requires-Dist: httpx; extra == "testing" +Requires-Dist: itsdangerous; extra == "testing" +Requires-Dist: jedi; extra == "testing" +Requires-Dist: Jinja2; extra == "testing" +Requires-Dist: pytest>=8.4.2; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-env; extra == "testing" +Requires-Dist: pytest-xdist; extra == "testing" +Requires-Dist: pytest-vcr; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "testing" +Requires-Dist: pytest-mock; extra == "testing" +Requires-Dist: urllib3<2.0; extra == "testing" +Requires-Dist: soundfile; extra == "testing" +Requires-Dist: Pillow; extra == "testing" +Requires-Dist: numpy; extra == "testing" +Requires-Dist: duckdb; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Provides-Extra: gradio +Requires-Dist: gradio>=5.0.0; extra == "gradio" +Requires-Dist: requests; extra == "gradio" +Provides-Extra: typing +Requires-Dist: typing-extensions>=4.8.0; extra == "typing" +Requires-Dist: types-PyYAML; extra == "typing" +Requires-Dist: types-simplejson; extra == "typing" +Requires-Dist: types-toml; extra == "typing" +Requires-Dist: types-tqdm; extra == "typing" +Requires-Dist: types-urllib3; extra == "typing" +Provides-Extra: quality +Requires-Dist: ruff>=0.9.0; extra == "quality" +Requires-Dist: mypy==1.15.0; extra == "quality" +Requires-Dist: libcst>=1.4.0; extra == "quality" +Requires-Dist: ty; extra == "quality" +Provides-Extra: all +Requires-Dist: authlib>=1.3.2; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: httpx; extra == "all" +Requires-Dist: itsdangerous; extra == "all" +Requires-Dist: jedi; extra == "all" +Requires-Dist: Jinja2; extra == "all" +Requires-Dist: pytest>=8.4.2; extra == "all" +Requires-Dist: pytest-cov; extra == "all" +Requires-Dist: pytest-env; extra == "all" +Requires-Dist: pytest-xdist; extra == "all" +Requires-Dist: pytest-vcr; extra == "all" +Requires-Dist: pytest-asyncio; extra == "all" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "all" +Requires-Dist: pytest-mock; extra == "all" +Requires-Dist: urllib3<2.0; extra == "all" +Requires-Dist: soundfile; extra == "all" +Requires-Dist: Pillow; extra == "all" +Requires-Dist: numpy; extra == "all" +Requires-Dist: duckdb; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: ruff>=0.9.0; extra == "all" +Requires-Dist: mypy==1.15.0; extra == "all" +Requires-Dist: libcst>=1.4.0; extra == "all" +Requires-Dist: ty; extra == "all" +Requires-Dist: typing-extensions>=4.8.0; extra == "all" +Requires-Dist: types-PyYAML; extra == "all" +Requires-Dist: types-simplejson; extra == "all" +Requires-Dist: types-toml; extra == "all" +Requires-Dist: types-tqdm; extra == "all" +Requires-Dist: types-urllib3; extra == "all" +Provides-Extra: dev +Requires-Dist: authlib>=1.3.2; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: httpx; extra == "dev" +Requires-Dist: itsdangerous; extra == "dev" +Requires-Dist: jedi; extra == "dev" +Requires-Dist: Jinja2; extra == "dev" +Requires-Dist: pytest>=8.4.2; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: pytest-env; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: pytest-vcr; extra == "dev" +Requires-Dist: pytest-asyncio; extra == "dev" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "dev" +Requires-Dist: pytest-mock; extra == "dev" +Requires-Dist: urllib3<2.0; extra == "dev" +Requires-Dist: soundfile; extra == "dev" +Requires-Dist: Pillow; extra == "dev" +Requires-Dist: numpy; extra == "dev" +Requires-Dist: duckdb; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: ruff>=0.9.0; extra == "dev" +Requires-Dist: mypy==1.15.0; extra == "dev" +Requires-Dist: libcst>=1.4.0; extra == "dev" +Requires-Dist: ty; extra == "dev" +Requires-Dist: typing-extensions>=4.8.0; extra == "dev" +Requires-Dist: types-PyYAML; extra == "dev" +Requires-Dist: types-simplejson; extra == "dev" +Requires-Dist: types-toml; extra == "dev" +Requires-Dist: types-tqdm; extra == "dev" +Requires-Dist: types-urllib3; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +

+ + + + huggingface_hub library logo + +
+
+

+ +

+ The official CLI and Python client for the Hugging Face Hub. +
+ About + · + Documentation + · + Install + · + CLI Guide + · + Contributing +

+ +

+ Documentation + GitHub release + PyPi version + PyPI - Downloads + Code coverage +

+ +

+

+ English | + Deutsch | + Français | + हिंदी | + 한국어 | + 中文 (简体) | + ಕನ್ನಡ +

+

+ +## Quick start + +Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer: + +```bash +# On macOS and Linux. +curl -LsSf https://hf.co/cli/install.sh | bash +``` + +```powershell +# On Windows. +powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex" +``` + +Log in, then start working with the Hub: + +```bash +# Log in (use --token $HF_TOKEN in non-interactive environments) +hf auth login + +# Find models served by Inference Providers +hf models ls --warm + +# Download a model +hf download Qwen/Qwen3-0.6B + +# Upload files to your own repo +hf upload username/my-cool-model ./model.safetensors + +# Sync a local folder to a storage bucket +hf buckets sync ./checkpoints hf://buckets/username/my-bucket + +# Run a job on Hugging Face infrastructure +hf jobs run python:3.12 python -c "print('Hello from the cloud!')" + +# Discover everything else +hf --help +``` + +The Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). Check out the [CLI guide](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for a tour of the main features. + +## What is `huggingface_hub`? + +The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects, play with the thousands of machine learning apps hosted on the Hub, or create and share your own models, datasets and demos with the community. Everything ships in one package with two interfaces: the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for your terminal and the `huggingface_hub` library for Python — both designed to work well for humans and AI agents. Use them to: + +- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub. +- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub. +- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository). +- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models. +- [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure. +- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces. +- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models. +- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments. +- Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli). + +## Built for humans and AI agents + +The `hf` CLI is designed for people and coding agents alike: the same commands adapt their output when run by an agent. If you use Claude Code, Codex, Cursor, or another coding agent, install the `hf` CLI Skill — a command reference generated from your installed CLI: + +```bash +# for Codex, Cursor, OpenCode, Pi and other agents that load skills from `.agents/skills` +hf skills add +# includes the above + Claude Code +hf skills add --claude +``` + +Learn more in the [Hugging Face CLI for AI agents guide](https://huggingface.co/docs/hub/agents-cli) and the [announcement blog post](https://huggingface.co/blog/hf-cli-for-agents). + +## Use the Python library + +Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI): + +```bash +pip install huggingface_hub +``` + +We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install: + +```bash +uv pip install huggingface_hub +``` + +In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run: + +```bash +pip install "huggingface_hub[mcp]" +``` + +To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation). + +### Download files + +Download a single file + +```py +from huggingface_hub import hf_hub_download + +hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json") +``` + +Or an entire repository + +```py +from huggingface_hub import snapshot_download + +snapshot_download("sentence-transformers/all-MiniLM-L6-v2") +``` + +Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache). + +### Create a repository + +```py +from huggingface_hub import create_repo + +create_repo(repo_id="super-cool-model") +``` + +### Upload files + +Upload a single file + +```py +from huggingface_hub import upload_file + +upload_file( + path_or_fileobj="/home/lysandre/dummy-test/README.md", + path_in_repo="README.md", + repo_id="lysandre/test-model", +) +``` + +Or an entire folder + +```py +from huggingface_hub import upload_folder + +upload_folder( + folder_path="/path/to/local/space", + repo_id="username/my-cool-space", + repo_type="space", +) +``` + +More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload). + +## Integrating with the Hub. + +We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries). + +The advantages are: + +- Free model or dataset hosting for libraries and their users. +- Built-in file versioning, even with very large files, made possible by [Xet](https://huggingface.co/docs/hub/xet/index), the Hub's chunk-deduplicated storage backend. +- In-browser widgets to play with the uploaded models. +- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable. +- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe. +- Usage stats and more features to come. + +If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration. + +## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️ + +Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community. +Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community. +We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize +how to get started to contribute to this repository. diff --git a/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 b/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 new file mode 100644 index 0000000000000000000000000000000000000000..ab185ee4e54c252b57041bee135de1b808ec67ea Binary files /dev/null and b/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 differ diff --git a/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535.body b/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535.body new file mode 100644 index 0000000000000000000000000000000000000000..650ce7c8227f78377cb5825873231f9b05a7964e --- /dev/null +++ b/.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774 +size 516040 diff --git a/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1 b/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1 new file mode 100644 index 0000000000000000000000000000000000000000..c5571338d9a313499a0fc1957d903254af6b974b Binary files /dev/null and b/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1 differ diff --git a/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body b/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body new file mode 100644 index 0000000000000000000000000000000000000000..51a5125b29f0cb1cdc40d609f1ec7a6c021925ae Binary files /dev/null and b/.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body differ diff --git a/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0 b/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0 new file mode 100644 index 0000000000000000000000000000000000000000..4743dc049b96edc5f96faa7d63303d40d9475d5a Binary files /dev/null and b/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0 differ diff --git a/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0.body b/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0.body new file mode 100644 index 0000000000000000000000000000000000000000..7bbe7ef36fe9269746e9abe02594775b44a9bd38 --- /dev/null +++ b/.cache/pip/http-v2/7/a/1/2/2/7a12234cc448f4452405e8d5b4447cba68049d0e6085f64225d7eef0.body @@ -0,0 +1,592 @@ +Metadata-Version: 2.1 +Name: timm +Version: 1.0.28 +Summary: PyTorch Image Models +Keywords: pytorch,image-classification +Author-Email: Ross Wightman +License: Apache-2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Project-URL: homepage, https://github.com/huggingface/pytorch-image-models +Project-URL: documentation, https://huggingface.co/docs/timm/en/index +Project-URL: repository, https://github.com/huggingface/pytorch-image-models +Requires-Python: >=3.8 +Requires-Dist: torch +Requires-Dist: torchvision +Requires-Dist: pyyaml +Requires-Dist: huggingface_hub +Requires-Dist: safetensors +Description-Content-Type: text/markdown + +# PyTorch Image Models +- [What's New](#whats-new) +- [Introduction](#introduction) +- [Models](#models) +- [Features](#features) +- [Results](#results) +- [Getting Started (Documentation)](#getting-started-documentation) +- [Train, Validation, Inference Scripts](#train-validation-inference-scripts) +- [Awesome PyTorch Resources](#awesome-pytorch-resources) +- [Licenses](#licenses) +- [Citing](#citing) + +## What's New + +## July 10, 2026 +* Improve optimizer `torch.compile` and tensor learning-rate support. +* Extend NaFlexViT patch-layout (for NaFlex-CLAP), and `forward_intermediates` (NaFlex dict input) support. +* Harden pickle loading and improve custom-label inference. +* Release 1.0.28 + +## May 27, 2026 +* Add model defs and pretrained weights for EUPE ViT (DINOv3-style) and ConvNeXt models. See the [Efficient Universal Perception Encoder paper](https://arxiv.org/abs/2603.22387). +* Add TIPSv2 model defs and pretrained weights for (DINOv2-style) ViTs. See the [TIPSv2 paper](https://arxiv.org/abs/2604.12012). + +## May 8, 2026 +* Release 1.0.27 + +## April 23, 2026 +* Add Gemma4 ViT encoders w/ NaFlex pipeline support (variable aspect/size per image). Thanks [Yonghye Kwon](https://github.com/developer0hye) +* Support DINOv3 weights in NaFlexVit. Thanks [Yonghye Kwon](https://github.com/developer0hye) +* Some improvements to Muon fallback (AdamW/NadamW) lr behavior + +## March 23, 2026 +* Improve pickle checkpoint handling security. Default all loading to `weights_only=True`, add safe_global for ArgParse. +* Improve attention mask handling for core ViT/EVA models & layers. Resolve bool masks, pass `is_causal` through for SSL tasks. +* Fix class & register token uses with ViT and no pos embed enabled. +* Add Patch Representation Refinement (PRR) as a pooling option in ViT. Thanks Sina (https://github.com/sinahmr). +* Improve consistency of output projection / MLP dimensions for attention pooling layers. +* Hiera model F.SDPA optimization to allow Flash Attention kernel use. +* Caution added to SGDP optimizer. +* Release 1.0.26. First maintenance release since my departure from Hugging Face. + +## Feb 23, 2026 +* Add token distillation training support to distillation task wrappers +* Remove some torch.jit usage in prep for official deprecation +* Caution added to AdamP optimizer +* Call reset_parameters() even if meta-device init so that buffers get init w/ hacks like init_empty_weights +* Tweak Muon optimizer to work with DTensor/FSDP2 (clamp_ instead of clamp_min_, alternate NS branch for DTensor) +* Release 1.0.25 + +## Jan 21, 2026 +* **Compat Break**: Fix oversight w/ QKV vs MLP bias in `ParallelScalingBlock` (& `DiffParallelScalingBlock`) + * Does not impact any trained `timm` models but could impact downstream use. + +## Jan 5 & 6, 2026 +* Release 1.0.24 +* Add new benchmark result csv files for inference timing on all models w/ RTX Pro 6000, 5090, and 4090 cards w/ PyTorch 2.9.1 +* Fix moved module error in deprecated timm.models.layers import path that impacts legacy imports +* Release 1.0.23 + +## Dec 30, 2025 +* Add better NAdaMuon trained `dpwee`, `dwee`, `dlittle` (differential) ViTs with a small boost over previous runs + * https://huggingface.co/timm/vit_dlittle_patch16_reg1_gap_256.sbb_nadamuon_in1k (83.24% top-1) + * https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.80% top-1) + * https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.67% top-1) +* Add a ~21M param `timm` variant of the CSATv2 model at 512x512 & 640x640 + * https://huggingface.co/timm/csatv2_21m.sw_r640_in1k (83.13% top-1) + * https://huggingface.co/timm/csatv2_21m.sw_r512_in1k (82.58% top-1) +* Factor non-persistent param init out of `__init__` into a common method that can be externally called via `init_non_persistent_buffers()` after meta-device init. + +## Dec 12, 2025 +* Add CSATV2 model (thanks https://github.com/gusdlf93) -- a lightweight but high res model with DCT stem & spatial attention. https://huggingface.co/Hyunil/CSATv2 +* Add AdaMuon and NAdaMuon optimizer support to existing `timm` Muon impl. Appears more competitive vs AdamW with familiar hparams for image tasks. +* End of year PR cleanup, merge aspects of several long open PR + * Merge differential attention (`DiffAttention`), add corresponding `DiffParallelScalingBlock` (for ViT), train some wee vits + * https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_in1k + * https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_in1k + * Add a few pooling modules, `LsePlus` and `SimPool` + * Cleanup, optimize `DropBlock2d` (also add support to ByobNet based models) +* Bump unit tests to PyTorch 2.9.1 + Python 3.13 on upper end, lower still PyTorch 1.13 + Python 3.10 + +## Dec 1, 2025 +* Add lightweight task abstraction, add logits and feature distillation support to train script via new tasks. +* Remove old APEX AMP support + +## Nov 4, 2025 +* Fix LayerScale / LayerScale2d init bug (init values ignored), introduced in 1.0.21. Thanks https://github.com/Ilya-Fradlin +* Release 1.0.22 + +## Oct 31, 2025 🎃 +* Update imagenet & OOD variant result csv files to include a few new models and verify correctness over several torch & timm versions +* EfficientNet-X and EfficientNet-H B5 model weights added as part of a hparam search for AdamW vs Muon (still iterating on Muon runs) + +## Oct 16-20, 2025 +* Add an impl of the Muon optimizer (based on https://github.com/KellerJordan/Muon) with customizations + * extra flexibility and improved handling for conv weights and fallbacks for weight shapes not suited for orthogonalization + * small speedup for NS iterations by reducing allocs and using fused (b)add(b)mm ops + * by default uses AdamW (or NAdamW if `nesterov=True`) updates if muon not suitable for parameter shape (or excluded via param group flag) + * like torch impl, select from several LR scale adjustment fns via `adjust_lr_fn` + * select from several NS coefficient presets or specify your own via `ns_coefficients` +* First 2 steps of 'meta' device model initialization supported + * Fix several ops that were breaking creation under 'meta' device context + * Add device & dtype factory kwarg support to all models and modules (anything inherting from nn.Module) in `timm` +* License fields added to pretrained cfgs in code +* Release 1.0.21 + +## Sept 21, 2025 +* Remap DINOv3 ViT weight tags from `lvd_1689m` -> `lvd1689m` to match (same for `sat_493m` -> `sat493m`) +* Release 1.0.20 + +## Sept 17, 2025 +* DINOv3 (https://arxiv.org/abs/2508.10104) ConvNeXt and ViT models added. ConvNeXt models were mapped to existing `timm` model. ViT support done via the EVA base model w/ a new `RotaryEmbeddingDinoV3` to match the DINOv3 specific RoPE impl + * HuggingFace Hub: https://huggingface.co/collections/timm/timm-dinov3-68cb08bb0bee365973d52a4d +* MobileCLIP-2 (https://arxiv.org/abs/2508.20691) vision encoders. New MCI3/MCI4 FastViT variants added and weights mapped to existing FastViT and B, L/14 ViTs. +* MetaCLIP-2 Worldwide (https://arxiv.org/abs/2507.22062) ViT encoder weights added. +* SigLIP-2 (https://arxiv.org/abs/2502.14786) NaFlex ViT encoder weights added via timm NaFlexViT model. +* Misc fixes and contributions + +## July 23, 2025 +* Add `set_input_size()` method to EVA models, used by OpenCLIP 3.0.0 to allow resizing for timm based encoder models. +* Release 1.0.18, needed for PE-Core S & T models in OpenCLIP 3.0.0 +* Fix small typing issue that broke Python 3.9 compat. 1.0.19 patch release. + +## July 21, 2025 +* ROPE support added to NaFlexViT. All models covered by the EVA base (`eva.py`) including EVA, EVA02, Meta PE ViT, `timm` SBB ViT w/ ROPE, and Naver ROPE-ViT can be now loaded in NaFlexViT when `use_naflex=True` passed at model creation time +* More Meta PE ViT encoders added, including small/tiny variants, lang variants w/ tiling, and more spatial variants. +* PatchDropout fixed with NaFlexViT and also w/ EVA models (regression after adding Naver ROPE-ViT) +* Fix XY order with grid_indexing='xy', impacted non-square image use in 'xy' mode (only ROPE-ViT and PE impacted). + +## July 7, 2025 +* MobileNet-v5 backbone tweaks for improved Google Gemma 3n behaviour (to pair with updated official weights) + * Add stem bias (zero'd in updated weights, compat break with old weights) + * GELU -> GELU (tanh approx). A minor change to be closer to JAX +* Add two arguments to layer-decay support, a min scale clamp and 'no optimization' scale threshold +* Add 'Fp32' LayerNorm, RMSNorm, SimpleNorm variants that can be enabled to force computation of norm in float32 +* Some typing, argument cleanup for norm, norm+act layers done with above +* Support Naver ROPE-ViT (https://github.com/naver-ai/rope-vit) in `eva.py`, add RotaryEmbeddingMixed module for mixed mode, weights on HuggingFace Hub + +|model |img_size|top1 |top5 |param_count| +|--------------------------------------------------|--------|------|------|-----------| +|vit_large_patch16_rope_mixed_ape_224.naver_in1k |224 |84.84 |97.122|304.4 | +|vit_large_patch16_rope_mixed_224.naver_in1k |224 |84.828|97.116|304.2 | +|vit_large_patch16_rope_ape_224.naver_in1k |224 |84.65 |97.154|304.37 | +|vit_large_patch16_rope_224.naver_in1k |224 |84.648|97.122|304.17 | +|vit_base_patch16_rope_mixed_ape_224.naver_in1k |224 |83.894|96.754|86.59 | +|vit_base_patch16_rope_mixed_224.naver_in1k |224 |83.804|96.712|86.44 | +|vit_base_patch16_rope_ape_224.naver_in1k |224 |83.782|96.61 |86.59 | +|vit_base_patch16_rope_224.naver_in1k |224 |83.718|96.672|86.43 | +|vit_small_patch16_rope_224.naver_in1k |224 |81.23 |95.022|21.98 | +|vit_small_patch16_rope_mixed_224.naver_in1k |224 |81.216|95.022|21.99 | +|vit_small_patch16_rope_ape_224.naver_in1k |224 |81.004|95.016|22.06 | +|vit_small_patch16_rope_mixed_ape_224.naver_in1k |224 |80.986|94.976|22.06 | +* Some cleanup of ROPE modules, helpers, and FX tracing leaf registration +* Preparing version 1.0.17 release + +## June 26, 2025 +* MobileNetV5 backbone (w/ encoder only variant) for [Gemma 3n](https://ai.google.dev/gemma/docs/gemma-3n#parameters) image encoder +* Version 1.0.16 released + +## June 23, 2025 +* Add F.grid_sample based 2D and factorized pos embed resize to NaFlexViT. Faster when lots of different sizes (based on example by https://github.com/stas-sl). +* Further speed up patch embed resample by replacing vmap with matmul (based on snippet by https://github.com/stas-sl). +* Add 3 initial native aspect NaFlexViT checkpoints created while testing, ImageNet-1k and 3 different pos embed configs w/ same hparams. + + | Model | Top-1 Acc | Top-5 Acc | Params (M) | Eval Seq Len | + |:---|:---:|:---:|:---:|:---:| + | [naflexvit_base_patch16_par_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_par_gap.e300_s576_in1k) | 83.67 | 96.45 | 86.63 | 576 | + | [naflexvit_base_patch16_parfac_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_parfac_gap.e300_s576_in1k) | 83.63 | 96.41 | 86.46 | 576 | + | [naflexvit_base_patch16_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_gap.e300_s576_in1k) | 83.50 | 96.46 | 86.63 | 576 | +* Support gradient checkpointing for `forward_intermediates` and fix some checkpointing bugs. Thanks https://github.com/brianhou0208 +* Add 'corrected weight decay' (https://arxiv.org/abs/2506.02285) as option to AdamW (legacy), Adopt, Kron, Adafactor (BV), Lamb, LaProp, Lion, NadamW, RmsPropTF, SGDW optimizers +* Switch PE (perception encoder) ViT models to use native timm weights instead of remapping on the fly +* Fix cuda stream bug in prefetch loader + +## June 5, 2025 +* Initial NaFlexVit model code. NaFlexVit is a Vision Transformer with: + 1. Encapsulated embedding and position encoding in a single module + 2. Support for nn.Linear patch embedding on pre-patchified (dictionary) inputs + 3. Support for NaFlex variable aspect, variable resolution (SigLip-2: https://arxiv.org/abs/2502.14786) + 4. Support for FlexiViT variable patch size (https://arxiv.org/abs/2212.08013) + 5. Support for NaViT fractional/factorized position embedding (https://arxiv.org/abs/2307.06304) +* Existing vit models in `vision_transformer.py` can be loaded into the NaFlexVit model by adding the `use_naflex=True` flag to `create_model` + * Some native weights coming soon +* A full NaFlex data pipeline is available that allows training / fine-tuning / evaluating with variable aspect / size images + * To enable in `train.py` and `validate.py` add the `--naflex-loader` arg, must be used with a NaFlexVit +* To evaluate an existing (classic) ViT loaded in NaFlexVit model w/ NaFlex data pipe: + * `python validate.py /imagenet --amp -j 8 --model vit_base_patch16_224 --model-kwargs use_naflex=True --naflex-loader --naflex-max-seq-len 256` +* The training has some extra args features worth noting + * The `--naflex-train-seq-lens'` argument specifies which sequence lengths to randomly pick from per batch during training + * The `--naflex-max-seq-len` argument sets the target sequence length for validation + * Adding `--model-kwargs enable_patch_interpolator=True --naflex-patch-sizes 12 16 24` will enable random patch size selection per-batch w/ interpolation + * The `--naflex-loss-scale` arg changes loss scaling mode per batch relative to the batch size, `timm` NaFlex loading changes the batch size for each seq len + +## May 28, 2025 +* Add a number of small/fast models thanks to https://github.com/brianhou0208 + * SwiftFormer - [(ICCV2023) SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications](https://github.com/Amshaker/SwiftFormer) + * FasterNet - [(CVPR2023) Run, Don’t Walk: Chasing Higher FLOPS for Faster Neural Networks](https://github.com/JierunChen/FasterNet) + * SHViT - [(CVPR2024) SHViT: Single-Head Vision Transformer with Memory Efficient](https://github.com/ysj9909/SHViT) + * StarNet - [(CVPR2024) Rewrite the Stars](https://github.com/ma-xu/Rewrite-the-Stars) + * GhostNet-V3 [GhostNetV3: Exploring the Training Strategies for Compact Models](https://github.com/huawei-noah/Efficient-AI-Backbones/tree/master/ghostnetv3_pytorch) +* Update EVA ViT (closest match) to support Perception Encoder models (https://arxiv.org/abs/2504.13181) from Meta, loading Hub weights but I still need to push dedicated `timm` weights + * Add some flexibility to ROPE impl +* Big increase in number of models supporting `forward_intermediates()` and some additional fixes thanks to https://github.com/brianhou0208 + * DaViT, EdgeNeXt, EfficientFormerV2, EfficientViT(MIT), EfficientViT(MSRA), FocalNet, GCViT, HGNet /V2, InceptionNeXt, Inception-V4, MambaOut, MetaFormer, NesT, Next-ViT, PiT, PVT V2, RepGhostNet, RepViT, ResNetV2, ReXNet, TinyViT, TResNet, VoV +* TNT model updated w/ new weights `forward_intermediates()` thanks to https://github.com/brianhou0208 +* Add `local-dir:` pretrained schema, can use `local-dir:/path/to/model/folder` for model name to source model / pretrained cfg & weights Hugging Face Hub models (config.json + weights file) from a local folder. +* Fixes, improvements for onnx export + +## Feb 21, 2025 +* SigLIP 2 ViT image encoders added (https://huggingface.co/collections/timm/siglip-2-67b8e72ba08b09dd97aecaf9) + * Variable resolution / aspect NaFlex versions are a WIP +* Add 'SO150M2' ViT weights trained with SBB recipes, great results, better for ImageNet than previous attempt w/ less training. + * `vit_so150m2_patch16_reg1_gap_448.sbb_e200_in12k_ft_in1k` - 88.1% top-1 + * `vit_so150m2_patch16_reg1_gap_384.sbb_e200_in12k_ft_in1k` - 87.9% top-1 + * `vit_so150m2_patch16_reg1_gap_256.sbb_e200_in12k_ft_in1k` - 87.3% top-1 + * `vit_so150m2_patch16_reg4_gap_256.sbb_e200_in12k` +* Updated InternViT-300M '2.5' weights +* Release 1.0.15 + +## Feb 1, 2025 +* FYI PyTorch 2.6 & Python 3.13 are tested and working w/ current main and released version of `timm` + +## Jan 27, 2025 +* Add Kron Optimizer (PSGD w/ Kronecker-factored preconditioner) + * Code from https://github.com/evanatyourservice/kron_torch + * See also https://sites.google.com/site/lixilinx/home/psgd + +## Jan 19, 2025 +* Fix loading of LeViT safetensor weights, remove conversion code which should have been deactivated +* Add 'SO150M' ViT weights trained with SBB recipes, decent results, but not optimal shape for ImageNet-12k/1k pretrain/ft + * `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k_ft_in1k` - 86.7% top-1 + * `vit_so150m_patch16_reg4_gap_384.sbb_e250_in12k_ft_in1k` - 87.4% top-1 + * `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k` +* Misc typing, typo, etc. cleanup +* 1.0.14 release to get above LeViT fix out + +## Jan 9, 2025 +* Add support to train and validate in pure `bfloat16` or `float16` +* `wandb` project name arg added by https://github.com/caojiaolong, use arg.experiment for name +* Fix old issue w/ checkpoint saving not working on filesystem w/o hard-link support (e.g. FUSE fs mounts) +* 1.0.13 release + +## Jan 6, 2025 +* Add `torch.utils.checkpoint.checkpoint()` wrapper in `timm.models` that defaults `use_reentrant=False`, unless `TIMM_REENTRANT_CKPT=1` is set in env. + +## Dec 31, 2024 +* `convnext_nano` 384x384 ImageNet-12k pretrain & fine-tune. https://huggingface.co/models?search=convnext_nano%20r384 +* Add AIM-v2 encoders from https://github.com/apple/ml-aim, see on Hub: https://huggingface.co/models?search=timm%20aimv2 +* Add PaliGemma2 encoders from https://github.com/google-research/big_vision to existing PaliGemma, see on Hub: https://huggingface.co/models?search=timm%20pali2 +* Add missing L/14 DFN2B 39B CLIP ViT, `vit_large_patch14_clip_224.dfn2b_s39b` +* Fix existing `RmsNorm` layer & fn to match standard formulation, use PT 2.5 impl when possible. Move old impl to `SimpleNorm` layer, it's LN w/o centering or bias. There were only two `timm` models using it, and they have been updated. +* Allow override of `cache_dir` arg for model creation +* Pass through `trust_remote_code` for HF datasets wrapper +* `inception_next_atto` model added by creator +* Adan optimizer caution, and Lamb decoupled weight decay options +* Some feature_info metadata fixed by https://github.com/brianhou0208 +* All OpenCLIP and JAX (CLIP, SigLIP, Pali, etc) model weights that used load time remapping were given their own HF Hub instances so that they work with `hf-hub:` based loading, and thus will work with new Transformers `TimmWrapperModel` + +## Introduction + +Py**T**orch **Im**age **M**odels (`timm`) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results. + +The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything. + +## Features + +### Models + +All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated. + +* Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723 +* BEiT - https://arxiv.org/abs/2106.08254 +* BEiT-V2 - https://arxiv.org/abs/2208.06366 +* BEiT3 - https://arxiv.org/abs/2208.10442 +* Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370 +* Bottleneck Transformers - https://arxiv.org/abs/2101.11605 +* CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239 +* CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399 +* CoAtNet (Convolution and Attention) - https://arxiv.org/abs/2106.04803 +* ConvNeXt - https://arxiv.org/abs/2201.03545 +* ConvNeXt-V2 - http://arxiv.org/abs/2301.00808 +* ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697 +* CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929 +* DeiT - https://arxiv.org/abs/2012.12877 +* DeiT-III - https://arxiv.org/pdf/2204.07118.pdf +* DenseNet - https://arxiv.org/abs/1608.06993 +* DLA - https://arxiv.org/abs/1707.06484 +* DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629 +* EdgeNeXt - https://arxiv.org/abs/2206.10589 +* EfficientFormer - https://arxiv.org/abs/2206.01191 +* EfficientFormer-V2 - https://arxiv.org/abs/2212.08059 +* EfficientNet (MBConvNet Family) + * EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252 + * EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665 + * EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946 + * EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html + * EfficientNet V2 - https://arxiv.org/abs/2104.00298 + * FBNet-C - https://arxiv.org/abs/1812.03443 + * MixNet - https://arxiv.org/abs/1907.09595 + * MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626 + * MobileNet-V2 - https://arxiv.org/abs/1801.04381 + * Single-Path NAS - https://arxiv.org/abs/1904.02877 + * TinyNet - https://arxiv.org/abs/2010.14819 +* EfficientViT (MIT) - https://arxiv.org/abs/2205.14756 +* EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027 +* EVA - https://arxiv.org/abs/2211.07636 +* EVA-02 - https://arxiv.org/abs/2303.11331 +* FasterNet - https://arxiv.org/abs/2303.03667 +* FastViT - https://arxiv.org/abs/2303.14189 +* FlexiViT - https://arxiv.org/abs/2212.08013 +* FocalNet (Focal Modulation Networks) - https://arxiv.org/abs/2203.11926 +* GCViT (Global Context Vision Transformer) - https://arxiv.org/abs/2206.09959 +* GhostNet - https://arxiv.org/abs/1911.11907 +* GhostNet-V2 - https://arxiv.org/abs/2211.12905 +* GhostNet-V3 - https://arxiv.org/abs/2404.11202 +* gMLP - https://arxiv.org/abs/2105.08050 +* GPU-Efficient Networks - https://arxiv.org/abs/2006.14090 +* Halo Nets - https://arxiv.org/abs/2103.12731 +* HGNet / HGNet-V2 - TBD +* HRNet - https://arxiv.org/abs/1908.07919 +* InceptionNeXt - https://arxiv.org/abs/2303.16900 +* Inception-V3 - https://arxiv.org/abs/1512.00567 +* Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261 +* Lambda Networks - https://arxiv.org/abs/2102.08602 +* LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136 +* MambaOut - https://arxiv.org/abs/2405.07992 +* MaxViT (Multi-Axis Vision Transformer) - https://arxiv.org/abs/2204.01697 +* MetaFormer (PoolFormer-v2, ConvFormer, CAFormer) - https://arxiv.org/abs/2210.13452 +* MLP-Mixer - https://arxiv.org/abs/2105.01601 +* MobileCLIP - https://arxiv.org/abs/2311.17049 +* MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244 + * FBNet-V3 - https://arxiv.org/abs/2006.02049 + * HardCoRe-NAS - https://arxiv.org/abs/2102.11646 + * LCNet - https://arxiv.org/abs/2109.15099 +* MobileNetV4 - https://arxiv.org/abs/2404.10518 +* MobileOne - https://arxiv.org/abs/2206.04040 +* MobileViT - https://arxiv.org/abs/2110.02178 +* MobileViT-V2 - https://arxiv.org/abs/2206.02680 +* MViT-V2 (Improved Multiscale Vision Transformer) - https://arxiv.org/abs/2112.01526 +* NASNet-A - https://arxiv.org/abs/1707.07012 +* NesT - https://arxiv.org/abs/2105.12723 +* Next-ViT - https://arxiv.org/abs/2207.05501 +* NFNet-F - https://arxiv.org/abs/2102.06171 +* NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692 +* PE (Perception Encoder) - https://arxiv.org/abs/2504.13181 +* PNasNet - https://arxiv.org/abs/1712.00559 +* PoolFormer (MetaFormer) - https://arxiv.org/abs/2111.11418 +* Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302 +* PVT-V2 (Improved Pyramid Vision Transformer) - https://arxiv.org/abs/2106.13797 +* RDNet (DenseNets Reloaded) - https://arxiv.org/abs/2403.19588 +* RegNet - https://arxiv.org/abs/2003.13678 +* RegNetZ - https://arxiv.org/abs/2103.06877 +* RepVGG - https://arxiv.org/abs/2101.03697 +* RepGhostNet - https://arxiv.org/abs/2211.06088 +* RepViT - https://arxiv.org/abs/2307.09283 +* ResMLP - https://arxiv.org/abs/2105.03404 +* ResNet/ResNeXt + * ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385 + * ResNeXt - https://arxiv.org/abs/1611.05431 + * 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187 + * Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932 + * Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546 + * ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4 + * Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507 + * ResNet-RS - https://arxiv.org/abs/2103.07579 +* Res2Net - https://arxiv.org/abs/1904.01169 +* ResNeSt - https://arxiv.org/abs/2004.08955 +* ReXNet - https://arxiv.org/abs/2007.00992 +* ROPE-ViT - https://arxiv.org/abs/2403.13298 +* SelecSLS - https://arxiv.org/abs/1907.00837 +* Selective Kernel Networks - https://arxiv.org/abs/1903.06586 +* Sequencer2D - https://arxiv.org/abs/2205.01972 +* SHViT - https://arxiv.org/abs/2401.16456 +* SigLIP (image encoder) - https://arxiv.org/abs/2303.15343 +* SigLIP 2 (image encoder) - https://arxiv.org/abs/2502.14786 +* StarNet - https://arxiv.org/abs/2403.19967 +* SwiftFormer - https://arxiv.org/pdf/2303.15446 +* Swin S3 (AutoFormerV2) - https://arxiv.org/abs/2111.14725 +* Swin Transformer - https://arxiv.org/abs/2103.14030 +* Swin Transformer V2 - https://arxiv.org/abs/2111.09883 +* TinyViT - https://arxiv.org/abs/2207.10666 +* Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112 +* TResNet - https://arxiv.org/abs/2003.13630 +* Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf +* VGG - https://arxiv.org/abs/1409.1556 +* Visformer - https://arxiv.org/abs/2104.12533 +* Vision Transformer - https://arxiv.org/abs/2010.11929 +* ViTamin - https://arxiv.org/abs/2404.02132 +* VOLO (Vision Outlooker) - https://arxiv.org/abs/2106.13112 +* VovNet V2 and V1 - https://arxiv.org/abs/1911.06667 +* Xception - https://arxiv.org/abs/1610.02357 +* Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611 +* Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611 +* XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681 + +### Optimizers +To see full list of optimizers w/ descriptions: `timm.optim.list_optimizers(with_description=True)` + +Included optimizers available via `timm.optim.create_optimizer_v2` factory method: +* `adabelief` an implementation of AdaBelief adapted from https://github.com/juntang-zhuang/Adabelief-Optimizer - https://arxiv.org/abs/2010.07468 +* `adafactor` adapted from [FAIRSeq impl](https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py) - https://arxiv.org/abs/1804.04235 +* `adafactorbv` adapted from [Big Vision](https://github.com/google-research/big_vision/blob/main/big_vision/optax.py) - https://arxiv.org/abs/2106.04560 +* `adahessian` by [David Samuel](https://github.com/davda54/ada-hessian) - https://arxiv.org/abs/2006.00719 +* `adamp` and `sgdp` by [Naver ClovAI](https://github.com/clovaai) - https://arxiv.org/abs/2006.08217 +* `adamuon` and `nadamuon` as per https://github.com/Chongjie-Si/AdaMuon - https://arxiv.org/abs/2507.11005 +* `adan` an implementation of Adan adapted from https://github.com/sail-sg/Adan - https://arxiv.org/abs/2208.06677 +* `adopt` ADOPT adapted from https://github.com/iShohei220/adopt - https://arxiv.org/abs/2411.02853 +* `kron` PSGD w/ Kronecker-factored preconditioner from https://github.com/evanatyourservice/kron_torch - https://sites.google.com/site/lixilinx/home/psgd +* `lamb` an implementation of Lamb and LambC (w/ trust-clipping) cleaned up and modified to support use with XLA - https://arxiv.org/abs/1904.00962 +* `laprop` optimizer from https://github.com/Z-T-WANG/LaProp-Optimizer - https://arxiv.org/abs/2002.04839 +* `lars` an implementation of LARS and LARC (w/ trust-clipping) - https://arxiv.org/abs/1708.03888 +* `lion` and implementation of Lion adapted from https://github.com/google/automl/tree/master/lion - https://arxiv.org/abs/2302.06675 +* `lookahead` adapted from impl by [Liam](https://github.com/alphadl/lookahead.pytorch) - https://arxiv.org/abs/1907.08610 +* `madgrad` an implementation of MADGRAD adapted from https://github.com/facebookresearch/madgrad - https://arxiv.org/abs/2101.11075 +* `mars` MARS optimizer from https://github.com/AGI-Arena/MARS - https://arxiv.org/abs/2411.10438 +* `muon` MUON optimizer from https://github.com/KellerJordan/Muon with numerous additions and improved non-transformer behaviour +* `nadam` an implementation of Adam w/ Nesterov momentum +* `nadamw` an implementation of AdamW (Adam w/ decoupled weight-decay) w/ Nesterov momentum. A simplified impl based on https://github.com/mlcommons/algorithmic-efficiency +* `novograd` by [Masashi Kimura](https://github.com/convergence-lab/novograd) - https://arxiv.org/abs/1905.11286 +* `radam` by [Liyuan Liu](https://github.com/LiyuanLucasLiu/RAdam) - https://arxiv.org/abs/1908.03265 +* `rmsprop_tf` adapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behaviour +* `sgdw` and implementation of SGD w/ decoupled weight-decay +* `fused` optimizers by name with [NVIDIA Apex](https://github.com/NVIDIA/apex/tree/master/apex/optimizers) installed +* `bnb` optimizers by name with [BitsAndBytes](https://github.com/TimDettmers/bitsandbytes) installed +* `cadamw`, `clion`, and more 'Cautious' optimizers from https://github.com/kyleliang919/C-Optim - https://arxiv.org/abs/2411.16085 +* `adam`, `adamw`, `rmsprop`, `adadelta`, `adagrad`, and `sgd` pass through to `torch.optim` implementations +* `c` suffix (eg `adamc`, `nadamc` to implement 'corrected weight decay' in https://arxiv.org/abs/2506.02285) + +### Augmentations +* Random Erasing from [Zhun Zhong](https://github.com/zhunzhong07/Random-Erasing/blob/master/transforms.py) - https://arxiv.org/abs/1708.04896) +* Mixup - https://arxiv.org/abs/1710.09412 +* CutMix - https://arxiv.org/abs/1905.04899 +* AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py) +* AugMix w/ JSD loss, JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well - https://arxiv.org/abs/1912.02781 +* SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data + +### Regularization +* DropPath aka "Stochastic Depth" - https://arxiv.org/abs/1603.09382 +* DropBlock - https://arxiv.org/abs/1810.12890 +* Blur Pooling - https://arxiv.org/abs/1904.11486 + +### Other + +Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP: + +* All models have a common default configuration interface and API for + * accessing/changing the classifier - `get_classifier` and `reset_classifier` + * doing a forward pass on just the features - `forward_features` (see [documentation](https://huggingface.co/docs/timm/feature_extraction)) + * these makes it easy to write consistent network wrappers that work with any of the models +* All models support multi-scale feature map extraction (feature pyramids) via create_model (see [documentation](https://huggingface.co/docs/timm/feature_extraction)) + * `create_model(name, features_only=True, out_indices=..., output_stride=...)` + * `out_indices` creation arg specifies which feature maps to return, these indices are 0 based and generally correspond to the `C(i + 1)` feature level. + * `output_stride` creation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this. + * feature map channel counts, reduction level (stride) can be queried AFTER model creation via the `.feature_info` member +* All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired +* High performance [reference training, validation, and inference scripts](https://huggingface.co/docs/timm/training_script) that work in several process/GPU modes: + * NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional) + * PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled) + * PyTorch w/ single GPU single process (AMP optional) +* A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights. +* A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs) +* Learning rate schedulers + * Ideas adopted from + * [AllenNLP schedulers](https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers) + * [FAIRseq lr_scheduler](https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler) + * SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983) + * Schedulers include `step`, `cosine` w/ restarts, `tanh` w/ restarts, `plateau` +* Space-to-Depth by [mrT23](https://github.com/mrT23/TResNet/blob/master/src/models/tresnet/layers/space_to_depth.py) (https://arxiv.org/abs/1801.04590) +* Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets) +* An extensive selection of channel and/or spatial attention modules: + * Bottleneck Transformer - https://arxiv.org/abs/2101.11605 + * CBAM - https://arxiv.org/abs/1807.06521 + * Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667 + * Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151 + * Gather-Excite (GE) - https://arxiv.org/abs/1810.12348 + * Global Context (GC) - https://arxiv.org/abs/1904.11492 + * Halo - https://arxiv.org/abs/2103.12731 + * Involution - https://arxiv.org/abs/2103.06255 + * Lambda Layer - https://arxiv.org/abs/2102.08602 + * Non-Local (NL) - https://arxiv.org/abs/1711.07971 + * Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507 + * Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586 + * Split (SPLAT) - https://arxiv.org/abs/2004.08955 + * Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030 + +## Results + +Model validation results can be found in the [results tables](results/README.md) + +## Getting Started (Documentation) + +The official documentation can be found at https://huggingface.co/docs/hub/timm. Documentation contributions are welcome. + +[Getting Started with PyTorch Image Models (timm): A Practitioner’s Guide](https://towardsdatascience.com/getting-started-with-pytorch-image-models-timm-a-practitioners-guide-4e77b4bf9055-2/) by [Chris Hughes](https://github.com/Chris-hughes10) is an extensive blog post covering many aspects of `timm` in detail. + +[timmdocs](http://timm.fast.ai/) is an alternate set of documentation for `timm`. A big thanks to [Aman Arora](https://github.com/amaarora) for his efforts creating timmdocs. + +[paperswithcode](https://paperswithcode.com/lib/timm) is a good resource for browsing the models within `timm`. + +## Train, Validation, Inference Scripts + +The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See [documentation](https://huggingface.co/docs/timm/training_script). + +## Awesome PyTorch Resources + +One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below. + +### Object Detection, Instance and Semantic Segmentation +* Detectron2 - https://github.com/facebookresearch/detectron2 +* Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch +* EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch + +### Computer Vision / Image Augmentation +* Albumentations - https://github.com/albumentations-team/albumentations +* Kornia - https://github.com/kornia/kornia + +### Knowledge Distillation +* RepDistiller - https://github.com/HobbitLong/RepDistiller +* torchdistill - https://github.com/yoshitomo-matsubara/torchdistill + +### Metric Learning +* PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning + +### Training / Frameworks +* fastai - https://github.com/fastai/fastai +* lightly_train - https://github.com/lightly-ai/lightly-train + +### Deployment +* timmx (Export timm models to ONNX, CoreML, LiteRT, TensorRT, and more) - https://github.com/Boulaouaney/timmx + +## Licenses + +### Code +The code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue. + +### Pretrained Weights +So far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product. + +#### Pretrained on more than ImageNet +Several weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions. + +## Citing + +### BibTeX + +```bibtex +@misc{rw2019timm, + author = {Ross Wightman}, + title = {PyTorch Image Models}, + year = {2019}, + publisher = {GitHub}, + journal = {GitHub repository}, + doi = {10.5281/zenodo.4414861}, + howpublished = {\url{https://github.com/rwightman/pytorch-image-models}} +} +``` + +### Latest DOI + +[![DOI](https://zenodo.org/badge/168799526.svg)](https://zenodo.org/badge/latestdoi/168799526) diff --git a/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b b/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b new file mode 100644 index 0000000000000000000000000000000000000000..d3fb4e2507529ba7c064aa3c50f73b26df40c024 Binary files /dev/null and b/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b differ diff --git a/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b.body b/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b.body new file mode 100644 index 0000000000000000000000000000000000000000..168fb2708c1a5d4cf50f799482acf6471c655037 --- /dev/null +++ b/.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f88193799d43dbf8c8a806d6405c9c52fe2af40bf75072a606357b33cc336c7f +size 621541 diff --git a/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c b/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c new file mode 100644 index 0000000000000000000000000000000000000000..d0323b6f5192206a69b8e671273d95241732ae47 Binary files /dev/null and b/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c differ diff --git a/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c.body b/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c.body new file mode 100644 index 0000000000000000000000000000000000000000..11d90086013cf9b671d9c66ee3f20a192e66b9c7 --- /dev/null +++ b/.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ec8606e8564f19e74ee05178d79403f084fa95690edb143c40fbbedc6c5360c +size 119472 diff --git a/.cache/pip/http-v2/b/9/9/a/d/b99ad330dfd2e9e0337861ace33d07fca2ddfd480ba4473963ebc23d b/.cache/pip/http-v2/b/9/9/a/d/b99ad330dfd2e9e0337861ace33d07fca2ddfd480ba4473963ebc23d new file mode 100644 index 0000000000000000000000000000000000000000..63afe251791261fdcac327ecb3ca000a9f00e44f Binary files /dev/null and b/.cache/pip/http-v2/b/9/9/a/d/b99ad330dfd2e9e0337861ace33d07fca2ddfd480ba4473963ebc23d differ diff --git a/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95 b/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95 new file mode 100644 index 0000000000000000000000000000000000000000..50d7df550c501c5132515a3873abb1b1e4af1578 Binary files /dev/null and b/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95 differ diff --git a/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95.body b/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95.body new file mode 100644 index 0000000000000000000000000000000000000000..0d9df734bf60fd465d9c4c9f92cfb5f3b71eed98 Binary files /dev/null and b/.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95.body differ diff --git a/.cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124.body b/.cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124.body new file mode 100644 index 0000000000000000000000000000000000000000..9d69d8498d998c34665eed7493a7cfa71ae212b8 --- /dev/null +++ b/.cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:294158e2f650b2fbdd2647a2ee713502b6f4b27a4092c35ad6e0749ddc34f0f4 +size 237138 diff --git a/.cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5.body b/.cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5.body new file mode 100644 index 0000000000000000000000000000000000000000..a743e0b3b1a95d98926178c5d1a3aab3c8e6ea2e --- /dev/null +++ b/.cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e577b88da96b3a722ea5e2f042455ce6f715d398304d8e63b17d126ed7d89968 +size 2597944 diff --git a/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b b/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b new file mode 100644 index 0000000000000000000000000000000000000000..d553e2c397c1261cffe8f975988f2107bf3b9fd7 Binary files /dev/null and b/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b differ diff --git a/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b.body b/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b.body new file mode 100644 index 0000000000000000000000000000000000000000..3eee724166b8ba6132c01f452f7df3c1975a5b2c --- /dev/null +++ b/.cache/pip/http-v2/d/d/2/0/6/dd206ee8d449d4bec512242e8f8ebadb5a808c682766018f3921f62b.body @@ -0,0 +1,51 @@ +Metadata-Version: 2.1 +Name: et_xmlfile +Version: 2.0.0 +Summary: An implementation of lxml.xmlfile for the standard library +Home-page: https://foss.heptapod.net/openpyxl/et_xmlfile +Author: See AUTHORS.txt +Author-email: charlie.clark@clark-consulting.eu +License: MIT +Project-URL: Documentation, https://openpyxl.pages.heptapod.net/et_xmlfile/ +Project-URL: Source, https://foss.heptapod.net/openpyxl/et_xmlfile +Project-URL: Tracker, https://foss.heptapod.net/openpyxl/et_xmfile/-/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Requires-Python: >=3.8 +License-File: LICENCE.python +License-File: LICENCE.rst +License-File: AUTHORS.txt + +.. image:: https://foss.heptapod.net/openpyxl/et_xmlfile/badges/branch/default/coverage.svg + :target: https://coveralls.io/bitbucket/openpyxl/et_xmlfile?branch=default + :alt: coverage status + +et_xmfile +========= + +XML can use lots of memory, and et_xmlfile is a low memory library for creating large XML files +And, although the standard library already includes an incremental parser, `iterparse` it has no equivalent when writing XML. Once an element has been added to the tree, it is written to +the file or stream and the memory is then cleared. + +This module is based upon the `xmlfile module from lxml `_ with the aim of allowing code to be developed that will work with both libraries. +It was developed initially for the openpyxl project, but is now a standalone module. + +The code was written by Elias Rabel as part of the `Python Düsseldorf `_ openpyxl sprint in September 2014. + +Proper support for incremental writing was provided by Daniel Hillier in 2024 + +Note on performance +------------------- + +The code was not developed with performance in mind, but turned out to be faster than the existing SAX-based implementation but is generally slower than lxml's xmlfile. +There is one area where an optimisation for lxml may negatively affect the performance of et_xmfile and that is when using the `.element()` method on the xmlfile context manager. It is, therefore, recommended simply to create Elements write these directly, as in the sample code. diff --git a/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a b/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a new file mode 100644 index 0000000000000000000000000000000000000000..1f3ba47d225b805004abca0dff207a8cafc54f5c Binary files /dev/null and b/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a differ diff --git a/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a.body b/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a.body new file mode 100644 index 0000000000000000000000000000000000000000..4c2e965a65fe50b3fd33366aa104252b9041d846 Binary files /dev/null and b/.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8a.body differ diff --git a/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d b/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d new file mode 100644 index 0000000000000000000000000000000000000000..a5968d49606bdcca92c465b29280effd3ee691ae Binary files /dev/null and b/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d differ diff --git a/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d.body b/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d.body new file mode 100644 index 0000000000000000000000000000000000000000..45ab2f7ba55964bf3f1c7d08c53b708b0f353fc1 --- /dev/null +++ b/.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d.body @@ -0,0 +1,139 @@ +Metadata-Version: 2.4 +Name: alembic +Version: 1.18.5 +Summary: A database migration tool for SQLAlchemy. +Author-email: Mike Bayer +License-Expression: MIT +Project-URL: Homepage, https://alembic.sqlalchemy.org +Project-URL: Documentation, https://alembic.sqlalchemy.org/en/latest/ +Project-URL: Changelog, https://alembic.sqlalchemy.org/en/latest/changelog.html +Project-URL: Source, https://github.com/sqlalchemy/alembic/ +Project-URL: Issue Tracker, https://github.com/sqlalchemy/alembic/issues/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Environment :: Console +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Database :: Front-Ends +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: SQLAlchemy>=1.4.23 +Requires-Dist: Mako +Requires-Dist: typing-extensions>=4.12 +Requires-Dist: tomli; python_version < "3.11" +Provides-Extra: tz +Requires-Dist: tzdata; extra == "tz" +Dynamic: license-file + +Alembic is a database migrations tool written by the author +of `SQLAlchemy `_. A migrations tool +offers the following functionality: + +* Can emit ALTER statements to a database in order to change + the structure of tables and other constructs +* Provides a system whereby "migration scripts" may be constructed; + each script indicates a particular series of steps that can "upgrade" a + target database to a new version, and optionally a series of steps that can + "downgrade" similarly, doing the same steps in reverse. +* Allows the scripts to execute in some sequential manner. + +The goals of Alembic are: + +* Very open ended and transparent configuration and operation. A new + Alembic environment is generated from a set of templates which is selected + among a set of options when setup first occurs. The templates then deposit a + series of scripts that define fully how database connectivity is established + and how migration scripts are invoked; the migration scripts themselves are + generated from a template within that series of scripts. The scripts can + then be further customized to define exactly how databases will be + interacted with and what structure new migration files should take. +* Full support for transactional DDL. The default scripts ensure that all + migrations occur within a transaction - for those databases which support + this (Postgresql, Microsoft SQL Server), migrations can be tested with no + need to manually undo changes upon failure. +* Minimalist script construction. Basic operations like renaming + tables/columns, adding/removing columns, changing column attributes can be + performed through one line commands like alter_column(), rename_table(), + add_constraint(). There is no need to recreate full SQLAlchemy Table + structures for simple operations like these - the functions themselves + generate minimalist schema structures behind the scenes to achieve the given + DDL sequence. +* "auto generation" of migrations. While real world migrations are far more + complex than what can be automatically determined, Alembic can still + eliminate the initial grunt work in generating new migration directives + from an altered schema. The ``--autogenerate`` feature will inspect the + current status of a database using SQLAlchemy's schema inspection + capabilities, compare it to the current state of the database model as + specified in Python, and generate a series of "candidate" migrations, + rendering them into a new migration script as Python directives. The + developer then edits the new file, adding additional directives and data + migrations as needed, to produce a finished migration. Table and column + level changes can be detected, with constraints and indexes to follow as + well. +* Full support for migrations generated as SQL scripts. Those of us who + work in corporate environments know that direct access to DDL commands on a + production database is a rare privilege, and DBAs want textual SQL scripts. + Alembic's usage model and commands are oriented towards being able to run a + series of migrations into a textual output file as easily as it runs them + directly to a database. Care must be taken in this mode to not invoke other + operations that rely upon in-memory SELECTs of rows - Alembic tries to + provide helper constructs like bulk_insert() to help with data-oriented + operations that are compatible with script-based DDL. +* Non-linear, dependency-graph versioning. Scripts are given UUID + identifiers similarly to a DVCS, and the linkage of one script to the next + is achieved via human-editable markers within the scripts themselves. + The structure of a set of migration files is considered as a + directed-acyclic graph, meaning any migration file can be dependent + on any other arbitrary set of migration files, or none at + all. Through this open-ended system, migration files can be organized + into branches, multiple roots, and mergepoints, without restriction. + Commands are provided to produce new branches, roots, and merges of + branches automatically. +* Provide a library of ALTER constructs that can be used by any SQLAlchemy + application. The DDL constructs build upon SQLAlchemy's own DDLElement base + and can be used standalone by any application or script. +* At long last, bring SQLite and its inability to ALTER things into the fold, + but in such a way that SQLite's very special workflow needs are accommodated + in an explicit way that makes the most of a bad situation, through the + concept of a "batch" migration, where multiple changes to a table can + be batched together to form a series of instructions for a single, subsequent + "move-and-copy" workflow. You can even use "move-and-copy" workflow for + other databases, if you want to recreate a table in the background + on a busy system. + +Documentation and status of Alembic is at https://alembic.sqlalchemy.org/ + +The SQLAlchemy Project +====================== + +Alembic is part of the `SQLAlchemy Project `_ and +adheres to the same standards and conventions as the core project. + +Development / Bug reporting / Pull requests +___________________________________________ + +Please refer to the +`SQLAlchemy Community Guide `_ for +guidelines on coding and participating in this project. + +Code of Conduct +_______________ + +Above all, SQLAlchemy places great emphasis on polite, thoughtful, and +constructive communication between users and developers. +Please see our current Code of Conduct at +`Code of Conduct `_. + +License +======= + +Alembic is distributed under the `MIT license +`_. diff --git a/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c b/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c new file mode 100644 index 0000000000000000000000000000000000000000..c93f9d33a0c8f5da2afc321b77069af7432f5023 Binary files /dev/null and b/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c differ diff --git a/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c.body b/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c.body new file mode 100644 index 0000000000000000000000000000000000000000..68529fbd400e902db54175b9286d9f24eb6976e1 --- /dev/null +++ b/.cache/pip/http-v2/e/d/e/d/1/eded1062df3a835b1d654db11016327d0de7276866caf329f6f27b1c.body @@ -0,0 +1,94 @@ +Metadata-Version: 2.1 +Name: contourpy +Version: 1.3.3 +Summary: Python library for calculating contours of 2D quadrilateral grids +Author-Email: Ian Thomas +License: BSD 3-Clause License + + Copyright (c) 2021-2025, ContourPy Developers. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Visualization +Project-URL: Homepage, https://github.com/contourpy/contourpy +Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html +Project-URL: Documentation, https://contourpy.readthedocs.io +Project-URL: Repository, https://github.com/contourpy/contourpy +Requires-Python: >=3.11 +Requires-Dist: numpy>=1.25 +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx>=7.2; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Provides-Extra: bokeh +Requires-Dist: bokeh; extra == "bokeh" +Requires-Dist: selenium; extra == "bokeh" +Provides-Extra: mypy +Requires-Dist: contourpy[bokeh,docs]; extra == "mypy" +Requires-Dist: bokeh; extra == "mypy" +Requires-Dist: docutils-stubs; extra == "mypy" +Requires-Dist: mypy==1.17.0; extra == "mypy" +Requires-Dist: types-Pillow; extra == "mypy" +Provides-Extra: test +Requires-Dist: contourpy[test-no-images]; extra == "test" +Requires-Dist: matplotlib; extra == "test" +Requires-Dist: Pillow; extra == "test" +Provides-Extra: test-no-images +Requires-Dist: pytest; extra == "test-no-images" +Requires-Dist: pytest-cov; extra == "test-no-images" +Requires-Dist: pytest-rerunfailures; extra == "test-no-images" +Requires-Dist: pytest-xdist; extra == "test-no-images" +Requires-Dist: wurlitzer; extra == "test-no-images" +Description-Content-Type: text/markdown + +ContourPy + +ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11. + +It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency. + + * **Documentation**: https://contourpy.readthedocs.io + * **Source code**: https://github.com/contourpy/contourpy + +| | | +| --- | --- | +| Latest release | [![PyPI version](https://img.shields.io/pypi/v/contourpy.svg?label=pypi&color=fdae61)](https://pypi.python.org/pypi/contourpy) [![conda-forge version](https://img.shields.io/conda/v/conda-forge/contourpy.svg?label=conda-forge&color=a6d96a)](https://anaconda.org/conda-forge/contourpy) | +| Downloads | [![PyPi downloads](https://img.shields.io/pypi/dm/contourpy?label=pypi&style=flat&color=fdae61)](https://pepy.tech/project/contourpy) | +| Python version | [![Platforms](https://img.shields.io/pypi/pyversions/contourpy?color=fdae61)](https://pypi.org/project/contourpy/) | +| Coverage | [![Codecov](https://img.shields.io/codecov/c/gh/contourpy/contourpy?color=fdae61&label=codecov)](https://app.codecov.io/gh/contourpy/contourpy) | diff --git a/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb b/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb new file mode 100644 index 0000000000000000000000000000000000000000..00b167ffec1a3b199196169b0e00651f1f6de592 Binary files /dev/null and b/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb differ diff --git a/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb.body b/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb.body new file mode 100644 index 0000000000000000000000000000000000000000..f27d7da5d21de6caf66ff9a8c0f61e2673fe13ae Binary files /dev/null and b/.cache/pip/http-v2/f/1/9/c/b/f19cb9f2548ebec3162f98dc0753cc5fe07d32364a02b1720f376edb.body differ diff --git a/.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122.body b/.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122.body new file mode 100644 index 0000000000000000000000000000000000000000..d32a85a7f228e7913407f0cb16fb1bf46754f5c4 --- /dev/null +++ b/.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122.body @@ -0,0 +1,2339 @@ +Metadata-Version: 2.4 +Name: fonttools +Version: 4.63.0 +Summary: Tools to manipulate font files +Home-page: http://github.com/fonttools/fonttools +Author: Just van Rossum +Author-email: just@letterror.com +Maintainer: Behdad Esfahbod +Maintainer-email: behdad@behdad.org +License: MIT +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: Other Environment +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.external +Provides-Extra: ufo +Provides-Extra: lxml +Requires-Dist: lxml>=4.0; extra == "lxml" +Provides-Extra: woff +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "woff" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "woff" +Requires-Dist: zopfli>=0.1.4; extra == "woff" +Provides-Extra: unicode +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "unicode" +Provides-Extra: graphite +Requires-Dist: lz4>=1.7.4.2; extra == "graphite" +Provides-Extra: interpolatable +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "interpolatable" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "interpolatable" +Requires-Dist: pycairo; extra == "interpolatable" +Provides-Extra: plot +Requires-Dist: matplotlib; extra == "plot" +Provides-Extra: symfont +Requires-Dist: sympy; extra == "symfont" +Provides-Extra: type1 +Requires-Dist: xattr; sys_platform == "darwin" and extra == "type1" +Provides-Extra: pathops +Requires-Dist: skia-pathops>=0.5.0; extra == "pathops" +Provides-Extra: repacker +Requires-Dist: uharfbuzz>=0.45.0; extra == "repacker" +Provides-Extra: all +Requires-Dist: lxml>=4.0; extra == "all" +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "all" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "all" +Requires-Dist: zopfli>=0.1.4; extra == "all" +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "all" +Requires-Dist: lz4>=1.7.4.2; extra == "all" +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "all" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "all" +Requires-Dist: pycairo; extra == "all" +Requires-Dist: matplotlib; extra == "all" +Requires-Dist: sympy; extra == "all" +Requires-Dist: xattr; sys_platform == "darwin" and extra == "all" +Requires-Dist: skia-pathops>=0.5.0; extra == "all" +Requires-Dist: uharfbuzz>=0.45.0; extra == "all" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: platform +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +|CI Build Status| |Coverage Status| |PyPI| |Gitter Chat| + +What is this? +~~~~~~~~~~~~~ + +| fontTools is a library for manipulating fonts, written in Python. The + project includes the TTX tool, that can convert TrueType and OpenType + fonts to and from an XML text format, which is also called TTX. It + supports TrueType, OpenType, AFM and to an extent Type 1 and some + Mac-specific formats. The project has an `MIT open-source + license `__. +| Among other things this means you can use it free of charge. + +`User documentation `_ and +`developer documentation `_ +are available at `Read the Docs `_. + +Installation +~~~~~~~~~~~~ + +FontTools requires `Python `__ 3.10 +or later. We try to follow the same schedule of minimum Python version support as +NumPy (see `NEP 29 `__). + +The package is listed in the Python Package Index (PyPI), so you can +install it with `pip `__: + +.. code:: sh + + pip install fonttools + +If you would like to contribute to its development, you can clone the +repository from GitHub, install the package in 'editable' mode and +modify the source code in place. We recommend creating a virtual +environment, using `virtualenv `__ or +Python 3 `venv `__ module. + +.. code:: sh + + # download the source code to 'fonttools' folder + git clone https://github.com/fonttools/fonttools.git + cd fonttools + + # create new virtual environment called e.g. 'fonttools-venv', or anything you like + python -m virtualenv fonttools-venv + + # source the `activate` shell script to enter the environment (Unix-like); to exit, just type `deactivate` + . fonttools-venv/bin/activate + + # to activate the virtual environment in Windows `cmd.exe`, do + fonttools-venv\Scripts\activate.bat + + # install in 'editable' mode + pip install -e . + +Optional Requirements +--------------------- + +The ``fontTools`` package currently has no (required) external dependencies +besides the modules included in the Python Standard Library. +However, a few extra dependencies are required by some of its modules, which +are needed to unlock optional features. +The ``fonttools`` PyPI distribution also supports so-called "extras", i.e. a +set of keywords that describe a group of additional dependencies, which can be +used when installing via pip, or when specifying a requirement. +For example: + +.. code:: sh + + pip install fonttools[ufo,lxml,woff,unicode] + +This command will install fonttools, as well as the optional dependencies that +are required to unlock the extra features named "ufo", etc. + +- ``Lib/fontTools/misc/etree.py`` + + The module exports a ElementTree-like API for reading/writing XML files, and + allows to use as the backend either the built-in ``xml.etree`` module or + `lxml `__. The latter is preferred whenever present, + as it is generally faster and more secure. + + *Extra:* ``lxml`` + +- ``Lib/fontTools/ttLib/woff2.py`` + + Module to compress/decompress WOFF 2.0 web fonts; it requires: + + * `brotli `__: Python bindings of + the Brotli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/ttLib/sfnt.py`` + + To better compress WOFF 1.0 web fonts, the following module can be used + instead of the built-in ``zlib`` library: + + * `zopfli `__: Python bindings of + the Zopfli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/unicode.py`` + + To display the Unicode character names when dumping the ``cmap`` table + with ``ttx`` we use the ``unicodedata`` module in the Standard Library. + The version included in there varies between different Python versions. + To use the latest available data, you can install: + + * `unicodedata2 `__: + ``unicodedata`` backport for Python 3.x updated to the latest Unicode + version 17.0. + + *Extra:* ``unicode`` + +- ``Lib/fontTools/varLib/interpolatable.py`` + + Module for finding wrong contour/component order between different masters. + It requires one of the following packages in order to solve the so-called + "minimum weight perfect matching problem in bipartite graphs", or + the Assignment problem: + + * `scipy `__: the Scientific Library + for Python, which internally uses `NumPy `__ + arrays and hence is very fast; + * `munkres `__: a pure-Python + module that implements the Hungarian or Kuhn-Munkres algorithm. Slower than + SciPy, but useful for minimalistic systems where adding SciPy is undesirable. + + This ensures both performance (via SciPy) and minimal footprint (via Munkres) + are possible. + + To plot the results to a PDF or HTML format, you also need to install: + + * `pycairo `__: Python bindings for the + Cairo graphics library. Note that wheels are currently only available for + Windows, for other platforms see pycairo's `installation instructions + `__. + + *Extra:* ``interpolatable`` + +- ``Lib/fontTools/varLib/plot.py`` + + Module for visualizing DesignSpaceDocument and resulting VariationModel. + + * `matplotlib `__: 2D plotting library. + + *Extra:* ``plot`` + +- ``Lib/fontTools/misc/symfont.py`` + + Advanced module for symbolic font statistics analysis; it requires: + + * `sympy `__: the Python library for + symbolic mathematics. + + *Extra:* ``symfont`` + +- ``Lib/fontTools/t1Lib.py`` + + To get the file creator and type of Macintosh PostScript Type 1 fonts + on Python 3 you need to install the following module, as the old ``MacOS`` + module is no longer included in Mac Python: + + * `xattr `__: Python wrapper for + extended filesystem attributes (macOS platform only). + + *Extra:* ``type1`` + +- ``Lib/fontTools/ttLib/removeOverlaps.py`` + + Simplify TrueType glyphs by merging overlapping contours and components. + + * `skia-pathops `__: Python + bindings for the Skia library's PathOps module, performing boolean + operations on paths (union, intersection, etc.). + + *Extra:* ``pathops`` + +- ``Lib/fontTools/ufoLib`` + + Package for reading and writing UFO source files; if available, it will use: + + * `fs `__: (aka ``pyfilesystem2``) filesystem abstraction layer + + for reading and writing UFOs to the local filesystem or zip files (.ufoz), instead of + the built-in ``fontTools.misc.filesystem`` package. + The reader and writer classes can in theory also accept any object compatible the + ``fs.base.FS`` interface, although not all have been tested. + +- ``Lib/fontTools/pens/cocoaPen.py`` and ``Lib/fontTools/pens/quartzPen.py`` + + Pens for drawing glyphs with Cocoa ``NSBezierPath`` or ``CGPath`` require: + + * `PyObjC `__: the bridge between + Python and the Objective-C runtime (macOS platform only). + +- ``Lib/fontTools/pens/qtPen.py`` + + Pen for drawing glyphs with Qt's ``QPainterPath``, requires: + + * `PyQt5 `__: Python bindings for + the Qt cross platform UI and application toolkit. + +- ``Lib/fontTools/pens/reportLabPen.py`` + + Pen to drawing glyphs as PNG images, requires: + + * `reportlab `__: Python toolkit + for generating PDFs and graphics. + +- ``Lib/fontTools/pens/freetypePen.py`` + + Pen to drawing glyphs with FreeType as raster images, requires: + + * `freetype-py `__: Python binding + for the FreeType library. + +- ``Lib/fontTools/ttLib/tables/otBase.py`` + + Use the Harfbuzz library to serialize GPOS/GSUB using ``hb_repack`` method, requires: + + * `uharfbuzz `__: Streamlined Cython + bindings for the harfbuzz shaping engine + + *Extra:* ``repacker`` + +How to make a new release +~~~~~~~~~~~~~~~~~~~~~~~~~ + +1) Update ``NEWS.rst`` with all the changes since the last release. Write a + changelog entry for each PR, with one or two short sentences summarizing it, + as well as links to the PR and relevant issues addressed by the PR. Do not + put a new title, the next command will do it for you. +2) Use semantic versioning to decide whether the new release will be a 'major', + 'minor' or 'patch' release. It's usually one of the latter two, depending on + whether new backward compatible APIs were added, or simply some bugs were fixed. +3) From inside a venv, first do ``pip install -r dev-requirements.txt``, then run + the ``python setup.py release`` command from the tip of the ``main`` branch. + By default this bumps the third or 'patch' digit only, unless you pass ``--major`` + or ``--minor`` to bump respectively the first or second digit. + This bumps the package version string, extracts the changes since the latest + version from ``NEWS.rst``, and uses that text to create an annotated git tag + (or a signed git tag if you pass the ``--sign`` option and your git and Github + account are configured for `signing commits `__ + using a GPG key). + It also commits an additional version bump which opens the main branch for + the subsequent developmental cycle +4) Push both the tag and commit to the upstream repository, by running the command + ``git push --follow-tags``. Note: it may push other local tags as well, be + careful. +5) Let the CI build the wheel and source distribution packages and verify both + get uploaded to the Python Package Index (PyPI). +6) [Optional] Go to fonttools `Github Releases `__ + page and create a new release, copy-pasting the content of the git tag + message. This way, the release notes are nicely formatted as markdown, and + users watching the repo will get an email notification. One day we shall + automate that too. + + +Acknowledgments +~~~~~~~~~~~~~~~~ + +In alphabetical order: + +aschmitz, Olivier Berten, Samyak Bhuta, Erik van Blokland, Petr van Blokland, +Jelle Bosma, Sascha Brawer, Tom Byrer, Antonio Cavedoni, Frédéric Coiffier, +Vincent Connare, David Corbett, Simon Cozens, Dave Crossland, Simon Daniels, +Peter Dekkers, Behdad Esfahbod, Behnam Esfahbod, Hannes Famira, Sam Fishman, +Matt Fontaine, Takaaki Fuji, Rob Hagemans, Yannis Haralambous, Greg Hitchcock, +Jeremie Hornus, Khaled Hosny, John Hudson, Denis Moyogo Jacquerye, Jack Jansen, +Tom Kacvinsky, Jens Kutilek, Antoine Leca, Werner Lemberg, Tal Leming, Liang Hai, Peter +Lofting, Cosimo Lupo, Olli Meier, Masaya Nakamura, Dave Opstad, Laurence Penney, +Roozbeh Pournader, Garret Rieger, Read Roberts, Colin Rofls, Guido van Rossum, +Just van Rossum, Andreas Seidel, Georg Seifert, Chris Simpkins, Miguel Sousa, +Adam Twardoch, Adrien Tétar, Vitaly Volkov, Paul Wise. + +Copyrights +~~~~~~~~~~ + +| Copyright (c) 1999-2004 Just van Rossum, LettError + (just@letterror.com) +| See `LICENSE `__ for the full license. + +Copyright (c) 2000 BeOpen.com. All Rights Reserved. + +Copyright (c) 1995-2001 Corporation for National Research Initiatives. +All Rights Reserved. + +Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All +Rights Reserved. + +Have fun! + +.. |CI Build Status| image:: https://github.com/fonttools/fonttools/workflows/Test/badge.svg + :target: https://github.com/fonttools/fonttools/actions?query=workflow%3ATest +.. |Coverage Status| image:: https://codecov.io/gh/fonttools/fonttools/branch/main/graph/badge.svg + :target: https://codecov.io/gh/fonttools/fonttools +.. |PyPI| image:: https://img.shields.io/pypi/v/fonttools.svg + :target: https://pypi.org/project/FontTools +.. |Gitter Chat| image:: https://badges.gitter.im/fonttools-dev/Lobby.svg + :alt: Join the chat at https://gitter.im/fonttools-dev/Lobby + :target: https://gitter.im/fonttools-dev/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + +Changelog +~~~~~~~~~ + +4.63.0 (released 2026-05-14) +---------------------------- + +- [ttLib] Add support for Apple Color Emoji ``bgcl`` table (#4065). +- [ttLib] Add support for ``IFT`` and ``IFTX`` tables (Incremental Font Transfer, + PatchMapFormat2) (#4070, #4072). +- [otData] Introduce ``FieldSpec`` dataclass for OpenType table schema definitions, + replacing raw tuples in ``otData.py`` (#4076). +- [Feat] Show ``name`` table strings as comments next to label IDs in TTX output, + matching the convention used by ``fvar``, ``STAT``, ``trak`` (#4089). +- [cu2qu] Fix Cython complex-division rounding difference in + ``split_cubic_into_three`` that could cause ±1 off-curve coordinate shifts + (#3928, #4083). +- [designspaceLib] Fix ``map_backward`` for many-to-one (flat-segment) axis maps + that silently dropped entries via dict comprehension + (googlefonts/ufo2ft#978, #4085). +- [OS/2] Fix ``setUnicodeRanges`` to accept reserved bits 123-127, restoring + round-trip with ``getUnicodeRanges`` and fixing ``recalcUnicodeRanges`` crash + in the subsetter (#4087, #4088). +- [cython] Declare Cython extensions as free-threading compatible on Python 3.13+, + so that importing them on free-threaded Python no longer re-enables the GIL + (#4073, #4090). + +4.62.1 (released 2026-03-13) +---------------------------- + +- [feaLib] Extend contextual rule merging to all rule types: single subst, GSUB/GPOS + named lookups, ignore rules, and chained alternate subst (#4061). + +4.62.0 (released 2026-03-09) +---------------------------- + +- [diff] Add new ``fonttools diff`` command for comparing font files, imported from the + ``fdiff`` project and heavily reworked (#1190, #4007, #4009, #4011, #4013, #4019). +- [feaLib] Fix ``VariableScalar`` interpolation bug with non-linear avar mappings. Also + decouple ``VariableScalar`` from compiled fonts, allowing it to work with designspace data + before compilation (#3938, #4054). +- [feaLib] Fix ``VariableScalar`` axis ordering and iterative delta rounding to match fontc + behavior (#4053). +- [feaLib] Merge chained multi subst rules with same context into a single subtable instead of + emitting one subtable per glyph (#4016, #4058). +- [feaLib] Pass location to ``ConditionsetStatement`` to fix glyphsLib round-tripping + (fontra/fontra-glyphs#130, #4057). +- [feaLib] Write ``0xFFFF`` instead of ``0`` for missing nameIDs in ``cv`` feature params + (#4010, #4012). +- [cmap] Fix ``CmapSubtable.__lt__()`` ``TypeError`` on Python 3 when subtables share the + same encoding record, and add compile-time validation for unique encoding records (#4035, + #4055). +- [svgLib] Skip non-element XML nodes (comments, processing instructions) when drawing SVG + paths (#4042, #4043). +- [glifLib] Fix regression reading glyph outlines when ``glyphObject=None`` (#4030, #4031). +- [pointPen] Fix ``SegmentToPointPen`` edge case: only remove a duplicate final point on + ``closePath()`` if it is an on-curve point (#4014, #4015). +- [cffLib] **SECURITY** Replace ``eval()`` with ``safeEval()`` in ``parseBlendList()`` to + prevent arbitrary code execution from crafted TTX files (#4039, #4040). +- [ttLib] Remove defunct Adobe SING Glyphlet tables (``META``, ``SING``, ``GMAP``, ``GPKG``) + (#4044). +- [varLib.interpolatable] Various bugfixes: fix swapped nodeTypes assignment, duplicate + kink-detector condition, typos, CFF2 vsindex parsing, glyph existence check, and plot + helpers (#4046). +- [varLib.models] Fix ``getSubModel`` not forwarding ``extrapolate``/``axisRanges``; check + location uniqueness after stripping zeros (#4047). +- [varLib] Fix ``--variable-fonts`` filter in ``build_many``; remove dead code and fix + comments (#4048). +- [avar] Preserve existing name table in build; keep ``unbuild`` return types consistent; + validate ``map`` CLI coordinates (#4051). +- [cu2qu/qu2cu] Add input validation: reject non-positive tolerances, validate curve inputs + and list lengths (#4052). +- [colorLib] Raise a clear ``ColorLibError`` when base glyphs are missing from glyphMap, + instead of a confusing ``KeyError`` (#4041). +- [glyf] Remove unnecessary ``fvar`` table dependency (#4017). +- [fvar/trak] Remove unnecessary ``name`` table dependency (#4018). +- [ufoLib] Relax guideline validation to follow the updated spec (#3537, #3553). +- [ttFont] Fix ``saveXML`` regression with empty table lists, clarify docstring (#4025, #4026, + #4056). +- [setup.py] Link ``libm`` for Cython extensions using math functions (#4028, #4029). +- Add typing annotations for ``DSIG``, ``DefaultTable``, ``ttProgram`` (#4033). + +4.61.1 (released 2025-12-12) +---------------------------- + +- [otlLib] buildCoverage: return empty Coverage instead of None (#4003, #4004). +- [instancer] bug fix in ``avar2`` full instancing (#4002). +- [designspaceLib] Preserve empty conditionsets when serializing to XML (#4001). +- [fontBu ilder] Fix FontBuilder ``setupOS2()`` default params globally polluted (#3996, #3997). +- [ttFont] Add more typing annotations to ttFont, xmlWriter, sfnt, varLib.models and others (#3952, #3826). +- Explicitly test and declare support for Python 3.14, even though we were already shipping pre-built wheels for it (#3990). + +4.60.2 (released 2025-12-09) +---------------------------- + +- **Backport release** Same as 4.61.0 but without "Drop support for EOL Python 3.9" change to allow + downstream projects still on Python 3.9 to avail of the security fix for CVE-2025-66034 (#3994, #3999). + +4.61.0 (released 2025-11-28) +---------------------------- + +- [varLib.main]: **SECURITY** Only use basename(vf.filename) to prevent path traversal attacks when + running ``fonttools varLib`` command, or code which invokes ``fonttools.varLib.main()``. + Fixes CVE-2025-66034, see: + https://github.com/fonttools/fonttools/security/advisories/GHSA-768j-98cg-p3fv. +- [feaLib] Sort BaseLangSysRecords by tag (#3986). +- Drop support for EOL Python 3.9 (#3982). +- [instancer] Support --remove-overlaps for fonts with CFF2 table (#3975). +- [CFF2ToCFF] Add --remove-overlaps option (#3976). +- [feaLib] Raise an error for rsub with NULL target (#3979). +- [bezierTools] Fix logic bug in curveCurveIntersections (#3963). +- [feaLib] Error when condition sets have the same name (#3958). +- [cu2qu.ufo] skip processing empty glyphs to support sparse kerning masters (#3956). +- [unicodedata] Update to Unicode 17. Require ``unicodedata2 >= 17.0.0`` when installed with 'unicode' extra. + +4.60.1 (released 2025-09-29) +---------------------------- + +- [ufoLib] Reverted accidental method name change in ``UFOReader.getKerningGroupConversionRenameMaps`` + that broke compatibility with downstream projects like defcon (#3948, #3947, robotools/defcon#478). +- [ufoLib] Added test coverage for ``getKerningGroupConversionRenameMaps`` method (#3950). +- [subset] Don't try to subset BASE table; pass it through by default instead (#3949). +- [subset] Remove empty BaseRecord entries in MarkBasePos lookups (#3897, #3892). +- [subset] Add pruning for MarkLigPos and MarkMarkPos lookups (#3946). +- [subset] Remove duplicate features when subsetting (#3945). +- [Docs] Added documentation for the visitor module (#3944). + +4.60.0 (released 2025-09-17) +---------------------------- + +- [pointPen] Allow ``reverseFlipped`` parameter of ``DecomposingPointPen`` to take a ``ReverseFlipped`` + enum value to control whether/how to reverse contour direction of flipped components, in addition to + the existing True/False. This allows to set ``ReverseFlipped.ON_CURVE_FIRST`` to ensure that + the decomposed outline starts with an on-curve point before being reversed, for better consistency + with other segment-oriented contour transformations. The change is backward compatible, and the + default behavior hasn't changed (#3934). +- [filterPen] Added ``ContourFilterPointPen``, base pen for buffered contour operations, and + ``OnCurveStartPointPen`` filter to ensure contours start with an on-curve point (#3934). +- [cu2qu] Fixed difference in cython vs pure-python complex division by real number (#3930). +- [varLib.avar] Refactored and added some new sub-modules and scripts (#3926). + * ``varLib.avar.build`` module to build avar (and a missing fvar) binaries into a possibly empty TTFont, + * ``varLib.avar.unbuild`` module to print a .designspace snippet that would generate the same avar binary, + * ``varLib.avar.map`` module to take TTFont and do the mapping, in user/normalized space, + * ``varLib.avar.plan`` module moved from ``varLib.avarPlanner``. + The bare ``fonttools varLib.avar`` script is deprecated, in favour of ``fonttools varLib.avar.build`` (or ``unbuild``). +- [interpolatable] Clarify ``linear_sum_assignment`` backend options and minimal dependency + usage (#3927). +- [post] Speed up ``build_psNameMapping`` (#3923). +- [ufoLib] Added typing annotations to fontTools.ufoLib (#3875). + +4.59.2 (released 2025-08-27) +---------------------------- + +- [varLib] Clear ``USE_MY_METRICS`` component flags when inconsistent across masters (#3912). +- [varLib.instancer] Avoid negative advance width/height values when instatiating HVAR/VVAR, + (unlikely in well-behaved fonts) (#3918). +- [subset] Fix shaping behaviour when pruning empty mark sets (#3915, harfbuzz/harfbuzz#5499). +- [cu2qu] Fixed ``dot()`` product of perpendicular vectors not always returning exactly 0.0 + in all Python implementations (#3911) +- [varLib.instancer] Implemented fully-instantiating ``avar2`` fonts (#3909). +- [feaLib] Allow float values in ``VariableScalar``'s axis locations (#3906, #3907). +- [cu2qu] Handle special case in ``calc_intersect`` for degenerate cubic curves where 3 to 4 + control points are equal (#3904). + +4.59.1 (released 2025-08-14) +---------------------------- + +- [featureVars] Update OS/2.usMaxContext if possible after addFeatureVariationsRaw (#3894). +- [vhmtx] raise TTLibError('not enough data...') when hmtx/vmtx are truncated (#3843, #3901). +- [feaLib] Combine duplicate features that have the same set of lookups regardless of the order in which those lookups are added to the feature (#3895). +- [varLib] Deprecate ``varLib.mutator`` in favor of ``varLib.instancer``. The latter + provides equivalent full (static font) instancing in addition to partial VF instancing. + CLI users should replace ``fonttools varLib.mutator`` with ``fonttools varLib.instancer``. + API users should migrate to ``fontTools.varLib.instancer.instantiateVariableFont`` (#2680). + + +4.59.0 (released 2025-07-16) +---------------------------- + +- Removed hard-dependency on pyfilesystem2 (``fs`` package) from ``fonttools[ufo]`` extra. + This is replaced by the `fontTools.misc.filesystem` package, a stdlib-only, drop-in + replacement for the subset of the pyfilesystem2's API used by ``fontTools.ufoLib``. + The latter should continue to work with the upstream ``fs`` (we even test with/without). + Clients who wish to continue using ``fs`` can do so by depending on it directly instead + of via the ``fonttools[ufo]`` extra (#3885, #3620). +- [xmlWriter] Replace illegal XML characters (e.g. control or non-characters) with "?" + when dumping to ttx (#3868, #71). +- [varLib.hvar] Fixed vertical metrics fields copy/pasta error (#3884). +- Micro optimizations in ttLib and sstruct modules (#3878, #3879). +- [unicodedata] Add Garay script to RTL_SCRIPTS (#3882). +- [roundingPen] Remove unreliable kwarg usage. Argument names aren’t consistent among + point pens’ ``.addComponent()`` implementations, in particular ``baseGlyphName`` + vs ``glyphName`` (#3880). + +4.58.5 (released 2025-07-03) +---------------------------- + +- [feaLib] Don't try to combine ligature & multisub rules (#3874). +- [feaLib/ast] Use weakref proxies to avoid cycles in visitor (#3873). +- [varLib.instancer] Fixed instancing CFF2 fonts where VarData contains more than 64k items (#3858). + +4.58.4 (released 2025-06-13) +---------------------------- + +- [feaLib] Allow for empty MarkFilter & MarkAttach sets (#3856). + +4.58.3 (released 2025-06-13) +---------------------------- + +- [feaLib] Fixed iterable check for Python 3.13.4 and newer (#3854, #3855). + +4.58.2 (released 2025-06-06) +---------------------------- + +- [ttLib.reorderGlyphs] Handle CFF2 when reordering glyphs (#3852) +- [subset] Copy name IDs in use before scrapping or scrambling them for webfonts (#3853) + +4.58.1 (released 2025-05-28) +---------------------------- + +- [varLib] Make sure that fvar named instances only reuse name ID 2 or 17 if they are at the default location across all axes, to match OT spec requirement (#3831). +- [feaLib] Improve single substitution promotion to multiple/ligature substitutions, fixing a few bugs as well (#3849). +- [loggingTools] Make ``Timer._time`` a static method that doesn't take self, makes it easier to override (#3836). +- [featureVars] Use ``None`` for empty ConditionSet, which translates to a null offset in the compiled table (#3850). +- [feaLib] Raise an error on conflicting ligature substitution rules instead of silently taking the last one (#3835). +- Add typing annotations to T2CharStringPen (#3837). +- [feaLib] Add single substitutions that were promoted to multiple or ligature substitutions to ``aalt`` feature (#3847). +- [featureVars] Create a default ``LangSys`` in a ``ScriptRecord`` if missing when adding feature variations to existing GSUB later in the build (#3838). +- [symfont] Added a ``main()``. +- [cffLib.specializer] Fix rmoveto merging when blends used (#3839, #3840). +- [pyftmerge] Add support for cmap format 14 in the merge tool (#3830). +- [varLib.instancer/cff2] Fix vsindex of Private dicts when instantiating (#3828, #3232). +- Update text file read to use UTF-8 with optional BOM so it works with e.g. Windows Notepad.exe (#3824). +- [varLib] Ensure that instances only reuse name ID 2 or 17 if they are at the default location across all axes (#3831). +- [varLib] Create a dflt LangSys in a ScriptRecord when adding variations later, to fix an avoidable crash in an edge case (#3838). + +4.58.0 (released 2025-05-10) +---------------------------- + +- Drop Python 3.8, require 3.9+ (#3819) +- [HVAR, VVAR] Prune unused regions when using a direct mapping (#3797) +- [Docs] Improvements to ufoLib documentation (#3721) +- [Docs] Improvements to varLib documentation (#3727) +- [Docs] Improvements to Pens and pen-module documentation (#3724) +- [Docs] Miscellany updates to docs (misc modules and smaller modules) (#3730) +- [subset] Close codepoints over BiDi mirror variants. (#3801) +- [feaLib] Fix serializing ChainContextPosStatement and + ChainContextSubstStatement in some rare cases (#3788) +- [designspaceLib] Clarify user expectations for getStatNames (#2892) +- [GVAR] Add support for new `GVAR` table (#3728) +- [TSI0, TSI5] Derive number of entries to decompile from data length (#2477) +- [ttLib] Fix `AttributeError` when reporting table overflow (#3808) +- [ttLib] Apply rounding more often in getCoordinates (#3798) +- [ttLib] Ignore component bounds if empty (#3799) +- [ttLib] Change the separator for duplicate glyph names from "#" to "." (#3809) +- [feaLib] Support subtable breaks in CursivePos, MarkBasePos, MarkToLigPos and + MarkToMarkPos lookups (#3800, #3807) +- [feaLib] If the same lookup has single substitutions and ligature + substitutions, upgrade single substitutions to ligature substitutions with + one input glyph (#3805) +- [feaLib] Correctly handle in single pos lookups (#3803) +- [feaLib] Remove duplicates from class pair pos classes instead of raising an + error (#3804) +- [feaLib] Support creating extension lookups using useExtenion lookup flag + instead of silently ignoring it (#3811) +- [STAT] Add typing for the simpler STAT arguments (#3812) +- [otlLib.builder] Add future import for annotations (#3814) +- [cffLib] Fix reading supplement encoding (#3813) +- [voltLib] Add some missing functionality and fixes to voltLib and VoltToFea, + making the conversion to feature files more robust. Add also `fonttools + voltLib` command line tool to compile VOLT sources directly (doing an + intermediate fea conversion internally) (#3818) +- [pens] Add some PointPen annotations (#3820) + +4.57.0 (released 2025-04-03) +---------------------------- + +- [ttLib.__main__] Add `--no-recalc-timestamp` flag (#3771) +- [ttLib.__main__] Add `-b` (recalcBBoxes=False) flag (#3772) +- [cmap] Speed up glyphOrder loading from cmap (#3774) +- [ttLib.__main__] Improvements around the `-t` flag (#3776) +- [Debg] Fix parsing from XML; add roundtrip tests (#3781) +- [fealib] Support \*Base.MinMax tables (#3783, #3786) +- [config] Add OPTIMIZE_FONT_SPEED (#3784) +- [varLib.hvar] New module to add HVAR table to the font (#3780) +- [otlLib.optimize] Fix crash when the provided TTF does not contain a `GPOS` (#3794) + +4.56.0 (released 2025-02-07) +---------------------------- + +- [varStore] Sort the input todo list with the same sorting key used for the opimizer's output (#3767). +- [otData] Fix DeviceTable's ``DeltaValue`` repeat value which caused a crash after importing from XML and then compiling a GPOS containing Device tables (#3758). +- [feaLib] Make ``FeatureLibError`` pickleable, so client can e.g. use feaLib to can compile features in parallel with multiprocessing (#3762). +- [varLib/gvar] Removed workaround for old, long-fixed macOS bug about composite glyphs with all zero deltas (#1381, #1788). +- [Docs] Updated ttLib documentation, beefed up TTFont and TTGlyphSet explanations (#3720). + +4.55.8 (released 2025-01-29) +---------------------------- + +- [MetaTools] Fixed bug in buildUCD.py script whereby the first non-header line of some UCD text file was being skipped. This affected in particular the U+00B7 (MIDDLE DOT) entry of ScriptExtensions.txt (#3756). + +4.55.7 (released 2025-01-28) +---------------------------- + +- Shorten the changelog included in PyPI package description to accommodate maximum length limit imposed by Azure DevOps. No actual code changes since v4.55.6 (#3754). + +4.55.6 (released 2025-01-24) +---------------------------- + +- [glyf] Fixed regression introduced in 4.55.5 when computing bounds of nested composite glyphs with transformed components (#3752). + +4.55.5 (released 2025-01-23) +---------------------------- + +- [glyf] Fixed recalcBounds of transformed components with unrounded coordinates (#3750). +- [feaLib] Allow duplicate script/language statements (#3749). + +4.55.4 (released 2025-01-21) +---------------------------- + +- [bezierTools] Fixed ``splitCubicAtT`` sometimes not returning identical start/end points as result of numerical precision (#3742, #3743). +- [feaLib/ast] Fixed docstring of ``AlternateSubstStatement`` (#3735). +- [transform] Typing fixes (#3734). + +4.55.3 (released 2024-12-10) +---------------------------- + +- [Docs] fill out ttLib table section [#3716] +- [feaLib] More efficient inline format 4 lookups [#3726] + +4.55.2 (released 2024-12-05) +---------------------------- + +- [Docs] update Sphinx config (#3712) +- [designspaceLib] Allow axisOrdering to be set to zero (#3715) +- [feaLib] Don’t modify variable anchors in place (#3717) + +4.55.1 (released 2024-12-02) +---------------------------- + +- [ttGlyphSet] Support VARC CFF2 fonts (#3683) +- [DecomposedTransform] Document and implement always skewY == 0 (#3697) +- [varLib] "Fix" cython iup issue? (#3704) +- Cython minor refactor (#3705) + + +4.55.0 (released 2024-11-14) +---------------------------- + +- [cffLib.specializer] Adjust stack use calculation (#3689) +- [varLib] Lets not add mac names if the rest of name doesn't have them (#3688) +- [ttLib.reorderGlyphs] Update CFF table charstrings and charset (#3682) +- [cffLib.specializer] Add cmdline to specialize a CFF2 font (#3675, #3679) +- [CFF2] Lift uint16 VariationStore.length limitation (#3674) +- [subset] consider variation selectors subsetting cmap14 (#3672) +- [varLib.interpolatable] Support CFF2 fonts (#3670) +- Set isfinal to true in XML parser for proper resource cleanup (#3669) +- [removeOverlaps] Fix CFF CharString width (#3659) +- [glyf] Add optimizeSize option (#3657) +- Python 3.13 support (#3656) +- [TupleVariation] Optimize for loading speed, not size (#3650, #3653) + + +4.54.1 (released 2024-09-24) +---------------------------- + +- [unicodedata] Update to Unicode 16 +- [subset] Escape ``\\`` in doc string + +4.54.0 (released 2024-09-23) +---------------------------- + +- [Docs] Small docs cleanups by @n8willis (#3611) +- [Docs] cleanup code blocks by @n8willis (#3627) +- [Docs] fix Sphinx builds by @n8willis (#3625) +- [merge] Minor fixes to documentation for merge by @drj11 (#3588) +- [subset] Small tweaks to pyftsubset documentation by @RoelN (#3633) +- [Tests] Do not require fonttools command to be available by @behdad (#3612) +- [Tests] subset_test: add failing test to reproduce issue #3616 by @anthrotype (#3622) +- [ttLib] NameRecordVisitor: include whole sequence of character variants' UI labels, not just the first by @anthrotype (#3617) +- [varLib.avar] Reconstruct mappings from binary by @behdad (#3598) +- [varLib.instancer] Fix visual artefacts with partial L2 instancing by @Hoolean (#3635) +- [varLib.interpolatable] Support discrete axes in .designspace by @behdad (#3599) +- [varLib.models] By default, assume OpenType-like normalized space by @behdad (#3601) + +4.53.1 (released 2024-07-05) +---------------------------- + +- [feaLib] Improve the sharing of inline chained lookups (#3559) +- [otlLib] Correct the calculation of OS/2.usMaxContext with reversed chaining contextual single substitutions (#3569) +- [misc.visitor] Visitors search the inheritance chain of objects they are visiting (#3581) + +4.53.0 (released 2024-05-31) +---------------------------- + +- [ttLib.removeOverlaps] Support CFF table to aid in downconverting CFF2 fonts (#3528) +- [avar] Fix crash when accessing not-yet-existing attribute (#3550) +- [docs] Add buildMathTable to otlLib.builder documentation (#3540) +- [feaLib] Allow UTF-8 with BOM when reading features (#3495) +- [SVGPathPen] Revert rounding coordinates to two decimal places by default (#3543) +- [varLib.instancer] Refix output filename decision-making (#3545, #3544, #3548) + +4.52.4 (released 2024-05-27) +---------------------------- + +- [varLib.cff] Restore and deprecate convertCFFtoCFF2 that was removed in 4.52.0 + release as it is used by downstream projects (#3535). + +4.52.3 (released 2024-05-27) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.2. No other code changes. + +4.52.2 (released 2024-05-27) +---------------------------- + +- [varLib.interpolatable] Ensure that scipy/numpy output is JSON-serializable + (#3522, #3526). +- [housekeeping] Regenerate table lists, to fix pyinstaller packaging of the new + ``VARC`` table (#3531, #3529). +- [cffLib] Make CFFToCFF2 and CFF2ToCFF more robust (#3521, #3525). + +4.52.1 (released 2024-05-24) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.0. No other code changes. + +4.52.0 (released 2024-05-24) +---------------------------- + +- Added support for the new ``VARC`` (Variable Composite) table that is being + proposed to OpenType spec (#3395). For more info: + https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md +- [ttLib.__main__] Fixed decompiling all tables (90fed08). +- [feaLib] Don't reference the same lookup index multiple times within the same + feature record, it is only applied once anyway (#3520). +- [cffLib] Moved methods to desubroutinize, remove hints and unused subroutines + from subset module to cffLib (#3517). +- [varLib.instancer] Added support for partial-instancing CFF2 tables! Also, added + method to down-convert from CFF2 to CFF 1.0, and CLI entry points to convert + CFF<->CFF2 (#3506). +- [subset] Prune unused user name IDs even with --name-IDs='*' (#3410). +- [ttx] use GNU-style getopt to intermix options and positional arguments (#3509). +- [feaLib.variableScalar] Fixed ``value_at_location()`` method (#3491) +- [psCharStrings] Shorten output of ``encodeFloat`` (#3492). +- [bezierTools] Fix infinite-recursion in ``calcCubicArcLength`` (#3502). +- [avar2] Implement ``avar2`` support in ``TTFont.getGlyphSet()`` (#3473). + +4.51.0 (released 2024-04-05) +---------------------------- + +- [ttLib] Optimization on loading aux fields (#3464). +- [ttFont] Add reorderGlyphs (#3468). + +4.50.0 (released 2024-03-15) +---------------------------- + +- [pens] Added decomposing filter pens that draw components as regular contours (#3460). +- [instancer] Drop explicit no-op axes from TupleVariations (#3457). +- [cu2qu/ufo] Return set of modified glyph names from fonts_to_quadratic (#3456). + +4.49.0 (released 2024-02-15) +---------------------------- + +- [otlLib] Add API for building ``MATH`` table (#3446) + +4.48.1 (released 2024-02-06) +---------------------------- + +- Fixed uploading wheels to PyPI, no code changes since v4.48.0. + +4.48.0 (released 2024-02-06) +---------------------------- + +- [varLib] Do not log when there are no OTL tables to be merged. +- [setup.py] Do not restrict lxml<5 any more, tests pass just fine with lxml>=5. +- [feaLib] Remove glyph and class names length restrictions in FEA (#3424). +- [roundingPens] Added ``transformRoundFunc`` parameter to the rounding pens to allow + for custom rounding of the components' transforms (#3426). +- [feaLib] Keep declaration order of ligature components within a ligature set, instead + of sorting by glyph name (#3429). +- [feaLib] Fixed ordering of alternates in ``aalt`` lookups, following the declaration + order of feature references within the ``aalt`` feature block (#3430). +- [varLib.instancer] Fixed a bug in the instancer's IUP optimization (#3432). +- [sbix] Support sbix glyphs with new graphicType "flip" (#3433). +- [svgPathPen] Added ``--glyphs`` option to dump the SVG paths for the named glyphs + in the font (0572f78). +- [designspaceLib] Added "description" attribute to ```` and ```` + elements, and allow multiple ```` elements to group ```` elements + that are logically related (#3435, #3437). +- [otlLib] Correctly choose the most compact GSUB contextual lookup format (#3439). + +4.47.2 (released 2024-01-11) +---------------------------- + +Minor release to fix uploading wheels to PyPI. + +4.47.1 (released 2024-01-11) +---------------------------- + +- [merge] Improve help message and add standard command line options (#3408) +- [otlLib] Pass ``ttFont`` to ``name.addName`` in ``buildStatTable`` (#3406) +- [featureVars] Re-use ``FeatureVariationRecord``'s when possible (#3413) + +4.47.0 (released 2023-12-18) +---------------------------- + +- [varLib.models] New API for VariationModel: ``getMasterScalars`` and + ``interpolateFromValuesAndScalars``. +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + add a Summary page in the front, and an Index and Table-of-Contents in the back. + Change the page size to Letter. +- [Docs/designspaceLib] Defined a new ``public.fontInfo`` lib key, not used anywhere yet (#3358). + +4.46.0 (released 2023-12-02) +---------------------------- + +- [featureVars] Allow to register the same set of substitution rules to multiple features. + The ``addFeatureVariations`` function can now take a list of featureTags; similarly, the + lib key 'com.github.fonttools.varLib.featureVarsFeatureTag' can now take a + comma-separateed string of feature tags (e.g. "salt,ss01") instead of a single tag (#3360). +- [featureVars] Don't overwrite GSUB FeatureVariations, but append new records to it + for features which are not already there. But raise ``VarLibError`` if the feature tag + already has feature variations associated with it (#3363). +- [varLib] Added ``addGSUBFeatureVariations`` function to add GSUB Feature Variations + to an existing variable font from rules defined in a DesignSpace document (#3362). +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + a new test for "underweight" glyphs. The new test reports quite a few false-positives + though. Please send feedback. + +4.45.1 (released 2023-11-23) +---------------------------- + +- [varLib.interpolatable] Various bugfixes and improvements, better reporting, reduced + false positives. +- [ttGlyphSet] Added option to not recalculate glyf bounds (#3348). + +4.45.0 (released 2023-11-20) +---------------------------- + +- [varLib.interpolatable] Vastly improved algorithms. Also available now is ``--pdf`` + and ``--html`` options to generate a PDF or HTML report of the interpolation issues. + The PDF/HTML report showcases the problematic masters, the interpolated broken + glyph, as well as the proposed fixed version. + +4.44.3 (released 2023-11-15) +---------------------------- + +- [subset] Only prune codepage ranges for OS/2.version >= 1, ignore otherwise (#3334). +- [instancer] Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing + MVAR table containing 'hasc', 'hdsc' or 'hlgp' tags (#3297). + +4.44.2 (released 2023-11-14) +---------------------------- + +- [glyf] Have ``Glyph.recalcBounds`` skip empty components (base glyph with no contours) + when computing the bounding box of composite glyphs. This simply restores the existing + behavior before some changes were introduced in fonttools 4.44.0 (#3333). + +4.44.1 (released 2023-11-14) +---------------------------- + +- [feaLib] Ensure variable mark anchors are deep-copied while building since they + get modified in-place and later reused (#3330). +- [OS/2|subset] Added method to ``recalcCodePageRanges`` to OS/2 table class; added + ``--prune-codepage-ranges`` to `fonttools subset` command (#3328, #2607). + +4.44.0 (released 2023-11-03) +---------------------------- + +- [instancer] Recalc OS/2 AvgCharWidth after instancing if default changes (#3317). +- [otlLib] Make ClassDefBuilder class order match varLib.merger's, i.e. large + classes first, then glyph lexicographic order (#3321, #3324). +- [instancer] Allow not specifying any of min:default:max values and let be filled + up with fvar's values (#3322, #3323). +- [instancer] When running --update-name-table ignore axes that have no STAT axis + values (#3318, #3319). +- [Debg] When dumping to ttx, write the embedded JSON as multi-line string with + indentation (92cbfee0d). +- [varStore] Handle > 65535 items per encoding by splitting VarData subtable (#3310). +- [subset] Handle null-offsets in MarkLigPos subtables. +- [subset] Keep East Asian spacing fatures vhal, halt, chws, vchw by default (#3305). +- [instancer.solver] Fixed case where axisDef < lower and upper < axisMax (#3304). +- [glyf] Speed up compilation, mostly around ``recalcBounds`` (#3301). +- [varLib.interpolatable] Speed it up when working on variable fonts, plus various + micro-optimizations (#3300). +- Require unicodedata2 >= 15.1.0 when installed with 'unicode' extra, contains UCD 15.1. + +4.43.1 (released 2023-10-06) +---------------------------- + +- [EBDT] Fixed TypeError exception in `_reverseBytes` method triggered when dumping + some bitmap fonts with `ttx -z bitwise` option (#3162). +- [v/hhea] Fixed UnboundLocalError exception in ``recalc`` method when no vmtx or hmtx + tables are present (#3290). +- [bezierTools] Fixed incorrectly typed cython local variable leading to TypeError when + calling ``calcQuadraticArcLength`` (#3288). +- [feaLib/otlLib] Better error message when building Coverage table with missing glyph (#3286). + +4.43.0 (released 2023-09-29) +---------------------------- + +- [subset] Set up lxml ``XMLParser(resolve_entities=False)`` when parsing OT-SVG documents + to prevent XML External Entity (XXE) attacks (9f61271dc): + https://codeql.github.com/codeql-query-help/python/py-xxe/ +- [varLib.iup] Added workaround for a Cython bug in ``iup_delta_optimize`` that was + leading to IUP tolerance being incorrectly initialised, resulting in sub-optimal deltas + (60126435d, cython/cython#5732). +- [varLib] Added new command-line entry point ``fonttools varLib.avar`` to add an + ``avar`` table to an existing VF from axes mappings in a .designspace file (0a3360e52). +- [instancer] Fixed bug whereby no longer used variation regions were not correctly pruned + after VarData optimization (#3268). +- Added support for Python 3.12 (#3283). + +4.42.1 (released 2023-08-20) +---------------------------- + +- [t1Lib] Fixed several Type 1 issues (#3238, #3240). +- [otBase/packer] Allow sharing tables reached by different offset sizes (#3241, #3236). +- [varLib/merger] Fix Cursive attachment merging error when all anchors are NULL (#3248, #3247). +- [ttLib] Fixed warning when calling ``addMultilingualName`` and ``ttFont`` parameter was not + passed on to ``findMultilingualName`` (#3253). + +4.42.0 (released 2023-08-02) +---------------------------- + +- [varLib] Use sentinel value 0xFFFF to mark a glyph advance in hmtx/vmtx as non + participating, allowing sparse masters to contain glyphs for variation purposes other + than {H,V}VAR (#3235). +- [varLib/cff] Treat empty glyphs in non-default masters as missing, thus not participating + in CFF2 delta computation, similarly to how varLib already treats them for gvar (#3234). +- Added varLib.avarPlanner script to deduce 'correct' avar v1 axis mappings based on + glyph average weights (#3223). + +4.41.1 (released 2023-07-21) +---------------------------- + +- [subset] Fixed perf regression in v4.41.0 by making ``NameRecordVisitor`` only visit + tables that do contain nameID references (#3213, #3214). +- [varLib.instancer] Support instancing fonts containing null ConditionSet offsets in + FeatureVariationRecords (#3211, #3212). +- [statisticsPen] Report font glyph-average weight/width and font-wide slant. +- [fontBuilder] Fixed head.created date incorrectly set to 0 instead of the current + timestamp, regression introduced in v4.40.0 (#3210). +- [varLib.merger] Support sparse ``CursivePos`` masters (#3209). + +4.41.0 (released 2023-07-12) +---------------------------- + +- [fontBuilder] Fixed bug in setupOS2 with default panose attribute incorrectly being + set to a dict instead of a Panose object (#3201). +- [name] Added method to ``removeUnusedNameRecords`` in the user range (#3185). +- [varLib.instancer] Fixed issue with L4 instancing (moving default) (#3179). +- [cffLib] Use latin1 so we can roundtrip non-ASCII in {Full,Font,Family}Name (#3202). +- [designspaceLib] Mark as optional in docs (as it is in the code). +- [glyf-1] Fixed drawPoints() bug whereby last cubic segment becomes quadratic (#3189, #3190). +- [fontBuilder] Propagate the 'hidden' flag to the fvar Axis instance (#3184). +- [fontBuilder] Update setupAvar() to also support avar 2, fixing ``_add_avar()`` call + site (#3183). +- Added new ``voltLib.voltToFea`` submodule (originally Tiro Typeworks' "Volto") for + converting VOLT OpenType Layout sources to FEA format (#3164). + +4.40.0 (released 2023-06-12) +---------------------------- + +- Published native binary wheels to PyPI for all the python minor versions and platform + and architectures currently supported that would benefit from this. They will include + precompiled Cython-accelerated modules (e.g. cu2qu) without requiring to compile them + from source. The pure-python wheel and source distribution will continue to be + published as always (pip will automatically chose them when no binary wheel is + available for the given platform, e.g. pypy). Use ``pip install --no-binary=fonttools fonttools`` + to expliclity request pip to install from the pure-python source. +- [designspaceLib|varLib] Add initial support for specifying axis mappings and build + ``avar2`` table from those (#3123). +- [feaLib] Support variable ligature caret position (#3130). +- [varLib|glyf] Added option to --drop-implied-oncurves; test for impliable oncurve + points either before or after rounding (#3146, #3147, #3155, #3156). +- [TTGlyphPointPen] Don't error with empty contours, simply ignore them (#3145). +- [sfnt] Fixed str vs bytes remnant of py3 transition in code dealing with de/compiling + WOFF metadata (#3129). +- [instancer-solver] Fixed bug when moving default instance with sparse masters (#3139, #3140). +- [feaLib] Simplify variable scalars that don’t vary (#3132). +- [pens] Added filter pen that explicitly emits closing line when lastPt != movePt (#3100). +- [varStore] Improve optimize algorithm and better document the algorithm (#3124, #3127). + Added ``quantization`` option (#3126). +- Added CI workflow config file for building native binary wheels (#3121). +- [fontBuilder] Added glyphDataFormat=0 option; raise error when glyphs contain cubic + outlines but glyphDataFormat was not explicitly set to 1 (#3113, #3119). +- [subset] Prune emptied GDEF.MarkGlyphSetsDef and remap indices; ensure GDEF is + subsetted before GSUB and GPOS (#3114, #3118). +- [xmlReader] Fixed issue whereby DSIG table data was incorrectly parsed (#3115, #2614). +- [varLib/merger] Fixed merging of SinglePos with pos=0 (#3111, #3112). +- [feaLib] Demote "Feature has not been defined" error to a warning when building aalt + and referenced feature is empty (#3110). +- [feaLib] Dedupe multiple substitutions with classes (#3105). + +4.39.4 (released 2023-05-10) +---------------------------- + +- [varLib.interpolatable] Allow for sparse masters (#3075) +- [merge] Handle differing default/nominalWidthX in CFF (#3070) +- [ttLib] Add missing main.py file to ttLib package (#3088) +- [ttx] Fix missing composite instructions in XML (#3092) +- [ttx] Fix split tables option to work on filenames containing '%' (#3096) +- [featureVars] Process lookups for features other than rvrn last (#3099) +- [feaLib] support multiple substitution with classes (#3103) + +4.39.3 (released 2023-03-28) +---------------------------- + +- [sbix] Fixed TypeError when compiling empty glyphs whose imageData is None, regression + was introduced in v4.39 (#3059). +- [ttFont] Fixed AttributeError on python <= 3.10 when opening a TTFont from a tempfile + SpooledTemporaryFile, seekable method only added on python 3.11 (#3052). + +4.39.2 (released 2023-03-16) +---------------------------- + +- [varLib] Fixed regression introduced in 4.39.1 whereby an incomplete 'STAT' table + would be built even though a DesignSpace v5 did contain 'STAT' definitions (#3045, #3046). + +4.39.1 (released 2023-03-16) +---------------------------- + +- [avar2] Added experimental support for reading/writing avar version 2 as specified in + this draft proposal: https://github.com/harfbuzz/boring-expansion-spec/blob/main/avar2.md +- [glifLib] Wrap underlying XML library exceptions with GlifLibError when parsing GLIFs, + and also print the name and path of the glyph that fails to be parsed (#3042). +- [feaLib] Consult avar for normalizing user-space values in ConditionSets and in + VariableScalars (#3042, #3043). +- [ttProgram] Handle string input to Program.fromAssembly() (#3038). +- [otlLib] Added a config option to emit GPOS 7 lookups, currently disabled by default + because of a macOS bug (#3034). +- [COLRv1] Added method to automatically compute ClipBoxes (#3027). +- [ttFont] Fixed getGlyphID to raise KeyError on missing glyphs instead of returning + None. The regression was introduced in v4.27.0 (#3032). +- [sbix] Fixed UnboundLocalError: cannot access local variable 'rawdata' (#3031). +- [varLib] When building VF, do not overwrite a pre-existing ``STAT`` table that was built + with feaLib from FEA feature file. Also, added support for building multiple VFs + defined in Designspace v5 from ``fonttools varLib`` script (#3024). +- [mtiLib] Only add ``Debg`` table with lookup names when ``FONTTOOLS_LOOKUP_DEBUGGING`` + env variable is set (#3023). + +4.39.0 (released 2023-03-06) +---------------------------- + +- [mtiLib] Optionally add `Debg` debug info for MTI feature builds (#3018). +- [ttx] Support reading input file from standard input using special `-` character, + similar to existing `-o -` option to write output to standard output (#3020). +- [cython] Prevent ``cython.compiled`` raise AttributeError if cython not installed + properly (#3017). +- [OS/2] Guard against ZeroDivisionError when calculating xAvgCharWidth in the unlikely + scenario no glyph has non-zero advance (#3015). +- [subset] Recompute xAvgCharWidth independently of --no-prune-unicode-ranges, + previously the two options were involuntarily bundled together (#3012). +- [fontBuilder] Add ``debug`` parameter to addOpenTypeFeatures method to add source + debugging information to the font in the ``Debg`` private table (#3008). +- [name] Make NameRecord `__lt__` comparison not fail on Unicode encoding errors (#3006). +- [featureVars] Fixed bug in ``overlayBox`` (#3003, #3005). +- [glyf] Added experimental support for cubic bezier curves in TrueType glyf table, as + outlined in glyf v1 proposal (#2988): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md +- Added new qu2cu module and related qu2cuPen, the reverse of cu2qu for converting + TrueType quadratic splines to cubic bezier curves (#2993). +- [glyf] Added experimental support for reading and writing Variable Composites/Components + as defined in glyf v1 spec proposal (#2958): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-varComposites.md. +- [pens]: Added `addVarComponent` method to pen protocols' base classes, which pens can implement + to handle varcomponents (by default they get decomposed) (#2958). +- [misc.transform] Added DecomposedTransform class which implements an affine transformation + with separate translate, rotation, scale, skew, and transformation-center components (#2598) +- [sbix] Ensure Glyph.referenceGlyphName is set; fixes error after dumping and + re-compiling sbix table with 'dupe' glyphs (#2984). +- [feaLib] Be cleverer when merging chained single substitutions into same lookup + when they are specified using the inline notation (#2150, #2974). +- [instancer] Clamp user-inputted axis ranges to those of fvar (#2959). +- [otBase/subset] Define ``__getstate__`` for BaseTable so that a copied/pickled 'lazy' + object gets its own OTTableReader to read from; incidentally fixes a bug while + subsetting COLRv1 table containing ClipBoxes on python 3.11 (#2965, #2968). +- [sbix] Handle glyphs with "dupe" graphic type on compile correctly (#2963). +- [glyf] ``endPointsOfContours`` field should be unsigned! Kudos to behdad for + spotting one of the oldest bugs in FT. Probably nobody has ever dared to make + glyphs with more than 32767 points... (#2957). +- [feaLib] Fixed handling of ``ignore`` statements with unmarked glyphs to match + makeotf behavior, which assumes the first glyph is marked (#2950). +- Reformatted code with ``black`` and enforce new code style via CI check (#2925). +- [feaLib] Sort name table entries following OT spec prescribed order in the builder (#2927). +- [cu2quPen] Add Cu2QuMultiPen that converts multiple outlines at a time in + interpolation compatible way; its methods take a list of tuples arguments + that would normally be passed to individual segment pens, and at the end it + dispatches the converted outlines to each pen (#2912). +- [reverseContourPen/ttGlyphPen] Add outputImpliedClosingLine option (#2913, #2914, + #2921, #2922, #2995). +- [gvar] Avoid expanding all glyphs unnecessarily upon compile (#2918). +- [scaleUpem] Fixed bug whereby CFF2 vsindex was scaled; it should not (#2893, #2894). +- [designspaceLib] Add DS.getAxisByTag and refactor getAxis (#2891). +- [unicodedata] map Zmth<->math in ot_tag_{to,from}_script (#1737, #2889). +- [woff2] Support encoding/decoding OVERLAP_SIMPLE glyf flags (#2576, #2884). +- [instancer] Update OS/2 class and post.italicAngle when default moved (L4) +- Dropped support for Python 3.7 which reached EOL, fontTools requires 3.8+. +- [instancer] Fixed instantiateFeatureVariations logic when a rule range becomes + default-applicable (#2737, #2880). +- [ttLib] Add main to ttFont and ttCollection that just decompile and re-compile the + input font (#2869). +- [featureVars] Insert 'rvrn' lookup at the beginning of LookupList, to work around bug + in Apple implementation of 'rvrn' feature which the spec says it should be processed + early whereas on macOS 10.15 it follows lookup order (#2140, #2867). +- [instancer/mutator] Remove 'DSIG' table if present. +- [svgPathPen] Don't close path in endPath(), assume open unless closePath() (#2089, #2865). + +4.38.0 (released 2022-10-21) +---------------------------- + +- [varLib.instancer] Added support for L4 instancing, i.e. moving the default value of + an axis while keeping it variable. Thanks Behdad! (#2728, #2861). + It's now also possible to restrict an axis min/max values beyond the current default + value, e.g. a font wght has min=100, def=400, max=900 and you want a partial VF that + only varies between 500 and 700, you can now do that. + You can either specify two min/max values (wght=500:700), and the new default will be + set to either the minimum or maximum, depending on which one is closer to the current + default (e.g. 500 in this case). Or you can specify three values (e.g. wght=500:600:700) + to specify the new default value explicitly. +- [otlLib/featureVars] Set a few Count values so one doesn't need to compile the font + to update them (#2860). +- [varLib.models] Make extrapolation work for 2-master models as well where one master + is at the default location (#2843, #2846). + Add optional extrapolate=False to normalizeLocation() (#2847, #2849). +- [varLib.cff] Fixed sub-optimal packing of CFF2 deltas by no longer rounding them to + integer (#2838). +- [scaleUpem] Calculate numShorts in VarData after scale; handle CFF hintmasks (#2840). + +4.37.4 (released 2022-09-30) +---------------------------- + +- [subset] Keep nameIDs used by CPAL palette entry labels (#2837). +- [varLib] Avoid negative hmtx values when creating font from variable CFF2 font (#2827). +- [instancer] Don't prune stat.ElidedFallbackNameID (#2828). +- [unicodedata] Update Scripts/Blocks to Unicode 15.0 (#2833). + +4.37.3 (released 2022-09-20) +---------------------------- + +- Fix arguments in calls to (glyf) glyph.draw() and drawPoints(), whereby offset wasn't + correctly passed down; this fix also exposed a second bug, where lsb and tsb were not + set (#2824, #2825, adobe-type-tools/afdko#1560). + +4.37.2 (released 2022-09-15) +---------------------------- + +- [subset] Keep CPAL table and don't attempt to prune unused color indices if OT-SVG + table is present even if COLR table was subsetted away; OT-SVG may be referencing the + CPAL table; for now we assume that's the case (#2814, #2815). +- [varLib.instancer] Downgrade GPOS/GSUB version if there are no more FeatureVariations + after instancing (#2812). +- [subset] Added ``--no-lazy`` to optionally load fonts eagerly (mostly to ease + debugging of table lazy loading, no practical effects) (#2807). +- [varLib] Avoid building empty COLR.DeltaSetIndexMap with only identity mappings (#2803). +- [feaLib] Allow multiple value record types (by promoting to the most general format) + within the same PairPos subtable; e.g. this allows variable and non variable kerning + rules to share the same subtable. This also fixes a bug whereby some kerning pairs + would become unreachable while shapiong because of premature subtable splitting (#2772, #2776). +- [feaLib] Speed up ``VarScalar`` by caching models for recurring master locations (#2798). +- [feaLib] Optionally cythonize ``feaLib.lexer``, speeds up parsing FEA a bit (#2799). +- [designspaceLib] Avoid crash when handling unbounded rule conditions (#2797). +- [post] Don't crash if ``post`` legacy format 1 is malformed/improperly used (#2786) +- [gvar] Don't be "lazy" (load all glyph variations up front) when TTFont.lazy=False (#2771). +- [TTFont] Added ``normalizeLocation`` method to normalize a location dict from the + font's defined axes space (also known as "user space") into the normalized (-1..+1) + space. It applies ``avar`` mapping if the font contains an ``avar`` table (#2789). +- [TTVarGlyphSet] Support drawing glyph instances from CFF2 variable glyph set (#2784). +- [fontBuilder] Do not error when building cmap if there are zero code points (#2785). +- [varLib.plot] Added ability to plot a variation model and set of accompaning master + values corresponding to the model's master locations into a pyplot figure (#2767). +- [Snippets] Added ``statShape.py`` script to draw statistical shape of a glyph as an + ellips (requires pycairo) (baecd88). +- [TTVarGlyphSet] implement drawPoints natively, avoiding going through + SegmentToPointPen (#2778). +- [TTVarGlyphSet] Fixed bug whereby drawing a composite glyph multiple times, its + components would shif; needed an extra copy (#2774). + +4.37.1 (released 2022-08-24) +---------------------------- + +- [subset] Fixed regression introduced with v4.37.0 while subsetting the VarStore of + ``HVAR`` and ``VVAR`` tables, whereby an ``AttributeError: subset_varidxes`` was + thrown because an apparently unused import statement (with the side-effect of + dynamically binding that ``subset_varidxes`` method to the VarStore class) had been + accidentally deleted in an unrelated PR (#2679, #2773). +- [pens] Added ``cairoPen`` (#2678). +- [gvar] Read ``gvar`` more lazily by not parsing all of the ``glyf`` table (#2771). +- [ttGlyphSet] Make ``drawPoints(pointPen)`` method work for CFF fonts as well via + adapter pen (#2770). + +4.37.0 (released 2022-08-23) +---------------------------- + +- [varLib.models] Reverted PR #2717 which added support for "narrow tents" in v4.36.0, + as it introduced a regression (#2764, #2765). It will be restored in upcoming release + once we found a solution to the bug. +- [cff.specializer] Fixed issue in charstring generalizer with the ``blend`` operator + (#2750, #1975). +- [varLib.models] Added support for extrapolation (#2757). +- [ttGlyphSet] Ensure the newly added ``_TTVarGlyphSet`` inherits from ``_TTGlyphSet`` + to keep backward compatibility with existing API (#2762). +- [kern] Allow compiling legacy kern tables with more than 64k entries (d21cfdede). +- [visitor] Added new visitor API to traverse tree of objects and dispatch based + on the attribute type: cf. ``fontTools.misc.visitor`` and ``fontTools.ttLib.ttVisitor``. Added ``fontTools.ttLib.scaleUpem`` module that uses the latter to + change a font's units-per-em and scale all the related fields accordingly (#2718, + #2755). + +4.36.0 (released 2022-08-17) +---------------------------- + +- [varLib.models] Use a simpler model that generates narrower "tents" (regions, master + supports) whenever possible: specifically when any two axes that actively "cooperate" + (have masters at non-zero positions for both axes) have a complete set of intermediates. + The simpler algorithm produces fewer overlapping regions and behaves better with + respect to rounding at the peak positions than the generic solver, always matching + intermediate masters exactly, instead of maximally 0.5 units off. This may be useful + when 100% metrics compatibility is desired (#2218, #2717). +- [feaLib] Remove warning when about ``GDEF`` not being built when explicitly not + requested; don't build one unconditonally even when not requested (#2744, also works + around #2747). +- [ttFont] ``TTFont.getGlyphSet`` method now supports selecting a location that + represents an instance of a variable font (supports both user-scale and normalized + axes coordinates via the ``normalized=False`` parameter). Currently this only works + for TrueType-flavored variable fonts (#2738). + +4.35.0 (released 2022-08-15) +---------------------------- + +- [otData/otConverters] Added support for 'biased' PaintSweepGradient start/end angles + to match latest COLRv1 spec (#2743). +- [varLib.instancer] Fixed bug in ``_instantiateFeatureVariations`` when at the same + time pinning one axis and restricting the range of a subsequent axis; the wrong axis + tag was being used in the latter step (as the records' axisIdx was updated in the + preceding step but looked up using the old axes order in the following step) (#2733, + #2734). +- [mtiLib] Pad script tags with space when less than 4 char long (#1727). +- [merge] Use ``'.'`` instead of ``'#'`` in duplicate glyph names (#2742). +- [gvar] Added support for lazily loading glyph variations (#2741). +- [varLib] In ``build_many``, we forgot to pass on ``colr_layer_reuse`` parameter to + the ``build`` method (#2730). +- [svgPathPen] Add a main that prints SVG for input text (6df779fd). +- [cffLib.width] Fixed off-by-one in optimized values; previous code didn't match the + code block above it (2963fa50). +- [varLib.interpolatable] Support reading .designspace and .glyphs files (via optional + ``glyphsLib``). +- Compile some modules with Cython when available and building/installing fonttools + from source: ``varLib.iup`` (35% faster), ``pens.momentsPen`` (makes + ``varLib.interpolatable`` 3x faster). +- [feaLib] Allow features to be built for VF without also building a GDEF table (e.g. + only build GSUB); warn when GDEF would be needed but isn't requested (#2705, 2694). +- [otBase] Fixed ``AttributeError`` when uharfbuzz < 0.23.0 and 'repack' method is + missing (32aa8eaf). Use new ``uharfbuzz.repack_with_tag`` when available (since + uharfbuzz>=0.30.0), enables table-specific optimizations to be performed during + repacking (#2724). +- [statisticsPen] By default report all glyphs (4139d891). Avoid division-by-zero + (52b28f90). +- [feaLib] Added missing required argument to FeatureLibError exception (#2693) +- [varLib.merge] Fixed error during error reporting (#2689). Fixed undefined + ``NotANone`` variable (#2714). + +4.34.4 (released 2022-07-07) +---------------------------- + +- Fixed typo in varLib/merger.py that causes NameError merging COLR glyphs + containing more than 255 layers (#2685). + +4.34.3 (released 2022-07-07) +---------------------------- + +- [designspaceLib] Don't make up bad PS names when no STAT data (#2684) + +4.34.2 (released 2022-07-06) +---------------------------- + +- [varStore/subset] fixed KeyError exception to do with NO_VARIATION_INDEX while + subsetting varidxes in GPOS/GDEF (a08140d). + +4.34.1 (released 2022-07-06) +---------------------------- + +- [instancer] When optimizing HVAR/VVAR VarStore, use_NO_VARIATION_INDEX=False to avoid + including NO_VARIATION_INDEX in AdvWidthMap, RsbMap, LsbMap mappings, which would + push the VarIdx width to maximum (4bytes), which is not desirable. This also fixes + a hard crash when attempting to subset a varfont after it had been partially instanced + with use_NO_VARIATION_INDEX=True. + +4.34.0 (released 2022-07-06) +---------------------------- + +- [instancer] Set RIBBI bits in head and OS/2 table when cutting instances and the + subfamily nameID=2 contains strings like 'Italic' or 'Bold' (#2673). +- [otTraverse] Addded module containing methods for traversing trees of otData tables + (#2660). +- [otTables] Made DeltaSetIndexMap TTX dump less verbose by omitting no-op entries + (#2660). +- [colorLib.builder] Added option to disable PaintColrLayers's reuse of layers from + LayerList (#2660). +- [varLib] Added support for merging multiple master COLRv1 tables into a variable + COLR table (#2660, #2328). Base color glyphs of same name in different masters must have + identical paint graph structure (incl. number of layers, palette indices, number + of color line stops, corresponding paint formats at each level of the graph), + but can differ in the variable fields (e.g. PaintSolid.Alpha). PaintVar* tables + are produced when this happens and a VarStore/DeltaSetIndexMap is added to the + variable COLR table. It is possible for non-default masters to be 'sparse', i.e. + omit some of the color glyphs present in the default master. +- [feaLib] Let the Parser set nameIDs 1 through 6 that were previously reserved (#2675). +- [varLib.varStore] Support NO_VARIATION_INDEX in optimizer and instancer. +- [feaLib] Show all missing glyphs at once at end of parsing (#2665). +- [varLib.iup] Rewrite force-set conditions and limit DP loopback length (#2651). + For Noto Sans, IUP time drops from 23s down to 9s, with only a slight size increase + in the final font. This basically turns the algorithm from O(n^3) into O(n). +- [featureVars] Report about missing glyphs in substitution rules (#2654). +- [mutator/instancer] Added CLI flag to --no-recalc-timestamp (#2649). +- [SVG] Allow individual SVG documents in SVG OT table to be compressed on uncompressed, + and remember that when roundtripping to/from ttx. The SVG.docList is now a list + of SVGDocument namedtuple-like dataclass containing an extra ``compressed`` field, + and no longer a bare 3-tuple (#2645). +- [designspaceLib] Check for descriptor types with hasattr() to allow custom classes + that don't inherit the default descriptors (#2634). +- [subset] Enable sharing across subtables of extension lookups for harfbuzz packing + (#2626). Updated how table packing falls back to fontTools from harfbuzz (#2668). +- [subset] Updated default feature tags following current Harfbuzz (#2637). +- [svgLib] Fixed regex for real number to support e.g. 1e-4 in addition to 1.0e-4. + Support parsing negative rx, ry on arc commands (#2596, #2611). +- [subset] Fixed subsetting SinglePosFormat2 when ValueFormat=0 (#2603). + +4.33.3 (released 2022-04-26) +---------------------------- + +- [designspaceLib] Fixed typo in ``deepcopyExceptFonts`` method, preventing font + references to be transferred (#2600). Fixed another typo in the name of ``Range`` + dataclass's ``__post_init__`` magic method (#2597). + +4.33.2 (released 2022-04-22) +---------------------------- + +- [otBase] Make logging less verbose when harfbuzz fails to serialize. Do not exit + at the first failure but continue attempting to fix offset overflow error using + the pure-python serializer even when the ``USE_HARFBUZZ_REPACKER`` option was + explicitly set to ``True``. This is normal with fonts with relatively large + tables, at least until hb.repack implements proper table splitting. + +4.33.1 (released 2022-04-22) +---------------------------- + +- [otlLib] Put back the ``FONTTOOLS_GPOS_COMPACT_MODE`` environment variable to fix + regression in ufo2ft (and thus fontmake) introduced with v4.33.0 (#2592, #2593). + This is deprecated and will be removed one ufo2ft gets updated to use the new + config setup. + +4.33.0 (released 2022-04-21) +---------------------------- + +- [OS/2 / merge] Automatically recalculate ``OS/2.xAvgCharWidth`` after merging + fonts with ``fontTools.merge`` (#2591, #2538). +- [misc/config] Added ``fontTools.misc.configTools`` module, a generic configuration + system (#2416, #2439). + Added ``fontTools.config`` module, a fontTools-specific configuration + system using ``configTools`` above. + Attached a ``Config`` object to ``TTFont``. +- [otlLib] Replaced environment variable for GPOS compression level with an + equivalent option using the new config system. +- [designspaceLib] Incremented format version to 5.0 (#2436). + Added discrete axes, variable fonts, STAT information, either design- or + user-space location on instances. + Added ``fontTools.designspaceLib.split`` module to split a designspace + into sub-spaces that interpolate and that represent the variable fonts + listed in the document. + Made instance names optional and allow computing them from STAT data instead. + Added ``fontTools.designspaceLib.statNames`` module. + Allow instances to have the same location as a previously defined STAT label. + Deprecated some attributes: + ``SourceDescriptor``: ``copyLib``, ``copyInfo``, ``copyGroups``, ``copyFeatures``. + ``InstanceDescriptor``: ``kerning``, ``info``; ``glyphs``: use rules or sparse + sources. + For both, ``location``: use the more explicit designLocation. + Note: all are soft deprecations and existing code should keep working. + Updated documentation for Python methods and the XML format. +- [varLib] Added ``build_many`` to build several variable fonts from a single + designspace document (#2436). + Added ``fontTools.varLib.stat`` module to build STAT tables from a designspace + document. +- [otBase] Try to use the Harfbuzz Repacker for packing GSUB/GPOS tables when + ``uharfbuzz`` python bindings are available (#2552). Disable it by setting the + "fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER" config option to ``False``. + If the option is set explicitly to ``True`` but ``uharfbuzz`` can't be imported + or fails to serialize for any reasons, an error will be raised (ImportError or + uharfbuzz errors). +- [CFF/T2] Ensure that ``pen.closePath()`` gets called for CFF2 charstrings (#2577). + Handle implicit CFF2 closePath within ``T2OutlineExtractor`` (#2580). + +4.32.0 (released 2022-04-08) +---------------------------- + +- [otlLib] Disable GPOS7 optimization to work around bug in Apple CoreText. + Always force Chaining GPOS8 for now (#2540). +- [glifLib] Added ``outputImpliedClosingLine=False`` parameter to ``Glyph.draw()``, + to control behaviour of ``PointToSegmentPen`` (6b4e2e7). +- [varLib.interpolatable] Check for wrong contour starting point (#2571). +- [cffLib] Remove leftover ``GlobalState`` class and fix calls to ``TopDictIndex()`` + (#2569, #2570). +- [instancer] Clear ``AxisValueArray`` if it is empty after instantiating (#2563). + +4.31.2 (released 2022-03-22) +---------------------------- + +- [varLib] fix instantiation of GPOS SinglePos values (#2555). + +4.31.1 (released 2022-03-18) +---------------------------- + +- [subset] fix subsetting OT-SVG when glyph id attribute is on the root ```` + element (#2553). + +4.31.0 (released 2022-03-18) +---------------------------- + +- [ttCollection] Fixed 'ResourceWarning: unclosed file' warning (#2549). +- [varLib.merger] Handle merging SinglePos with valueformat=0 (#2550). +- [ttFont] Update glyf's glyphOrder when calling TTFont.setGlyphOrder() (#2544). +- [ttFont] Added ``ensureDecompiled`` method to load all tables irrespective + of the ``lazy`` attribute (#2551). +- [otBase] Added ``iterSubTable`` method to iterate over BaseTable's children of + type BaseTable; useful for traversing a tree of otTables (#2551). + +4.30.0 (released 2022-03-10) +---------------------------- + +- [varLib] Added debug logger showing the glyph name for which ``gvar`` is built (#2542). +- [varLib.errors] Fixed undefined names in ``FoundANone`` and ``UnsupportedFormat`` + exceptions (ac4d5611). +- [otlLib.builder] Added ``windowsNames`` and ``macNames`` (bool) parameters to the + ``buildStatTabe`` function, so that one can select whether to only add one or both + of the two sets (#2528). +- [t1Lib] Added the ability to recreate PostScript stream (#2504). +- [name] Added ``getFirstDebugName``, ``getBest{Family,SubFamily,Full}Name`` methods (#2526). + +4.29.1 (released 2022-02-01) +---------------------------- + +- [colorLib] Fixed rounding issue with radial gradient's start/end circles inside + one another (#2521). +- [freetypePen] Handle rotate/skew transform when auto-computing width/height of the + buffer; raise PenError wen missing moveTo (#2517) + +4.29.0 (released 2022-01-24) +---------------------------- + +- [ufoLib] Fixed illegal characters and expanded reserved filenames (#2506). +- [COLRv1] Don't emit useless PaintColrLayers of lenght=1 in LayerListBuilder (#2513). +- [ttx] Removed legacy ``waitForKeyPress`` method on Windows (#2509). +- [pens] Added FreeTypePen that uses ``freetype-py`` and the pen protocol for + rasterizating outline paths (#2494). +- [unicodedata] Updated the script direction list to Unicode 14.0 (#2484). + Bumped unicodedata2 dependency to 14.0 (#2499). +- [psLib] Fixed type of ``fontName`` in ``suckfont`` (#2496). + +4.28.5 (released 2021-12-19) +---------------------------- + +- [svgPathPen] Continuation of #2471: make sure all occurrences of ``str()`` are now + replaced with user-defined ``ntos`` callable. +- [merge] Refactored code into submodules, plus several bugfixes and improvements: + fixed duplicate-glyph-resolution GSUB-lookup generation code; use tolerance in glyph + comparison for empty glyph's width; ignore space of default ignorable glyphs; + downgrade duplicates-resolution missing-GSUB from assert to warn; added --drop-tables + option (#2473, #2475, #2476). + +4.28.4 (released 2021-12-15) +---------------------------- + +- [merge] Merge GDEF marksets in Lookups properly (#2474). +- [feaLib] Have ``fontTools feaLib`` script exit with error code when build fails (#2459) +- [svgPathPen] Added ``ntos`` option to customize number formatting (e.g. rounding) (#2471). +- [subset] Speed up subsetting of large CFF fonts (#2467). +- [otTables] Speculatively promote lookups to extension to speed up compilation. If the + offset to lookup N is too big to fit in a ushort, the offset to lookup N+1 is going to + be too big as well, so we promote to extension all lookups from lookup N onwards (#2465). + +4.28.3 (released 2021-12-03) +---------------------------- + +- [subset] Fixed bug while subsetting ``COLR`` table, whereby incomplete layer records + pointing to missing glyphs were being retained leading to ``struct.error`` upon + compiling. Make it so that ``glyf`` glyph closure, which follows the ``COLR`` glyph + closure, does not influence the ``COLR`` table subsetting (#2461, #2462). +- [docs] Fully document the ``cmap`` and ``glyf`` tables (#2454, #2457). +- [colorLib.unbuilder] Fixed CLI by deleting no longer existing parameter (180bb1867). + +4.28.2 (released 2021-11-22) +---------------------------- + +- [otlLib] Remove duplicates when building coverage (#2433). +- [docs] Add interrogate configuration (#2443). +- [docs] Remove comment about missing “start” optional argument to ``calcChecksum`` (#2448). +- [cu2qu/cli] Adapt to the latest ufoLib2. +- [subset] Support subsetting SVG table and remove it from the list of drop by default tables (#534). +- [subset] add ``--pretty-svg`` option to pretty print SVG table contents (#2452). +- [merge] Support merging ``CFF`` tables (CID-keyed ``CFF`` is still not supported) (#2447). +- [merge] Support ``--output-file`` (#2447). +- [docs] Split table docs into individual pages (#2444). +- [feaLib] Forbid empty classes (#2446). +- [docs] Improve documentation for ``fontTools.ttLib.ttFont`` (#2442). + +4.28.1 (released 2021-11-08) +---------------------------- + +- [subset] Fixed AttributeError while traversing a color glyph's Paint graph when there is no + LayerList, which is optional (#2441). + +4.28.0 (released 2021-11-05) +---------------------------- + +- Dropped support for EOL Python 3.6, require Python 3.7 (#2417). +- [ufoLib/glifLib] Make filename-clash checks faster by using a set instead of a list (#2422). +- [subset] Don't crash if optional ClipList and LayerList are ``None`` (empty) (#2424, 2439). +- [OT-SVG] Removed support for old deprecated version 1 and embedded color palettes, + which were never officially part of the OpenType SVG spec. Upon compile, reuse offsets + to SVG documents that are identical (#2430). +- [feaLib] Added support for Variable Feature File syntax. This is experimental and subject + to change until it is finalized in the Adobe FEA spec (#2432). +- [unicodedata] Update Scripts/ScriptExtensions/Blocks to UnicodeData 14.0 (#2437). + +4.27.1 (released 2021-09-23) +---------------------------- + +- [otlLib] Fixed error when chained contextual lookup builder overflows (#2404, #2411). +- [bezierTools] Fixed two floating-point bugs: one when computing `t` for a point + lying on an almost horizontal/vertical line; another when computing the intersection + point between a curve and a line (#2413). + +4.27.0 (released 2021-09-14) +---------------------------- + +- [ttLib/otTables] Cleaned up virtual GID handling: allow virtual GIDs in ``Coverage`` + and ``ClassDef`` readers; removed unused ``allowVID`` argument from ``TTFont`` + constructor, and ``requireReal`` argument in ``TTFont.getGlyphID`` method. + Make ``TTFont.setGlyphOrder`` clear reverse glyphOrder map, and assume ``glyphOrder`` + internal attribute is never modified outside setGlyphOrder; added ``TTFont.getGlyphNameMany`` + and ``getGlyphIDMany`` (#1536, #1654, #2334, #2398). +- [py23] Dropped internal use of ``fontTools.py23`` module to fix deprecation warnings + in client code that imports from fontTools (#2234, #2399, #2400). +- [subset] Fix subsetting COLRv1 clip boxes when font is loaded lazily (#2408). + +4.26.2 (released 2021-08-09) +---------------------------- + +- [otTables] Added missing ``CompositeMode.PLUS`` operator (#2390). + +4.26.1 (released 2021-08-03) +---------------------------- + +- [transform] Added ``transformVector`` and ``transformVectors`` methods to the + ``Transform`` class. Similar to ``transformPoint`` but ignore the translation + part (#2386). + +4.26.0 (released 2021-08-03) +---------------------------- + +- [xmlWriter] Default to ``"\n"`` for ``newlinestr`` instead of platform-specific + ``os.linesep`` (#2384). +- [otData] Define COLRv1 ClipList and ClipBox (#2379). +- [removeOverlaps/instancer] Added --ignore-overlap-errors option to work around + Skia PathOps.Simplify bug (#2382, #2363, google/fonts#3365). +- NOTE: This will be the last version to support Python 3.6. FontTools will require + Python 3.7 or above from the next release (#2350) + +4.25.2 (released 2021-07-26) +---------------------------- + +- [COLRv1] Various changes to sync with the latest CORLv1 draft spec. In particular: + define COLR.VarIndexMap, remove/inline ColorIndex struct, add VarIndexBase to ``PaintVar*`` tables (#2372); + add reduced-precicion specialized transform Paints; + define Angle as fraction of half circle encoded as F2Dot14; + use FWORD (int16) for all Paint center coordinates; + change PaintTransform to have an offset to Affine2x3; +- [ttLib] when importing XML, only set sfntVersion if the font has no reader and is empty (#2376) + +4.25.1 (released 2021-07-16) +---------------------------- + +- [ttGlyphPen] Fixed bug in ``TTGlyphPointPen``, whereby open contours (i.e. starting + with segmentType "move") would throw ``NotImplementedError``. They are now treated + as if they are closed, like with the ``TTGlyphPen`` (#2364, #2366). + +4.25.0 (released 2021-07-05) +---------------------------- + +- [tfmLib] Added new library for parsing TeX Font Metric (TFM) files (#2354). +- [TupleVariation] Make shared tuples order deterministic on python < 3.7 where + Counter (subclass of dict) doesn't remember insertion order (#2351, #2353). +- [otData] Renamed COLRv1 structs to remove 'v1' suffix and match the updated draft + spec: 'LayerV1List' -> 'LayerList', 'BaseGlyphV1List' -> 'BaseGlyphList', + 'BaseGlyphV1Record' -> 'BaseGlyphPaintRecord' (#2346). + Added 8 new ``PaintScale*`` tables: with/without centers, uniform vs non-uniform. + Added ``*AroundCenter`` variants to ``PaintRotate`` and ``PaintSkew``: the default + versions no longer have centerX/Y, but default to origin. + ``PaintRotate``, ``PaintSkew`` and ``PaintComposite`` formats were re-numbered. + NOTE: these are breaking changes; clients using the experimental COLRv1 API will + have to be updated (#2348). +- [pointPens] Allow ``GuessSmoothPointPen`` to accept a tolerance. Fixed call to + ``math.atan2`` with x/y parameters inverted. Sync the code with fontPens (#2344). +- [post] Fixed parsing ``post`` table format 2.0 when it contains extra garbage + at the end of the stringData array (#2314). +- [subset] drop empty features unless 'size' with FeatureParams table (#2324). +- [otlLib] Added ``otlLib.optimize`` module; added GPOS compaction algorithm. + The compaction can be run on existing fonts with ``fonttools otlLib.optimize`` + or using the snippet ``compact_gpos.py``. There's experimental support for + compacting fonts at compilation time using an environment variable, but that + might be removed later (#2326). + +4.24.4 (released 2021-05-25) +---------------------------- + +- [subset/instancer] Fixed ``AttributeError`` when instantiating a VF that + contains GPOS ValueRecords with ``Device`` tables but without the respective + non-Device values (e.g. ``XAdvDevice`` without ``XAdvance``). When not + explicitly set, the latter are assumed to be 0 (#2323). + +4.24.3 (released 2021-05-20) +---------------------------- + +- [otTables] Fixed ``AttributeError`` in methods that split LigatureSubst, + MultipleSubst and AlternateSubst subtables when an offset overflow occurs. + The ``Format`` attribute was removed in v4.22.0 (#2319). + +4.24.2 (released 2021-05-20) +---------------------------- + +- [ttGlyphPen] Fixed typing annotation of TTGlyphPen glyphSet parameter (#2315). +- Fixed two instances of DeprecationWarning: invalid escape sequence (#2311). + +4.24.1 (released 2021-05-20) +---------------------------- + +- [subset] Fixed AttributeError when SinglePos subtable has None Value (ValueFormat 0) + (#2312, #2313). + +4.24.0 (released 2021-05-17) +---------------------------- + +- [pens] Add ``ttGlyphPen.TTGlyphPointPen`` similar to ``TTGlyphPen`` (#2205). + +4.23.1 (released 2021-05-14) +---------------------------- + +- [subset] Fix ``KeyError`` after subsetting ``COLR`` table that initially contains + both v0 and v1 color glyphs when the subset only requested v1 glyphs; we were + not pruning the v0 portion of the table (#2308). +- [colorLib] Set ``LayerV1List`` attribute to ``None`` when empty, it's optional + in CORLv1 (#2308). + +4.23.0 (released 2021-05-13) +---------------------------- + +- [designspaceLib] Allow to use ``\\UNC`` absolute paths on Windows (#2299, #2306). +- [varLib.merger] Fixed bug where ``VarLibMergeError`` was raised with incorrect + parameters (#2300). +- [feaLib] Allow substituting a glyph class with ``NULL`` to delete multiple glyphs + (#2303). +- [glyf] Fixed ``NameError`` exception in ``getPhantomPoints`` (#2295, #2305). +- [removeOverlaps] Retry pathops.simplify after rounding path coordinates to integers + if it fails the first time using floats, to work around a rare and hard to debug + Skia bug (#2288). +- [varLib] Added support for building, reading, writing and optimizing 32-bit + ``ItemVariationStore`` as used in COLRv1 table (#2285). +- [otBase/otConverters] Add array readers/writers for int types (#2285). +- [feaLib] Allow more than one lookahead glyph/class in contextual positioning with + "value at end" (#2293, #2294). +- [COLRv1] Default varIdx should be 0xFFFFFFFF (#2297, #2298). +- [pens] Make RecordingPointPen actually pass on identifiers; replace asserts with + explicit ``PenError`` exception (#2284). +- [mutator] Round lsb for CF2 fonts as well (#2286). + +4.22.1 (released 2021-04-26) +---------------------------- + +- [feaLib] Skip references to named lookups if the lookup block definition + is empty, similarly to makeotf. This also fixes an ``AttributeError`` while + generating ``aalt`` feature (#2276, #2277). +- [subset] Fixed bug with ``--no-hinting`` implementation for Device tables (#2272, + #2275). The previous code was alwyas dropping Device tables if no-hinting was + requested, but some Device tables (DeltaFormat=0x8000) are also used to encode + variation indices and need to be retained. +- [otBase] Fixed bug in getting the ValueRecordSize when decompiling ``MVAR`` + table with ``lazy=True`` (#2273, #2274). +- [varLib/glyf/gvar] Optimized and simplified ``GlyphCoordinates`` and + ``TupleVariation`` classes, use ``bytearray`` where possible, refactored + phantom-points calculations. We measured about 30% speedup in total time + of loading master ttfs, building gvar, and saving (#2261, #2266). +- [subset] Fixed ``AssertionError`` while pruning unused CPAL palettes when + ``0xFFFF`` is present (#2257, #2259). + +4.22.0 (released 2021-04-01) +---------------------------- + +- [ttLib] Remove .Format from Coverage, ClassDef, SingleSubst, LigatureSubst, + AlternateSubst, MultipleSubst (#2238). + ATTENTION: This will change your TTX dumps! +- [misc.arrayTools] move Vector to its own submodule, and rewrite as a tuple + subclass (#2201). +- [docs] Added a terminology section for varLib (#2209). +- [varLib] Move rounding to VariationModel, to avoid error accumulation from + multiple deltas (#2214) +- [varLib] Explain merge errors in more human-friendly terms (#2223, #2226) +- [otlLib] Correct some documentation (#2225) +- [varLib/otlLib] Allow merging into VariationFont without first saving GPOS + PairPos2 (#2229) +- [subset] Improve PairPosFormat2 subsetting (#2221) +- [ttLib] TTFont.save: create file on disk as late as possible (#2253) +- [cffLib] Add missing CFF2 dict operators LanguageGroup and ExpansionFactor + (#2249) + ATTENTION: This will change your TTX dumps! + +4.21.1 (released 2021-02-26) +---------------------------- + +- [pens] Reverted breaking change that turned ``AbstractPen`` and ``AbstractPointPen`` + into abstract base classes (#2164, #2198). + +4.21.0 (released 2021-02-26) +---------------------------- + +- [feaLib] Indent anchor statements in ``asFea()`` to make them more legible and + diff-able (#2193). +- [pens] Turn ``AbstractPen`` and ``AbstractPointPen`` into abstract base classes + (#2164). +- [feaLib] Added support for parsing and building ``STAT`` table from AFDKO feature + files (#2039). +- [instancer] Added option to update name table of generated instance using ``STAT`` + table's axis values (#2189). +- [bezierTools] Added functions to compute bezier point-at-time, as well as line-line, + curve-line and curve-curve intersections (#2192). + +4.20.0 (released 2021-02-15) +---------------------------- + +- [COLRv1] Added ``unbuildColrV1`` to deconstruct COLRv1 otTables to raw json-able + data structure; it does the reverse of ``buildColrV1`` (#2171). +- [feaLib] Allow ``sub X by NULL`` sequence to delete a glyph (#2170). +- [arrayTools] Fixed ``Vector`` division (#2173). +- [COLRv1] Define new ``PaintSweepGradient`` (#2172). +- [otTables] Moved ``Paint.Format`` enum class outside of ``Paint`` class definition, + now named ``PaintFormat``. It was clashing with paint instance ``Format`` attribute + and thus was breaking lazy load of COLR table which relies on magic ``__getattr__`` + (#2175). +- [COLRv1] Replace hand-coded builder functions with otData-driven dynamic + implementation (#2181). +- [COLRv1] Define additional static (non-variable) Paint formats (#2181). +- [subset] Added support for subsetting COLR v1 and CPAL tables (#2174, #2177). +- [fontBuilder] Allow ``setupFvar`` to optionally take ``designspaceLib.AxisDescriptor`` + objects. Added new ``setupAvar`` method. Support localised names for axes and + named instances (#2185). + +4.19.1 (released 2021-01-28) +---------------------------- + +- [woff2] An initial off-curve point with an overlap flag now stays an off-curve + point after compression. + +4.19.0 (released 2021-01-25) +---------------------------- + +- [codecs] Handle ``errors`` parameter different from 'strict' for the custom + extended mac encodings (#2137, #2132). +- [featureVars] Raise better error message when a script is missing the required + default language system (#2154). +- [COLRv1] Avoid abrupt change caused by rounding ``PaintRadialGradient.c0`` when + the start circle almost touches the end circle's perimeter (#2148). +- [COLRv1] Support building unlimited lists of paints as 255-ary trees of + ``PaintColrLayers`` tables (#2153). +- [subset] Prune redundant format-12 cmap subtables when all non-BMP characters + are dropped (#2146). +- [basePen] Raise ``MissingComponentError`` instead of bare ``KeyError`` when a + referenced component is missing (#2145). + +4.18.2 (released 2020-12-16) +---------------------------- + +- [COLRv1] Implemented ``PaintTranslate`` paint format (#2129). +- [varLib.cff] Fixed unbound local variable error (#1787). +- [otlLib] Don't crash when creating OpenType class definitions if some glyphs + occur more than once (#2125). + +4.18.1 (released 2020-12-09) +---------------------------- + +- [colorLib] Speed optimization for ``LayerV1ListBuilder`` (#2119). +- [mutator] Fixed missing tab in ``interpolate_cff2_metrics`` (0957dc7a). + +4.18.0 (released 2020-12-04) +---------------------------- + +- [COLRv1] Update to latest draft: added ``PaintRotate`` and ``PaintSkew`` (#2118). +- [woff2] Support new ``brotlicffi`` bindings for PyPy (#2117). +- [glifLib] Added ``expectContentsFile`` parameter to ``GlyphSet``, for use when + reading existing UFOs, to comply with the specification stating that a + ``contents.plist`` file must exist in a glyph set (#2114). +- [subset] Allow ``LangSys`` tags in ``--layout-scripts`` option (#2112). For example: + ``--layout-scripts=arab.dflt,arab.URD,latn``; this will keep ``DefaultLangSys`` + and ``URD`` language for ``arab`` script, and all languages for ``latn`` script. +- [varLib.interpolatable] Allow UFOs to be checked; report open paths, non existant + glyphs; add a ``--json`` option to produce a machine-readable list of + incompatibilities +- [pens] Added ``QuartzPen`` to create ``CGPath`` from glyph outlines on macOS. + Requires pyobjc (#2107). +- [feaLib] You can export ``FONTTOOLS_LOOKUP_DEBUGGING=1`` to enable feature file + debugging info stored in ``Debg`` table (#2106). +- [otlLib] Build more efficient format 1 and format 2 contextual lookups whenever + possible (#2101). + +4.17.1 (released 2020-11-16) +---------------------------- + +- [colorLib] Fixed regression in 4.17.0 when building COLR v0 table; when color + layers are stored in UFO lib plist, we can't distinguish tuples from lists so + we need to accept either types (e5439eb9, googlefonts/ufo2ft/issues#426). + +4.17.0 (released 2020-11-12) +---------------------------- + +- [colorLib/otData] Updated to latest draft ``COLR`` v1 spec (#2092). +- [svgLib] Fixed parsing error when arc commands' boolean flags are not separated + by space or comma (#2094). +- [varLib] Interpret empty non-default glyphs as 'missing', if the default glyph is + not empty (#2082). +- [feaLib.builder] Only stash lookup location for ``Debg`` if ``Builder.buildLookups_`` + has cooperated (#2065, #2067). +- [varLib] Fixed bug in VarStore optimizer (#2073, #2083). +- [varLib] Add designspace lib key for custom feavar feature tag (#2080). +- Add HashPointPen adapted from psautohint. With this pen, a hash value of a glyph + can be computed, which can later be used to detect glyph changes (#2005). + +4.16.1 (released 2020-10-05) +---------------------------- + +- [varLib.instancer] Fixed ``TypeError`` exception when instantiating a VF with + a GSUB table 1.1 in which ``FeatureVariations`` attribute is present but set to + ``None`` -- indicating that optional ``FeatureVariations`` is missing (#2077). +- [glifLib] Make ``x`` and ``y`` attributes of the ``point`` element required + even when validation is turned off, and raise a meaningful ``GlifLibError`` + message when that happens (#2075). + +4.16.0 (released 2020-09-30) +---------------------------- + +- [removeOverlaps] Added new module and ``removeOverlaps`` function that merges + overlapping contours and components in TrueType glyphs. It requires the + `skia-pathops `__ module. + Note that removing overlaps invalidates the TrueType hinting (#2068). +- [varLib.instancer] Added ``--remove-overlaps`` command-line option. + The ``overlap`` option in ``instantiateVariableFont`` now takes an ``OverlapMode`` + enum: 0: KEEP_AND_DONT_SET_FLAGS, 1: KEEP_AND_SET_FLAGS (default), and 2: REMOVE. + The latter is equivalent to calling ``removeOverlaps`` on the generated static + instance. The option continues to accept ``bool`` value for backward compatibility. + + +4.15.0 (released 2020-09-21) +---------------------------- + +- [plistlib] Added typing annotations to plistlib module. Set up mypy static + typechecker to run automatically on CI (#2061). +- [ttLib] Implement private ``Debg`` table, a reverse-DNS namespaced JSON dict. +- [feaLib] Optionally add an entry into the ``Debg`` table with the original + lookup name (if any), feature name / script / language combination (if any), + and original source filename and line location. Annotate the ttx output for + a lookup with the information from the Debg table (#2052). +- [sfnt] Disabled checksum checking by default in ``SFNTReader`` (#2058). +- [Docs] Document ``mtiLib`` module (#2027). +- [varLib.interpolatable] Added checks for contour node count and operation type + of each node (#2054). +- [ttLib] Added API to register custom table packer/unpacker classes (#2055). + +4.14.0 (released 2020-08-19) +---------------------------- + +- [feaLib] Allow anonymous classes in LookupFlags definitions (#2037). +- [Docs] Better document DesignSpace rules processing order (#2041). +- [ttLib] Fixed 21-year old bug in ``maxp.maxComponentDepth`` calculation (#2044, + #2045). +- [varLib.models] Fixed misspelled argument name in CLI entry point (81d0042a). +- [subset] When subsetting GSUB v1.1, fixed TypeError by checking whether the + optional FeatureVariations table is present (e63ecc5b). +- [Snippets] Added snippet to show how to decompose glyphs in a TTF (#2030). +- [otlLib] Generate GSUB type 5 and GPOS type 7 contextual lookups where appropriate + (#2016). + +4.13.0 (released 2020-07-10) +---------------------------- + +- [feaLib/otlLib] Moved lookup subtable builders from feaLib to otlLib; refactored + some common code (#2004, #2007). +- [docs] Document otlLib module (#2009). +- [glifLib] Fixed bug with some UFO .glif filenames clashing on case-insensitive + filesystems (#2001, #2002). +- [colorLib] Updated COLRv1 implementation following changes in the draft spec: + (#2008, googlefonts/colr-gradients-spec#24). + +4.12.1 (released 2020-06-16) +---------------------------- + +- [_n_a_m_e] Fixed error in ``addMultilingualName`` with one-character names. + Only attempt to recovered malformed UTF-16 data from a ``bytes`` string, + not from unicode ``str`` (#1997, #1998). + +4.12.0 (released 2020-06-09) +---------------------------- + +- [otlLib/varLib] Ensure that the ``AxisNameID`` in the ``STAT`` and ``fvar`` + tables is grater than 255 as per OpenType spec (#1985, #1986). +- [docs] Document more modules in ``fontTools.misc`` package: ``filenames``, + ``fixedTools``, ``intTools``, ``loggingTools``, ``macCreatorType``, ``macRes``, + ``plistlib`` (#1981). +- [OS/2] Don't calculate whole sets of unicode codepoints, use faster and more memory + efficient ranges and bisect lookups (#1984). +- [voltLib] Support writing back abstract syntax tree as VOLT data (#1983). +- [voltLib] Accept DO_NOT_TOUCH_CMAP keyword (#1987). +- [subset/merge] Fixed a namespace clash involving a private helper class (#1955). + +4.11.0 (released 2020-05-28) +---------------------------- + +- [feaLib] Introduced ``includeDir`` parameter on Parser and IncludingLexer to + explicitly specify the directory to search when ``include()`` statements are + encountered (#1973). +- [ufoLib] Silently delete duplicate glyphs within the same kerning group when reading + groups (#1970). +- [ttLib] Set version of COLR table when decompiling COLRv1 (commit 9d8a7e2). + +4.10.2 (released 2020-05-20) +---------------------------- + +- [sfnt] Fixed ``NameError: SimpleNamespace`` while reading TTC header. The regression + was introduced with 4.10.1 after removing ``py23`` star import. + +4.10.1 (released 2020-05-19) +---------------------------- + +- [sfnt] Make ``SFNTReader`` pickleable even when TTFont is loaded with lazy=True + option and thus keeps a reference to an external file (#1962, #1967). +- [feaLib.ast] Restore backward compatibility (broken in 4.10 with #1905) for + ``ChainContextPosStatement`` and ``ChainContextSubstStatement`` classes. + Make them accept either list of lookups or list of lists of lookups (#1961). +- [docs] Document some modules in ``fontTools.misc`` package: ``arrayTools``, + ``bezierTools`` ``cliTools`` and ``eexec`` (#1956). +- [ttLib._n_a_m_e] Fixed ``findMultilingualName()`` when name record's ``string`` is + encoded as bytes sequence (#1963). + +4.10.0 (released 2020-05-15) +---------------------------- + +- [varLib] Allow feature variations to be active across the entire space (#1957). +- [ufoLib] Added support for ``formatVersionMinor`` in UFO's ``fontinfo.plist`` and for + ``formatMinor`` attribute in GLIF file as discussed in unified-font-object/ufo-spec#78. + No changes in reading or writing UFOs until an upcoming (non-0) minor update of the + UFO specification is published (#1786). +- [merge] Fixed merging fonts with different versions of ``OS/2`` table (#1865, #1952). +- [subset] Fixed ``AttributeError`` while subsetting ``ContextSubst`` and ``ContextPos`` + Format 3 subtable (#1879, #1944). +- [ttLib.table._m_e_t_a] if data happens to be ascii, emit comment in TTX (#1938). +- [feaLib] Support multiple lookups per glyph position (#1905). +- [psCharStrings] Use inheritance to avoid repeated code in initializer (#1932). +- [Doc] Improved documentation for the following modules: ``afmLib`` (#1933), ``agl`` + (#1934), ``cffLib`` (#1935), ``cu2qu`` (#1937), ``encodings`` (#1940), ``feaLib`` + (#1941), ``merge`` (#1949). +- [Doc] Split off developer-centric info to new page, making front page of docs more + user-focused. List all utilities and sub-modules with brief descriptions. + Make README more concise and focused (#1914). +- [otlLib] Add function to build STAT table from high-level description (#1926). +- [ttLib._n_a_m_e] Add ``findMultilingualName()`` method (#1921). +- [unicodedata] Update ``RTL_SCRIPTS`` for Unicode 13.0 (#1925). +- [gvar] Sort ``gvar`` XML output by glyph name, not glyph order (#1907, #1908). +- [Doc] Added help options to ``fonttools`` command line tool (#1913, #1920). + Ensure all fonttools CLI tools have help documentation (#1948). +- [ufoLib] Only write fontinfo.plist when there actually is content (#1911). + +4.9.0 (released 2020-04-29) +--------------------------- + +- [subset] Fixed subsetting of FeatureVariations table. The subsetter no longer drops + FeatureVariationRecords that have empty substitutions as that will keep the search + going and thus change the logic. It will only drop empty records that occur at the + end of the FeatureVariationRecords array (#1881). +- [subset] Remove FeatureVariations table and downgrade GSUB/GPOS to version 0x10000 + when FeatureVariations contain no FeatureVariationRecords after subsetting (#1903). +- [agl] Add support for legacy Adobe Glyph List of glyph names in ``fontTools.agl`` + (#1895). +- [feaLib] Ignore superfluous script statements (#1883). +- [feaLib] Hide traceback by default on ``fonttools feaLib`` command line. + Use ``--traceback`` option to show (#1898). +- [feaLib] Check lookup index in chaining sub/pos lookups and print better error + message (#1896, #1897). +- [feaLib] Fix building chained alt substitutions (#1902). +- [Doc] Included all fontTools modules in the sphinx-generated documentation, and + published it to ReadTheDocs for continuous documentation of the fontTools project + (#1333). Check it out at https://fonttools.readthedocs.io/. Thanks to Chris Simpkins! +- [transform] The ``Transform`` class is now subclass of ``typing.NamedTuple``. No + change in functionality (#1904). + + +4.8.1 (released 2020-04-17) +--------------------------- + +- [feaLib] Fixed ``AttributeError: 'NoneType' has no attribute 'getAlternateGlyphs'`` + when ``aalt`` feature references a chain contextual substitution lookup + (googlefonts/fontmake#648, #1878). + +4.8.0 (released 2020-04-16) +--------------------------- + +- [feaLib] If Parser is initialized without a ``glyphNames`` parameter, it cannot + distinguish between a glyph name containing an hyphen, or a range of glyph names; + instead of raising an error, it now interprets them as literal glyph names, while + also outputting a logging warning to alert user about the ambiguity (#1768, #1870). +- [feaLib] When serializing AST to string, emit spaces around hyphens that denote + ranges. Also, fixed an issue with CID ranges when round-tripping AST->string->AST + (#1872). +- [Snippets/otf2ttf] In otf2ttf.py script update LSB in hmtx to match xMin (#1873). +- [colorLib] Added experimental support for building ``COLR`` v1 tables as per + the `colr-gradients-spec `__ + draft proposal. **NOTE**: both the API and the XML dump of ``COLR`` v1 are + susceptible to change while the proposal is being discussed and formalized (#1822). + +4.7.0 (released 2020-04-03) +--------------------------- + +- [cu2qu] Added ``fontTools.cu2qu`` package, imported from the original + `cu2qu `__ project. The ``cu2qu.pens`` module + was moved to ``fontTools.pens.cu2quPen``. The optional cu2qu extension module + can be compiled by installing `Cython `__ before installing + fonttools from source (i.e. git repo or sdist tarball). The wheel package that + is published on PyPI (i.e. the one ``pip`` downloads, unless ``--no-binary`` + option is used), will continue to be pure-Python for now (#1868). + +4.6.0 (released 2020-03-24) +--------------------------- + +- [varLib] Added support for building variable ``BASE`` table version 1.1 (#1858). +- [CPAL] Added ``fromRGBA`` method to ``Color`` class (#1861). + + +4.5.0 (released 2020-03-20) +--------------------------- + +- [designspaceLib] Added ``add{Axis,Source,Instance,Rule}Descriptor`` methods to + ``DesignSpaceDocument`` class, to initialize new descriptor objects using keyword + arguments, and at the same time append them to the current document (#1860). +- [unicodedata] Update to Unicode 13.0 (#1859). + +4.4.3 (released 2020-03-13) +--------------------------- + +- [varLib] Always build ``gvar`` table for TrueType-flavored Variable Fonts, + even if it contains no variation data. The table is required according to + the OpenType spec (#1855, #1857). + +4.4.2 (released 2020-03-12) +--------------------------- + +- [ttx] Annotate ``LookupFlag`` in XML dump with comment explaining what bits + are set and what they mean (#1850). +- [feaLib] Added more descriptive message to ``IncludedFeaNotFound`` error (#1842). + +4.4.1 (released 2020-02-26) +--------------------------- + +- [woff2] Skip normalizing ``glyf`` and ``loca`` tables if these are missing from + a font (e.g. in NotoColorEmoji using ``CBDT/CBLC`` tables). +- [timeTools] Use non-localized date parsing in ``timestampFromString``, to fix + error when non-English ``LC_TIME`` locale is set (#1838, #1839). +- [fontBuilder] Make sure the CFF table generated by fontBuilder can be used by varLib + without having to compile and decompile the table first. This was breaking in + converting the CFF table to CFF2 due to some unset attributes (#1836). + +4.4.0 (released 2020-02-18) +--------------------------- + +- [colorLib] Added ``fontTools.colorLib.builder`` module, initially with ``buildCOLR`` + and ``buildCPAL`` public functions. More color font formats will follow (#1827). +- [fontBuilder] Added ``setupCOLR`` and ``setupCPAL`` methods (#1826). +- [ttGlyphPen] Quantize ``GlyphComponent.transform`` floats to ``F2Dot14`` to fix + round-trip issue when computing bounding boxes of transformed components (#1830). +- [glyf] If a component uses reference points (``firstPt`` and ``secondPt``) for + alignment (instead of X and Y offsets), compute the effective translation offset + *after* having applied any transform (#1831). +- [glyf] When all glyphs have zero contours, compile ``glyf`` table data as a single + null byte in order to pass validation by OTS and Windows (#1829). +- [feaLib] Parsing feature code now ensures that referenced glyph names are part of + the known glyph set, unless a glyph set was not provided. +- [varLib] When filling in the default axis value for a missing location of a source or + instance, correctly map the value forward. +- [varLib] The avar table can now contain mapping output values that are greater than + OR EQUAL to the preceeding value, as the avar specification allows this. +- [varLib] The errors of the module are now ordered hierarchically below VarLibError. + See #1821. + +4.3.0 (released 2020-02-03) +--------------------------- + +- [EBLC/CBLC] Fixed incorrect padding length calculation for Format 3 IndexSubTable + (#1817, #1818). +- [varLib] Fixed error when merging OTL tables and TTFonts were loaded as ``lazy=True`` + (#1808, #1809). +- [varLib] Allow to use master fonts containing ``CFF2`` table when building VF (#1816). +- [ttLib] Make ``recalcBBoxes`` option work also with ``CFF2`` table (#1816). +- [feaLib] Don't reset ``lookupflag`` in lookups defined inside feature blocks. + They will now inherit the current ``lookupflag`` of the feature. This is what + Adobe ``makeotf`` also does in this case (#1815). +- [feaLib] Fixed bug with mixed single/multiple substitutions. If a single substitution + involved a glyph class, we were incorrectly using only the first glyph in the class + (#1814). + +4.2.5 (released 2020-01-29) +--------------------------- + +- [feaLib] Do not fail on duplicate multiple substitutions, only warn (#1811). +- [subset] Optimize SinglePos subtables to Format 1 if all ValueRecords are the same + (#1802). + +4.2.4 (released 2020-01-09) +--------------------------- + +- [unicodedata] Update RTL_SCRIPTS for Unicode 11 and 12. + +4.2.3 (released 2020-01-07) +--------------------------- + +- [otTables] Fixed bug when splitting `MarkBasePos` subtables as offsets overflow. + The mark class values in the split subtable were not being updated, leading to + invalid mark-base attachments (#1797, googlefonts/noto-source#145). +- [feaLib] Only log a warning instead of error when features contain duplicate + substitutions (#1767). +- [glifLib] Strip XML comments when parsing with lxml (#1784, #1785). + +4.2.2 (released 2019-12-12) +--------------------------- + +- [subset] Fixed issue with subsetting FeatureVariations table when the index + of features changes as features get dropped. The feature index need to be + remapped to point to index of the remaining features (#1777, #1782). +- [fontBuilder] Added `addFeatureVariations` method to `FontBuilder` class. This + is a shorthand for calling `featureVars.addFeatureVariations` on the builder's + TTFont object (#1781). +- [glyf] Fixed the flags bug in glyph.drawPoints() like we did for glyph.draw() + (#1771, #1774). + +4.2.1 (released 2019-12-06) +--------------------------- + +- [glyf] Use the ``flagOnCurve`` bit mask in ``glyph.draw()``, so that we ignore + the ``overlap`` flag that may be set when instantiating variable fonts (#1771). + +4.2.0 (released 2019-11-28) +--------------------------- + +- [pens] Added the following pens: + + * ``roundingPen.RoundingPen``: filter pen that rounds coordinates and components' + offsets to integer; + * ``roundingPen.RoundingPointPen``: like the above, but using PointPen protocol. + * ``filterPen.FilterPointPen``: base class for filter point pens; + * ``transformPen.TransformPointPen``: filter point pen to apply affine transform; + * ``recordingPen.RecordingPointPen``: records and replays point-pen commands. + +- [ttGlyphPen] Always round float coordinates and component offsets to integers + (#1763). +- [ufoLib] When converting kerning groups from UFO2 to UFO3, avoid confusing + groups with the same name as one of the glyphs (#1761, #1762, + unified-font-object/ufo-spec#98). + +4.1.0 (released 2019-11-18) +--------------------------- + +- [instancer] Implemented restricting axis ranges (level 3 partial instancing). + You can now pass ``{axis_tag: (min, max)}`` tuples as input to the + ``instantiateVariableFont`` function. Note that changing the default axis + position is not supported yet. The command-line script also accepts axis ranges + in the form of colon-separated float values, e.g. ``wght=400:700`` (#1753, #1537). +- [instancer] Never drop STAT ``DesignAxis`` records, but only prune out-of-range + ``AxisValue`` records. +- [otBase/otTables] Enforce that VarStore.RegionAxisCount == fvar.axisCount, even + when regions list is empty to appease OTS < v8.0 (#1752). +- [designspaceLib] Defined new ``processing`` attribute for ```` element, + with values "first" or "last", plus other editorial changes to DesignSpace + specification. Bumped format version to 4.1 (#1750). +- [varLib] Improved error message when masters' glyph orders do not match (#1758, + #1759). +- [featureVars] Allow to specify custom feature tag in ``addFeatureVariations``; + allow said feature to already exist, in which case we append new lookup indices + to existing features. Implemented ```` attribute ``processing`` according to + DesignSpace specification update in #1750. Depending on this flag, we generate + either an 'rvrn' (always processed first) or a 'rclt' feature (follows lookup order, + therefore last) (#1747, #1625, #1371). +- [ttCollection] Added support for context manager auto-closing via ``with`` statement + like with ``TTFont`` (#1751). +- [unicodedata] Require unicodedata2 >= 12.1.0. +- [py2.py3] Removed yet more PY2 vestiges (#1743). +- [_n_a_m_e] Fixed issue when comparing NameRecords with different string types (#1742). +- [fixedTools] Changed ``fixedToFloat`` to not do any rounding but simply return + ``value / (1 << precisionBits)``. Added ``floatToFixedToStr`` and + ``strToFixedToFloat`` functions to be used when loading from or dumping to XML. + Fixed values (e.g. fvar axes and instance coordinates, avar mappings, etc.) are + are now stored as un-rounded decimal floats upon decompiling (#1740, #737). +- [feaLib] Fixed handling of multiple ``LigatureCaret`` statements for the same glyph. + Only the first rule per glyph is used, additional ones are ignored (#1733). + +4.0.2 (released 2019-09-26) +--------------------------- + +- [voltLib] Added support for ``ALL`` and ``NONE`` in ``PROCESS_MARKS`` (#1732). +- [Silf] Fixed issue in ``Silf`` table compilation and decompilation regarding str vs + bytes in python3 (#1728). +- [merge] Handle duplicate glyph names better: instead of appending font index to + all glyph names, use similar code like we use in ``post`` and ``CFF`` tables (#1729). + +4.0.1 (released 2019-09-11) +--------------------------- + +- [otTables] Support fixing offset overflows in ``MultipleSubst`` lookup subtables + (#1706). +- [subset] Prune empty strikes in ``EBDT`` and ``CBDT`` table data (#1698, #1633). +- [pens] Fixed issue in ``PointToSegmentPen`` when last point of closed contour has + same coordinates as the starting point and was incorrectly dropped (#1720). +- [Graphite] Fixed ``Sill`` table output to pass OTS (#1705). +- [name] Added ``removeNames`` method to ``table__n_a_m_e`` class (#1719). +- [ttLib] Added aliases for renamed entries ``ascender`` and ``descender`` in + ``hhea`` table (#1715). + +4.0.0 (released 2019-08-22) +--------------------------- + +- NOTE: The v4.x version series only supports Python 3.6 or greater. You can keep + using fonttools 3.x if you need support for Python 2. +- [py23] Removed all the python2-only code since it is no longer reachable, thus + unused; only the Python3 symbols were kept, but these are no-op. The module is now + DEPRECATED and will removed in the future. +- [ttLib] Fixed UnboundLocalError for empty loca/glyph tables (#1680). Also, allow + the glyf table to be incomplete when dumping to XML (#1681). +- [varLib.models] Fixed KeyError while sorting masters and there are no on-axis for + a given axis (38a8eb0e). +- [cffLib] Make sure glyph names are unique (#1699). +- [feaLib] Fix feature parser to correctly handle octal numbers (#1700). + +\... see `here `__ for earlier changes diff --git a/.cache/uv/.gitignore b/.cache/uv/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f59ec20aabf5842d237244ece8c81ab184faeac1 --- /dev/null +++ b/.cache/uv/.gitignore @@ -0,0 +1 @@ +* \ No newline at end of file diff --git a/.cache/uv/.lock b/.cache/uv/.lock new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.cache/uv/CACHEDIR.TAG b/.cache/uv/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..bc1ecb967a482524e7736038de0df6e08f9ee452 --- /dev/null +++ b/.cache/uv/CACHEDIR.TAG @@ -0,0 +1 @@ +Signature: 8a477f597d28d172789f06886806bc55 \ No newline at end of file diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/METADATA b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7757c23918738f77859b5cbea21c1bbcfcee9dd2 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/METADATA @@ -0,0 +1,373 @@ +Metadata-Version: 2.4 +Name: huggingface_hub +Version: 1.26.0 +Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub +Home-page: https://github.com/huggingface/huggingface_hub +Author: Hugging Face, Inc. +Author-email: julien@huggingface.co +License: Apache-2.0 +Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.10.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: click<9.0.0,>=8.4.2 +Requires-Dist: filelock>=3.10.0 +Requires-Dist: fsspec>=2023.5.0 +Requires-Dist: hf-xet<2.0.0,>=1.5.1; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64" +Requires-Dist: httpx<1,>=0.23.0 +Requires-Dist: packaging>=20.9 +Requires-Dist: pyyaml>=5.1 +Requires-Dist: tqdm>=4.42.1 +Requires-Dist: typing-extensions>=4.1.0 +Provides-Extra: oauth +Requires-Dist: authlib>=1.3.2; extra == "oauth" +Requires-Dist: fastapi; extra == "oauth" +Requires-Dist: httpx; extra == "oauth" +Requires-Dist: itsdangerous; extra == "oauth" +Provides-Extra: torch +Requires-Dist: torch; extra == "torch" +Requires-Dist: safetensors[torch]; extra == "torch" +Provides-Extra: fastai +Requires-Dist: toml; extra == "fastai" +Requires-Dist: fastai>=2.4; extra == "fastai" +Requires-Dist: fastcore>=1.3.27; extra == "fastai" +Provides-Extra: hf-xet +Requires-Dist: hf-xet<2.0.0,>=1.5.1; extra == "hf-xet" +Provides-Extra: mcp +Requires-Dist: mcp>=1.8.0; extra == "mcp" +Provides-Extra: testing +Requires-Dist: authlib>=1.3.2; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Requires-Dist: httpx; extra == "testing" +Requires-Dist: itsdangerous; extra == "testing" +Requires-Dist: jedi; extra == "testing" +Requires-Dist: Jinja2; extra == "testing" +Requires-Dist: pytest>=8.4.2; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-env; extra == "testing" +Requires-Dist: pytest-xdist; extra == "testing" +Requires-Dist: pytest-vcr; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "testing" +Requires-Dist: pytest-mock; extra == "testing" +Requires-Dist: urllib3<2.0; extra == "testing" +Requires-Dist: soundfile; extra == "testing" +Requires-Dist: Pillow; extra == "testing" +Requires-Dist: numpy; extra == "testing" +Requires-Dist: duckdb; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Provides-Extra: gradio +Requires-Dist: gradio>=5.0.0; extra == "gradio" +Requires-Dist: requests; extra == "gradio" +Provides-Extra: typing +Requires-Dist: typing-extensions>=4.8.0; extra == "typing" +Requires-Dist: types-PyYAML; extra == "typing" +Requires-Dist: types-simplejson; extra == "typing" +Requires-Dist: types-toml; extra == "typing" +Requires-Dist: types-tqdm; extra == "typing" +Requires-Dist: types-urllib3; extra == "typing" +Provides-Extra: quality +Requires-Dist: ruff>=0.9.0; extra == "quality" +Requires-Dist: mypy==1.15.0; extra == "quality" +Requires-Dist: libcst>=1.4.0; extra == "quality" +Requires-Dist: ty; extra == "quality" +Provides-Extra: all +Requires-Dist: authlib>=1.3.2; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: httpx; extra == "all" +Requires-Dist: itsdangerous; extra == "all" +Requires-Dist: jedi; extra == "all" +Requires-Dist: Jinja2; extra == "all" +Requires-Dist: pytest>=8.4.2; extra == "all" +Requires-Dist: pytest-cov; extra == "all" +Requires-Dist: pytest-env; extra == "all" +Requires-Dist: pytest-xdist; extra == "all" +Requires-Dist: pytest-vcr; extra == "all" +Requires-Dist: pytest-asyncio; extra == "all" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "all" +Requires-Dist: pytest-mock; extra == "all" +Requires-Dist: urllib3<2.0; extra == "all" +Requires-Dist: soundfile; extra == "all" +Requires-Dist: Pillow; extra == "all" +Requires-Dist: numpy; extra == "all" +Requires-Dist: duckdb; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: ruff>=0.9.0; extra == "all" +Requires-Dist: mypy==1.15.0; extra == "all" +Requires-Dist: libcst>=1.4.0; extra == "all" +Requires-Dist: ty; extra == "all" +Requires-Dist: typing-extensions>=4.8.0; extra == "all" +Requires-Dist: types-PyYAML; extra == "all" +Requires-Dist: types-simplejson; extra == "all" +Requires-Dist: types-toml; extra == "all" +Requires-Dist: types-tqdm; extra == "all" +Requires-Dist: types-urllib3; extra == "all" +Provides-Extra: dev +Requires-Dist: authlib>=1.3.2; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: httpx; extra == "dev" +Requires-Dist: itsdangerous; extra == "dev" +Requires-Dist: jedi; extra == "dev" +Requires-Dist: Jinja2; extra == "dev" +Requires-Dist: pytest>=8.4.2; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: pytest-env; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: pytest-vcr; extra == "dev" +Requires-Dist: pytest-asyncio; extra == "dev" +Requires-Dist: pytest-rerunfailures>=16.2; extra == "dev" +Requires-Dist: pytest-mock; extra == "dev" +Requires-Dist: urllib3<2.0; extra == "dev" +Requires-Dist: soundfile; extra == "dev" +Requires-Dist: Pillow; extra == "dev" +Requires-Dist: numpy; extra == "dev" +Requires-Dist: duckdb; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: ruff>=0.9.0; extra == "dev" +Requires-Dist: mypy==1.15.0; extra == "dev" +Requires-Dist: libcst>=1.4.0; extra == "dev" +Requires-Dist: ty; extra == "dev" +Requires-Dist: typing-extensions>=4.8.0; extra == "dev" +Requires-Dist: types-PyYAML; extra == "dev" +Requires-Dist: types-simplejson; extra == "dev" +Requires-Dist: types-toml; extra == "dev" +Requires-Dist: types-tqdm; extra == "dev" +Requires-Dist: types-urllib3; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +

+ + + + huggingface_hub library logo + +
+
+

+ +

+ The official CLI and Python client for the Hugging Face Hub. +
+ About + · + Documentation + · + Install + · + CLI Guide + · + Contributing +

+ +

+ Documentation + GitHub release + PyPi version + PyPI - Downloads + Code coverage +

+ +

+

+ English | + Deutsch | + Français | + हिंदी | + 한국어 | + 中文 (简体) | + ಕನ್ನಡ +

+

+ +## Quick start + +Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer: + +```bash +# On macOS and Linux. +curl -LsSf https://hf.co/cli/install.sh | bash +``` + +```powershell +# On Windows. +powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex" +``` + +Log in, then start working with the Hub: + +```bash +# Log in (use --token $HF_TOKEN in non-interactive environments) +hf auth login + +# Find models served by Inference Providers +hf models ls --warm + +# Download a model +hf download Qwen/Qwen3-0.6B + +# Upload files to your own repo +hf upload username/my-cool-model ./model.safetensors + +# Sync a local folder to a storage bucket +hf buckets sync ./checkpoints hf://buckets/username/my-bucket + +# Run a job on Hugging Face infrastructure +hf jobs run python:3.12 python -c "print('Hello from the cloud!')" + +# Discover everything else +hf --help +``` + +The Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). Check out the [CLI guide](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for a tour of the main features. + +## What is `huggingface_hub`? + +The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects, play with the thousands of machine learning apps hosted on the Hub, or create and share your own models, datasets and demos with the community. Everything ships in one package with two interfaces: the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for your terminal and the `huggingface_hub` library for Python — both designed to work well for humans and AI agents. Use them to: + +- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub. +- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub. +- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository). +- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models. +- [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure. +- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces. +- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models. +- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments. +- Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli). + +## Built for humans and AI agents + +The `hf` CLI is designed for people and coding agents alike: the same commands adapt their output when run by an agent. If you use Claude Code, Codex, Cursor, or another coding agent, install the `hf` CLI Skill — a command reference generated from your installed CLI: + +```bash +# for Codex, Cursor, OpenCode, Pi and other agents that load skills from `.agents/skills` +hf skills add +# includes the above + Claude Code +hf skills add --claude +``` + +Learn more in the [Hugging Face CLI for AI agents guide](https://huggingface.co/docs/hub/agents-cli) and the [announcement blog post](https://huggingface.co/blog/hf-cli-for-agents). + +## Use the Python library + +Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI): + +```bash +pip install huggingface_hub +``` + +We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install: + +```bash +uv pip install huggingface_hub +``` + +In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run: + +```bash +pip install "huggingface_hub[mcp]" +``` + +To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation). + +### Download files + +Download a single file + +```py +from huggingface_hub import hf_hub_download + +hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json") +``` + +Or an entire repository + +```py +from huggingface_hub import snapshot_download + +snapshot_download("sentence-transformers/all-MiniLM-L6-v2") +``` + +Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache). + +### Create a repository + +```py +from huggingface_hub import create_repo + +create_repo(repo_id="super-cool-model") +``` + +### Upload files + +Upload a single file + +```py +from huggingface_hub import upload_file + +upload_file( + path_or_fileobj="/home/lysandre/dummy-test/README.md", + path_in_repo="README.md", + repo_id="lysandre/test-model", +) +``` + +Or an entire folder + +```py +from huggingface_hub import upload_folder + +upload_folder( + folder_path="/path/to/local/space", + repo_id="username/my-cool-space", + repo_type="space", +) +``` + +More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload). + +## Integrating with the Hub. + +We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries). + +The advantages are: + +- Free model or dataset hosting for libraries and their users. +- Built-in file versioning, even with very large files, made possible by [Xet](https://huggingface.co/docs/hub/xet/index), the Hub's chunk-deduplicated storage backend. +- In-browser widgets to play with the uploaded models. +- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable. +- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe. +- Usage stats and more features to come. + +If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration. + +## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️ + +Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community. +Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community. +We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize +how to get started to contribute to this repository. diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/RECORD b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3a7f82c2d6459e3b073719f1d4c708e9339bbac5 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/RECORD @@ -0,0 +1,191 @@ +huggingface_hub/__init__.py,sha256=MHnwtoK4eZWretvLQzTgRce55TAwjlkZld6FvUq1TLY,60623 +huggingface_hub/_buckets.py,sha256=XyLbsLzS2fpQz0aAIjKzV-1YbQ4XYZ4-HXQTVq0TXoU,45311 +huggingface_hub/_commit_api.py,sha256=lalqhJKl8_RWVHgAdnzZKG_fy4E7fbyHIev6nDLrj4w,45378 +huggingface_hub/_commit_scheduler.py,sha256=VG3zjb7xb66NrFMq_pB9dWIsoqSPoF6CntovV7vUiWg,14684 +huggingface_hub/_dataset_viewer.py,sha256=LE9k4s0WJ0JNdriJ8L6qV_-xfbUVC1VEh7CBd0jOjLI,5675 +huggingface_hub/_eval_results.py,sha256=Og7p7bCl2HQG6ZWlSDyir-CRTXjNWPu3S3q65cTGffs,8126 +huggingface_hub/_inference_endpoints.py,sha256=TNCEvHfu5M790bQPl4BccRzcii8WS5FlDYGrGqQzdW4,17724 +huggingface_hub/_jobs_api.py,sha256=f7NhziUMH6jWpWClnLPFx4XIZ0xVGAdTGfBxIn2IVy0,23679 +huggingface_hub/_local_folder.py,sha256=KsetQw7pW0ZwFI2RLQPqVq0ZnORogPkBwRYcbRqNd5o,20654 +huggingface_hub/_login.py,sha256=wAMdhqMSSh3GBJDozodmk4IIsAvb9J6LaLY9KnXFoyY,21818 +huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628 +huggingface_hub/_oidc.py,sha256=3kcCLavWQ5FQOwizUPzLaBb1ft2FIJo0bSXL24S3r4U,7098 +huggingface_hub/_revision.py,sha256=NCmIVCR-_HjmxeYiDntcsTU-bLSfJLq8PLvvG8UhZtI,1696 +huggingface_hub/_sandbox.py,sha256=XEXZi5S3rYyw_o3td3rB0xOVdmhpAlnyUykBsAw9KP8,80148 +huggingface_hub/_sandbox_cache.py,sha256=UYpvHOWZj7CRhacYs5Ot-5N1wFcAapiAyniYdoX-jX8,5742 +huggingface_hub/_snapshot_download.py,sha256=fOte9xmpaok0LGbubJZhSRd7t0nn-p00mWMebCx56qc,31029 +huggingface_hub/_space_api.py,sha256=MF3ezhgl0Vpt3RP1wuwZ7VI9_rSyIlIJ5SmDzIwQlcQ,13424 +huggingface_hub/_tensorboard_logger.py,sha256=GA-LhoG4Z-0Zq7w5B9vTIDJbWUkAhiG2d8a-ktlwGDY,8377 +huggingface_hub/_tree_cache.py,sha256=M7CHMKhwY1cuhe9fb3WT1X8jmd9BXa2Sx_HS4TIXFgI,5843 +huggingface_hub/_upload_large_folder.py,sha256=BWA1zyOK9W_3YUerX9YWQa3wAYtHRe_ypgsO79JEkqo,31235 +huggingface_hub/_upload_pipeline.py,sha256=6YaQNtubAEaPyRoRBjPQrmsdSnCExg2KzfBuhjNqI5I,28994 +huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544 +huggingface_hub/_webhooks_server.py,sha256=VXOk3FHkbIc28phxknJfaFy5B_EoKOKihoCKyOaWZQk,15767 +huggingface_hub/community.py,sha256=N5OE5Rbc2BMwpNXCFOPQAwn0otqQunsXdEnSE_0J2Xo,12325 +huggingface_hub/constants.py,sha256=y4TqYE5UuXFrc-ivzpLiQKoKKw6xHY75SBEIgOuuD8g,13174 +huggingface_hub/dataclasses.py,sha256=dkPHOKq1YVlto9TWMkeX8BnErmbZk6tVtqD1S_n6Cw8,25896 +huggingface_hub/errors.py,sha256=MsfOFq6Sxo2bZ8PTPWbQb250v7aqZJO5-mmWSnX_kDk,18695 +huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583 +huggingface_hub/file_download.py,sha256=QT4ICMPp_CbLBVNn-qCYnyuwmA2mjjc546fYppt1m8Y,87740 +huggingface_hub/hf_api.py,sha256=ByjtP6rHRHBeQIgYKc9AjysjA219t8O14tuXfVs-6YQ,672231 +huggingface_hub/hf_file_system.py,sha256=39YZea452YnGVvHZosmL3_QtWaz7VS-4P2Mc-xI7K0E,60503 +huggingface_hub/hub_mixin.py,sha256=ljKAtm3qQsY-ARtxY-PCFx0koFXLI37JytMrzpqfnQo,36912 +huggingface_hub/lfs.py,sha256=8ymYNHRXgvgUUM9w0EAnC-vkSOOq_1EFJEJNoevoeE8,16588 +huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/repocard.py,sha256=7u7hiKjNuPYOwa3XPOPUnYPpuv4buya4WM47kVexklY,35602 +huggingface_hub/repocard_data.py,sha256=f834MUSXGqrVcC02668r3ACrPzKKOAg75y3aB_hXm1U,34308 +huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606 +huggingface_hub/_hot_reload/client.py,sha256=Ax7qT4CUi5wrg3mDzqkAG8ZzDsCwdcIIS1FIXK0SqD8,4269 +huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948 +huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725 +huggingface_hub/cli/__init__.py,sha256=tWu3Is-m2tlJwXhM_vT2mPRgpnt9KhU9qvw5aRsnjU0,664 +huggingface_hub/cli/_city_game.py,sha256=2qkC9dCtPwf4-aqrnbN-vApf0YqIcGGjn2v-etrTfqg,20585 +huggingface_hub/cli/_cli_utils.py,sha256=Q5795puu89Kf4fEvQYPjyJmDnyqFEyEr5SW1xQXQk8I,41313 +huggingface_hub/cli/_completion.py,sha256=BDP6Vob9TLFp6K3lr0XOY98FyD-rm22KrjwsO_YGNbE,3759 +huggingface_hub/cli/_cp.py,sha256=Z-2Z_tBs1e4XBqRO5R9QnabU4qTi9HDlbA52jTBaCkY,10436 +huggingface_hub/cli/_errors.py,sha256=X0rUTO-3eCK5v_MLGEza1BxcuXGccPY-h7ShzmuQc34,5907 +huggingface_hub/cli/_file_listing.py,sha256=h_dTEphSqtvknzqJ_9cIK3Cjlz5M6cycYD3cqUW9Fn0,7986 +huggingface_hub/cli/_framework.py,sha256=HqfAEYGWRSjKABAZi2zVNgryyU9QKW8u-tRXfR_4nQ8,27364 +huggingface_hub/cli/_help_formatter.py,sha256=-vsa3HfHQFkKWms77EGyp9i22t44ETmVt2L-e8qP-KM,1288 +huggingface_hub/cli/_output.py,sha256=OxFrvAcDU1TRDV0AbNh4EI1P6tqifSeVT-yqfF92U_0,14754 +huggingface_hub/cli/_skills.py,sha256=b1dlasxALM5KsDG5R1azcETksQ6ssYYZN-kaz-RdHwg,12134 +huggingface_hub/cli/auth.py,sha256=Ew79M60pTMCnS1ewKVK3fd8ZyfHrNjREOmNWuFXy37M,6056 +huggingface_hub/cli/buckets.py,sha256=J8xMP88fQ6ri3f65Z8XEImI2GNA4KKWloLJJQCBezZw,21062 +huggingface_hub/cli/cache.py,sha256=2T0oTYXsrtcJxhQENSpXnYYNUkagsvvdrf5gbCACBjA,28574 +huggingface_hub/cli/collections.py,sha256=Ed41zJqrvK-AWkHdkeHWm_aJKR_ZeNIovCGvWG04itk,10120 +huggingface_hub/cli/datasets.py,sha256=X1xMJTFhHH5NJtmjTS6NN1g4ffai6Abh_obDEJM5mvo,10497 +huggingface_hub/cli/deprecated_cli.py,sha256=vAK_CR4NE9uzNJ0I59SyBnIln5nlypG4CPoohMoPMVg,1090 +huggingface_hub/cli/discussions.py,sha256=obvvN4mtsFnfMs67YTZaMvHkVaM6A-FYr5n-wGkF_jE,14029 +huggingface_hub/cli/download.py,sha256=o6fMKJoNQMxCm1RQUnX3blihJ17mantxkf0F68rZIxs,9669 +huggingface_hub/cli/extensions.py,sha256=qNM1DmzcQXt8kPWQfISc8Pvyku8BxAs-BOVP6sKRBOM,25572 +huggingface_hub/cli/hf.py,sha256=G2R-Mgo2AX09aRiAb-13eZbO441m9yDTwMCtSUf1iac,5208 +huggingface_hub/cli/inference_endpoints.py,sha256=4pfvPm5PVQizStyXGRBnrev62KvhzSNEL65UEVtRcKw,17418 +huggingface_hub/cli/jobs.py,sha256=EVGuxn2GZqkQolHib98PztJeJ64Opq-MjgIub2WTYb4,52840 +huggingface_hub/cli/lfs.py,sha256=MAccazVPX0n-ySRaPocaQUHP7oBnVrvWZt0RhmNIavs,5936 +huggingface_hub/cli/models.py,sha256=eG7H5yDjCVrdL7W_-wpcl70qXlv8bC-roSEu8AroPws,10148 +huggingface_hub/cli/papers.py,sha256=HvT-8zj2fi14ua6awWpHphlbJ362FEJIwSCBJRQZ_cM,4982 +huggingface_hub/cli/repo_files.py,sha256=sGbD5wND3miF71ThfOBJm4xzPRUpJBeLFdvyj229NAM,2443 +huggingface_hub/cli/repos.py,sha256=QS3xYKvspLhCfO5VvpORrSiF6XhSVFclmBxsacVDP2c,20192 +huggingface_hub/cli/sandbox.py,sha256=rTCZf6WhoDa7UiNhsTU_4Lh5uKqKYOs73xXGAAqJGdA,18379 +huggingface_hub/cli/skills.py,sha256=JQkqD43bfr8IapIVp8rvQpd8NKA0dXSbGJD8g-u51w8,19473 +huggingface_hub/cli/spaces.py,sha256=AU655GGrQmF1s1yO8yO6ml2Z8veE7zsh4UMuR5b13RI,40800 +huggingface_hub/cli/system.py,sha256=NtICLnQ49BHFpm2Cl37IV_h21L6mufxVDfse8Lp38HA,1760 +huggingface_hub/cli/upload.py,sha256=P6sq8Dj81a2wazUgZEqbliRleVAAmJrf8ajFDDzHrBE,11318 +huggingface_hub/cli/upload_large_folder.py,sha256=A-2qxAdLrYd8IogfZS2nDhSR1cpA_aaxhXst638WkAk,4081 +huggingface_hub/cli/webhooks.py,sha256=HdpPp01c6Ece_EuNNJr46rnRki3vF4j4o9-SqYRUHnM,8550 +huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/_client.py,sha256=bN5cj4tBHPD6v603uq4CJjMB_mmmpdVcfXtl9XIOVqc,157679 +huggingface_hub/inference/_common.py,sha256=X-fBP8s6xuNTAuQsGVIethE8dNQaa-mK7Ds54qVVDz8,14999 +huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/_generated/_async_client.py,sha256=imtfJD9m3qxeo_59gox3nnV8Tr8dfQF3dQF0Joy5K4g,160890 +huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869 +huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567 +huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891 +huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439 +huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938 +huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100 +huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910 +huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146 +huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509 +huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680 +huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579 +huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935 +huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585 +huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450 +huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262 +huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740 +huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206 +huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965 +huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845 +huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027 +huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472 +huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269 +huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591 +huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439 +huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813 +huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677 +huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869 +huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693 +huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756 +huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894 +huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742 +huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668 +huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654 +huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697 +huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449 +huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605 +huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=kIA8FfRfOWS3SrZrMTbuVOjE6yxfKfMK75Co5egTWHA,3284 +huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250 +huggingface_hub/inference/_mcp/cli.py,sha256=RKdVQ_VdEgf1AL_QBCvwrsUQ0Ux4R1yerrE46DrV5C0,9642 +huggingface_hub/inference/_mcp/constants.py,sha256=0Ih6ivEvG-pfF8NwErFngzP4Rof4lQoz6ms_eKSAkUI,2463 +huggingface_hub/inference/_mcp/mcp_client.py,sha256=dGp8PhN6aVw4bDnuSySFSiguHUiz-nzhgv89CVdO7pI,17243 +huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929 +huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318 +huggingface_hub/inference/_providers/__init__.py,sha256=TNWnSNPk0RmToBysTc5D1COm0vHEJoGom0Yh7oG2wC4,9838 +huggingface_hub/inference/_providers/_common.py,sha256=9CjlMAtb7W0-GdB1Z-VkV0GKZ0Zm68rIuicdGE-765M,13716 +huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210 +huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226 +huggingface_hub/inference/_providers/deepinfra.py,sha256=4Behgf5V7FTv7CbN6vPEIYwv1z4gztdRRU-KVoOgxVE,4703 +huggingface_hub/inference/_providers/fal_ai.py,sha256=Y2vo5Dl3e8EoehplwNshu8LbDT1e7V4ZyhAMqs0wXws,11705 +huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347 +huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188 +huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315 +huggingface_hub/inference/_providers/hf_inference.py,sha256=d2vdCKSi5CtyQqYndHHvH7SY131-7YHUK3yE7653eIc,9467 +huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470 +huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767 +huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054 +huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314 +huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210 +huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027 +huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174 +huggingface_hub/inference/_providers/together.py,sha256=lrymDZ86n5yoR_Zz7o3AzzSePyo0s7BOBU5digLxb5o,12220 +huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028 +huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739 +huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963 +huggingface_hub/serialization/_base.py,sha256=8vYeDIsqgyOO3I_uii44Bkb50LsMz3kkD4gwAPzhfWU,8436 +huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385 +huggingface_hub/serialization/_torch.py,sha256=BtaCP-G3oYRP6Pj9MhI-ygBsk3JbBPnVDW9huSOgtkk,46897 +huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503 +huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870 +huggingface_hub/utils/__init__.py,sha256=pdVhPWWZkv0QM7kAQw7Bf259RZdPtYBLQqQwLQN-VC4,4045 +huggingface_hub/utils/_auth.py,sha256=Ykuq3yi67jxHmFdyLSc43xvGuCAIR7-h-dajX8IxpGQ,19958 +huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691 +huggingface_hub/utils/_cache_manager.py,sha256=2StxP-nHZ5W9_hi8N9wBFqRNLw5HwO0h9HC7NTAGaFE,34955 +huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121 +huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755 +huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865 +huggingface_hub/utils/_detect_agent.py,sha256=Iw2KW9BUZWfIypn9CtiTmEibHwKK9xx5Ar48z1cMU-Q,7337 +huggingface_hub/utils/_dotenv.py,sha256=NdlEM8OXtzwlwmJCmdc6oGubFObrpgr408y8gnSs7ls,2604 +huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464 +huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124 +huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548 +huggingface_hub/utils/_headers.py,sha256=Q9bu9mvOpm-9rfv-YRlr_Ywy_aMZkmRcN3MbVEcJAJA,8234 +huggingface_hub/utils/_hf_uris.py,sha256=RTHrVKLT5vVU-ca8roXHrKwbN3njowanvxHjx5B4sUg,27558 +huggingface_hub/utils/_http.py,sha256=C_mC63TsaxpmzyYBPHCneXKFLACEytAkBwxRwMNxcB4,46014 +huggingface_hub/utils/_lfs.py,sha256=xMU-ROgNAUpDkzbH6yRZsE-eVYUYTNMGrgVb_QdTv-k,3942 +huggingface_hub/utils/_oauth_device.py,sha256=o7ICmI01yDt1oAFNMUJvN1ThSfaCDpC8AHYSQgcnFGw,7983 +huggingface_hub/utils/_pagination.py,sha256=h-TJjFbX3FqkA1T0tGZ0EhxMvuRSCg-UfL_a-BMs54I,1943 +huggingface_hub/utils/_parsing.py,sha256=DVWuO6s_XMiGfXyc0jyX5hi_yGgBHpF9KLoeQM-VVK0,3586 +huggingface_hub/utils/_paths.py,sha256=kWpUMIK9rmKb2LHgHCkk2DnroDzucrwbj-urCJCgfGw,5962 +huggingface_hub/utils/_runtime.py,sha256=GVJ_Dt6y_48TZWl0ui9yPdW8M7rqGblRGyUqKaXxkCo,13493 +huggingface_hub/utils/_safetensors.py,sha256=qFE7OA-vjU8X0zBBtOeNRzLu147KF-PdFoaxkYfWB4M,4426 +huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542 +huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824 +huggingface_hub/utils/_terminal.py,sha256=whHgs0Co-1LatoCmJE_ojqE_cWP6b5dWPWpU-uSFWUU,8969 +huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542 +huggingface_hub/utils/_validators.py,sha256=tuC1U4yxB-4XKIajZMnKZUSKvZ6qPpydY8LItfa0g40,8419 +huggingface_hub/utils/_verification.py,sha256=ZSilnolSkYmHB3vmBlWuuVr53xz59P5uGnxC3H-Hjc0,5434 +huggingface_hub/utils/_xet.py,sha256=lVCUmCxzmBFYRSkJxFLtfhe7_HJWdLzJdENL-ln5Grc,6556 +huggingface_hub/utils/_xet_progress_reporting.py,sha256=MnNCxB9ieflArNNyz3R4kpkjOdt6mQxi8qp8xqzXQTM,14162 +huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366 +huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008 +huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870 +huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121 +huggingface_hub/utils/tqdm.py,sha256=xXjKGy2y2gMqpKeMUqXcQWc66buW39NwkTr3hlWH6MY,16729 +huggingface_hub-1.26.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +huggingface_hub-1.26.0.dist-info/METADATA,sha256=KcwO-q5qwA5Ebh_FICnvHDP8U6mPa8rdlnih7rnssYc,16314 +huggingface_hub-1.26.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 +huggingface_hub-1.26.0.dist-info/entry_points.txt,sha256=zP7F_bBSdircPQFysHQZ9F3Lcn5_dCSOEZxVlGCsG0w,212 +huggingface_hub-1.26.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16 +huggingface_hub-1.26.0.dist-info/RECORD,, diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/WHEEL b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1d472b6c22838de58d1c3c0dd2c795a5cde9e415 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (83.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/entry_points.txt b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..62018f2f5622f61920179a20b80488f21dbb1686 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/entry_points.txt @@ -0,0 +1,7 @@ +[console_scripts] +hf = huggingface_hub.cli.hf:main +huggingface-cli = huggingface_hub.cli.deprecated_cli:main +tiny-agents = huggingface_hub.inference._mcp.cli:app + +[fsspec.specs] +hf = huggingface_hub.HfFileSystem diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/top_level.txt b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b964ccca3c1b6766042b3fe3b2707ba25372924 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub-1.26.0.dist-info/top_level.txt @@ -0,0 +1 @@ +huggingface_hub diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/errors.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..38f9d339be2e73ce4b26bfbea9dd9165f2d5848c --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/errors.py @@ -0,0 +1,617 @@ +"""Contains all custom errors.""" + +from enum import Enum +from pathlib import Path + +from httpx import HTTPError, Response + + +# CACHE ERRORS + + +class CacheNotFound(Exception): + """Exception thrown when the Huggingface cache is not found.""" + + cache_dir: str | Path + + def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + self.cache_dir = cache_dir + + +class CorruptedCacheException(Exception): + """Exception for any unexpected structure in the Huggingface cache-system.""" + + +class CachedRepoTreeNotFoundError(Exception): + """Raised by [`get_cached_repo_tree`] when no tree listing is cached for the requested revision. + + The tree listing is populated as a side effect of [`snapshot_download`]. + """ + + +# HEADERS ERRORS + + +class LocalTokenNotFoundError(EnvironmentError): + """Raised if local token is required but not found.""" + + +# OIDC ERRORS + + +class OIDCError(Exception): + """Raised when keyless CI/CD auth via OIDC token exchange ("Trusted Publishers") cannot proceed. + + Typically because `HF_OIDC_RESOURCE` is set but no id token is available: not running in a + supported CI provider and `HF_OIDC_ID_TOKEN` is unset. + + See https://huggingface.co/docs/hub/trusted-publishers. + """ + + +# DEVICE CODE OAUTH ERRORS + + +class OAuthErrorCode(str, Enum): + """Known OAuth `error` codes returned by the Hub's token endpoint (RFC 6749 / RFC 8628).""" + + AUTHORIZATION_PENDING = "authorization_pending" + SLOW_DOWN = "slow_down" + EXPIRED_TOKEN = "expired_token" + ACCESS_DENIED = "access_denied" + INVALID_GRANT = "invalid_grant" + + +class DeviceCodeError(Exception): + """Raised when the Device Code OAuth login flow (RFC 8628) or an OAuth token refresh fails. + + Covers failures at any step: requesting the device code, polling for the token, + authorization denied/expired, or unexpected server responses. + + Attributes: + error_code (`str`, *optional*): + The OAuth `error` code returned by the server, if any. Known values are listed in + [`OAuthErrorCode`] but the server may return other codes. + """ + + def __init__(self, message: str, error_code: str | None = None): + super().__init__(message) + self.error_code = error_code + + +# HTTP ERRORS + + +class OfflineModeIsEnabled(ConnectionError): + """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable.""" + + +class HfHubHTTPError(HTTPError, OSError): + """ + HTTPError to inherit from for any custom HTTP Error raised in HF Hub. + + Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is + sent back by the server, it will be added to the error message. + + Added details: + - Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id". + - Server error message from the header "X-Error-Message". + - Server error message if we can found one in the response body. + + Example: + ```py + import httpx + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + """ + + def __init__( + self, + message: str, + *, + response: Response, + server_message: str | None = None, + ): + self.request_id = ( + response.headers.get("x-request-id") + or response.headers.get("X-Amzn-Trace-Id") + or response.headers.get("x-amz-cf-id") + ) + self.server_message = server_message + self.response = response + self.request = response.request + super().__init__(message) + + def append_to_message(self, additional_message: str) -> None: + """Append additional information to the `HfHubHTTPError` initial message.""" + self.args = (self.args[0] + additional_message,) + self.args[1:] + + @classmethod + def _reconstruct_hf_hub_http_error( + cls, message: str, response: Response, server_message: str | None + ) -> "HfHubHTTPError": + return cls(message, response=response, server_message=server_message) + + def __reduce_ex__(self, protocol): + """Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class""" + return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message)) + + +# INFERENCE CLIENT ERRORS + + +class InferenceTimeoutError(HTTPError, TimeoutError): + """Error raised when a model is unavailable or the request times out.""" + + +# INFERENCE ENDPOINT ERRORS + + +class InferenceEndpointError(Exception): + """Generic exception when dealing with Inference Endpoints.""" + + +class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError): + """Exception for timeouts while waiting for Inference Endpoint.""" + + +# SAFETENSORS ERRORS + + +class SafetensorsParsingError(Exception): + """Raised when failing to parse a safetensors file metadata. + + This can be the case if the file is not a safetensors file or does not respect the specification. + """ + + +class NotASafetensorsRepoError(Exception): + """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a + `model.safetensors.index.json` file. + """ + + +# TEXT GENERATION ERRORS + + +class TextGenerationError(HTTPError): + """Generic error raised if text-generation went wrong.""" + + +# Text Generation Inference Errors +class ValidationError(TextGenerationError): + """Server-side validation error.""" + + +class GenerationError(TextGenerationError): + pass + + +class OverloadedError(TextGenerationError): + pass + + +class IncompleteGenerationError(TextGenerationError): + pass + + +class UnknownError(TextGenerationError): + pass + + +# VALIDATION ERRORS + + +class HFValidationError(ValueError): + """Generic exception thrown by `huggingface_hub` validators. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + +class HfUriError(ValueError): + """Raised when an `hf://...` URI is malformed. + + See [`parse_hf_uri`] and the + [HF URIs reference](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_uris) + for the canonical syntax. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + def __init__(self, uri: str, msg: str): + self.uri = uri + self.msg = msg + full_msg = f"Invalid HF URI '{uri}'. {msg}" if uri else f"Invalid HF URI. {msg}" + super().__init__(full_msg) + + +# FILE METADATA ERRORS + + +class DryRunError(OSError): + """Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo).""" + + +class FileMetadataError(OSError): + """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash). + + Inherits from `OSError` for backward compatibility. + """ + + +# BUCKET ERRORS + + +class BucketNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a bucket that does not exist. + + Attributes: + bucket_id (`str` or `None`): + The bucket id (namespace/name) that was not found, if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import bucket_info + >>> bucket_info("") + (...) + huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX) + + Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name. + Please make sure you specified the correct bucket id (namespace/name). + If the bucket is private, make sure you are authenticated and your token has the required permissions. + ``` + """ + + bucket_id: str | None = None + + +# JOB ERRORS + + +class JobNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a Job that does not exist. + + Attributes: + job_id (`str`): + The job id that was not found. + """ + + job_id: str + + +# REPOSITORY ERRORS + + +class RepositoryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with an invalid repository name, or + with a private repo name the user does not have access to. + + Attributes: + repo_id (`str` or `None`): + The repo id that was not found, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP) + + Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E. + Please make sure you specified the correct `repo_id` and `repo_type`. + If the repo is private, make sure you are authenticated and your token has the required permissions. + Invalid username or password. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +class GatedRepoError(RepositoryNotFoundError): + """ + Raised when trying to access a gated repository for which the user is not on the + authorized list. + + Note: derives from `RepositoryNotFoundError` to ensure backward compatibility. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa) + + Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model. + Access to model ardent-figment/gated-model is restricted and you are not in the authorized list. + Visit https://huggingface.co/ardent-figment/gated-model to ask for access. + ``` + """ + + +class DisabledRepoError(HfHubHTTPError): + """ + Raised when trying to access a repository that has been disabled by its author. + + Example: + + ```py + >>> from huggingface_hub import dataset_info + >>> dataset_info("laion/laion-art") + (...) + huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8) + + Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art. + Access to this resource is disabled. + ``` + """ + + +# REVISION ERROR + + +class RevisionNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository but an invalid + revision. + + Attributes: + repo_id (`str` or `None`): + The repo id, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', 'config.json', revision='') + (...) + huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX) + + Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +class RevisionResolutionError(Exception): + """ + Raised by [`HfApi.resolve_revision`] when a revision cannot be resolved to a commit hash: the Hub could not be + reached (offline mode, connection error, timeout, Hub downtime, ...) and no matching entry was found in the + local cache. + """ + + +# ENTRY ERRORS +class EntryNotFoundError(Exception): + """ + Raised when entry not found, either locally or remotely. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.errors.RemoteEntryNotFoundError (...) + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.utils.errors.LocalEntryNotFoundError (...) + ``` + """ + + +class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError): + """ + Raised when trying to access a hf.co URL with a valid repository and revision + but an invalid filename. + + Attributes: + repo_id (`str` or `None`): + The repo id, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x) + + Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError): + """ + Raised when trying to access a file or snapshot that is not on the disk when network is + disabled or unavailable (connection issue). The entry may exist on the Hub. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False. + ``` + """ + + def __init__(self, message: str): + super().__init__(message) + + +class IncompleteSnapshotError(LocalEntryNotFoundError): + """ + Raised by [`snapshot_download`] when the Hub cannot be reached (offline, connection issue, or + `local_files_only=True`) and the cached snapshot is known to be incomplete: some files listed in + the repository's cached tree listing are missing from the local snapshot. + + This is a subclass of [`LocalEntryNotFoundError`] for backward compatibility. + + The `snapshot_path` attribute holds the path to the incomplete local snapshot, so a downstream library can locate + the latest cached files even though they are known to be incomplete. + """ + + def __init__(self, message: str, snapshot_path: str): + super().__init__(message) + self.snapshot_path = snapshot_path + + +# REQUEST ERROR +class BadRequestError(HfHubHTTPError, ValueError): + """ + Raised by `hf_raise_for_status` when the server returns a HTTP 400 error. + + Example: + + ```py + >>> resp = httpx.post("hf.co/api/check", ...) + >>> hf_raise_for_status(resp, endpoint_name="check") + huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX) + ``` + """ + + +# DDUF file format ERROR + + +class DDUFError(Exception): + """Base exception for errors related to the DDUF format.""" + + +class DDUFCorruptedFileError(DDUFError): + """Exception thrown when the DDUF file is corrupted.""" + + +class DDUFExportError(DDUFError): + """Base exception for errors during DDUF export.""" + + +class DDUFInvalidEntryNameError(DDUFExportError): + """Exception thrown when the entry name is invalid.""" + + +# STRICT DATACLASSES ERRORS + + +class StrictDataclassError(Exception): + """Base exception for strict dataclasses.""" + + +class StrictDataclassDefinitionError(StrictDataclassError): + """Exception thrown when a strict dataclass is defined incorrectly.""" + + +class StrictDataclassFieldValidationError(StrictDataclassError): + """Exception thrown when a strict dataclass fails validation for a given field.""" + + def __init__(self, field: str, cause: Exception): + error_message = f"Validation error for field '{field}':" + error_message += f"\n {cause.__class__.__name__}: {cause}" + super().__init__(error_message) + + +class StrictDataclassClassValidationError(StrictDataclassError): + """Exception thrown when a strict dataclass fails validation on a class validator.""" + + def __init__(self, validator: str, cause: Exception): + error_message = f"Class validation error for validator '{validator}':" + error_message += f"\n {cause.__class__.__name__}: {cause}" + super().__init__(error_message) + + +# XET ERRORS + + +class XetDownloadError(Exception): + """Exception thrown when the download from Xet Storage fails.""" + + +# LFS ERRORS + + +class FileDuplicationError(Exception): + """Raised when duplicating files across repos fails.""" + + +# CLI ERRORS + + +class CLIError(Exception): + """CLI error with clean message (no traceback by default).""" + + +class ConfirmationError(CLIError): + """Raised when a confirmation prompt is declined (non-interactive mode).""" + + +class CLIExtensionInstallError(CLIError): + """Error during CLI extension installation.""" + + +# SANDBOX ERRORS + + +class SandboxError(Exception): + """Base exception for sandbox operations (see `huggingface_hub.Sandbox`). + + Attributes: + status_code: The HTTP status returned by the in-sandbox server, if the error + originated from an API response (e.g. `404` for a missing file). `None` otherwise. + """ + + def __init__(self, message: str, *, status_code: int | None = None) -> None: + super().__init__(message) + self.status_code = status_code + + +class SandboxCommandError(SandboxError): + """Raised when a command run in a sandbox exits with a non-zero code. + + Attributes: + cmd: The command that failed. + result: The full `SandboxCommandResult` (exit_code, stdout, stderr, ...). + """ + + def __init__(self, cmd, result) -> None: + self.cmd = cmd + self.result = result + stderr_tail = result.stderr[-1000:] if result.stderr else "" + if result.timed_out: + reason = "timed out" + elif result.signal is not None: + reason = f"was killed by signal {result.signal}" + else: + reason = f"exited with code {result.exit_code}" + super().__init__(f"Command {cmd!r} {reason}. stderr:\n{stderr_tail}") diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/fastai_utils.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/fastai_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2604e7b1e598d3d1c0b9dc8115e5e3c0a3fc3de2 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/fastai_utils.py @@ -0,0 +1,414 @@ +import json +import os +from pathlib import Path +from pickle import DEFAULT_PROTOCOL, PicklingError +from typing import Any + +from packaging import version + +from huggingface_hub import constants, snapshot_download +from huggingface_hub.hf_api import HfApi +from huggingface_hub.utils import ( + SoftTemporaryDirectory, + get_fastai_version, + get_fastcore_version, + get_python_version, +) + +from .utils import logging, validate_hf_hub_args + + +logger = logging.get_logger(__name__) + + +def _check_fastai_fastcore_versions( + fastai_min_version: str = "2.4", + fastcore_min_version: str = "1.3.27", +): + """ + Checks that the installed fastai and fastcore versions are compatible for pickle serialization. + + Args: + fastai_min_version (`str`, *optional*): + The minimum fastai version supported. + fastcore_min_version (`str`, *optional*): + The minimum fastcore version supported. + + > [!TIP] + > Raises the following error: + > + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the fastai or fastcore libraries are not available or are of an invalid version. + """ + + if (get_fastcore_version() or get_fastai_version()) == "N/A": + raise ImportError( + f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are" + f" required. Currently using fastai=={get_fastai_version()} and" + f" fastcore=={get_fastcore_version()}." + ) + + current_fastai_version = version.Version(get_fastai_version()) + current_fastcore_version = version.Version(get_fastcore_version()) + + if current_fastai_version < version.Version(fastai_min_version): + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require a" + f" fastai>={fastai_min_version} version, but you are using fastai version" + f" {get_fastai_version()} which is incompatible. Upgrade with `pip install" + " fastai==2.5.6`." + ) + + if current_fastcore_version < version.Version(fastcore_min_version): + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require a" + f" fastcore>={fastcore_min_version} version, but you are using fastcore" + f" version {get_fastcore_version()} which is incompatible. Upgrade with" + " `pip install fastcore==1.3.27`." + ) + + +def _check_fastai_fastcore_pyproject_versions( + storage_folder: str, + fastai_min_version: str = "2.4", + fastcore_min_version: str = "1.3.27", +): + """ + Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions + that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist + or does not contain versions for fastai and fastcore, then it logs a warning. + + Args: + storage_folder (`str`): + Folder to look for the `pyproject.toml` file. + fastai_min_version (`str`, *optional*): + The minimum fastai version supported. + fastcore_min_version (`str`, *optional*): + The minimum fastcore version supported. + + > [!TIP] + > Raises the following errors: + > + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the `toml` module is not installed. + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore. + """ + + try: + import toml + except ModuleNotFoundError: + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module." + " Install it with `pip install toml`." + ) + + # Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages. + if not os.path.isfile(f"{storage_folder}/pyproject.toml"): + logger.warning( + "There is no `pyproject.toml` in the repository that contains the fastai" + " `Learner`. The `pyproject.toml` would allow us to verify that your fastai" + " and fastcore versions are compatible with those of the model you want to" + " load." + ) + return + pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml") + + if "build-system" not in pyproject_toml.keys(): + logger.warning( + "There is no `build-system` section in the pyproject.toml of the repository" + " that contains the fastai `Learner`. The `build-system` would allow us to" + " verify that your fastai and fastcore versions are compatible with those" + " of the model you want to load." + ) + return + build_system_toml = pyproject_toml["build-system"] + + if "requires" not in build_system_toml.keys(): + logger.warning( + "There is no `requires` section in the pyproject.toml of the repository" + " that contains the fastai `Learner`. The `requires` would allow us to" + " verify that your fastai and fastcore versions are compatible with those" + " of the model you want to load." + ) + return + package_versions = build_system_toml["requires"] + + # Extracts contains fastai and fastcore versions from `pyproject.toml` if available. + # If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest. + fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")] + if len(fastai_packages) == 0: + logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.") + # fastai_version is an empty string if not specified + else: + fastai_version = str(fastai_packages[0]).partition("=")[2] + if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version): + raise ImportError( + "`from_pretrained_fastai` requires" + f" fastai>={fastai_min_version} version but the model to load uses" + f" {fastai_version} which is incompatible." + ) + + fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")] + if len(fastcore_packages) == 0: + logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.") + # fastcore_version is an empty string if not specified + else: + fastcore_version = str(fastcore_packages[0]).partition("=")[2] + if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version): + raise ImportError( + "`from_pretrained_fastai` requires" + f" fastcore>={fastcore_min_version} version, but you are using fastcore" + f" version {fastcore_version} which is incompatible." + ) + + +README_TEMPLATE = """--- +tags: +- fastai +--- + +# Amazing! + +🥳 Congratulations on hosting your fastai model on the Hugging Face Hub! + +# Some next steps +1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))! + +2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)). + +3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)! + +Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card. + + +--- + + +# Model card + +## Model description +More information needed + +## Intended uses & limitations +More information needed + +## Training and evaluation data +More information needed +""" + +PYPROJECT_TEMPLATE = f"""[build-system] +requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"] +build-backend = "setuptools.build_meta:__legacy__" +""" + + +def _create_model_card(repo_dir: Path): + """ + Creates a model card for the repository. + + Args: + repo_dir (`Path`): + Directory where model card is created. + """ + readme_path = repo_dir / "README.md" + + if not readme_path.exists(): + with readme_path.open("w", encoding="utf-8") as f: + f.write(README_TEMPLATE) + + +def _create_model_pyproject(repo_dir: Path): + """ + Creates a `pyproject.toml` for the repository. + + Args: + repo_dir (`Path`): + Directory where `pyproject.toml` is created. + """ + pyproject_path = repo_dir / "pyproject.toml" + + if not pyproject_path.exists(): + with pyproject_path.open("w", encoding="utf-8") as f: + f.write(PYPROJECT_TEMPLATE) + + +def _save_pretrained_fastai( + learner, + save_directory: str | Path, + config: dict[str, Any] | None = None, +): + """ + Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used. + + Args: + learner (`Learner`): + The `fastai.Learner` you'd like to save. + save_directory (`str` or `Path`): + Specific directory in which you want to save the fastai learner. + config (`dict`, *optional*): + Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'. + + > [!TIP] + > Raises the following error: + > + > - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) + > if the config file provided is not a dictionary. + """ + _check_fastai_fastcore_versions() + + os.makedirs(save_directory, exist_ok=True) + + # if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE. + if config is not None: + if not isinstance(config, dict): + raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'") + path = os.path.join(save_directory, constants.CONFIG_NAME) + with open(path, "w") as f: + json.dump(config, f) + + _create_model_card(Path(save_directory)) + _create_model_pyproject(Path(save_directory)) + + # learner.export saves the model in `self.path`. + learner.path = Path(save_directory) + os.makedirs(save_directory, exist_ok=True) + try: + learner.export( + fname="model.pkl", + pickle_protocol=DEFAULT_PROTOCOL, + ) + except PicklingError: + raise PicklingError( + "You are using a lambda function, i.e., an anonymous function. `pickle`" + " cannot pickle function objects and requires that all functions have" + " names. One possible solution is to name the function." + ) + + +@validate_hf_hub_args +def from_pretrained_fastai( + repo_id: str, + revision: str | None = None, +): + """ + Load pretrained fastai model from the Hub or from a local directory. + + Args: + repo_id (`str`): + The location where the pickled fastai.Learner is. It can be either of the two: + - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'. + You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`. + Revision is the specific model version to use. Since we use a git-based system for storing models and other + artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id. + - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml + indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`. + revision (`str`, *optional*): + Revision at which the repo's files are downloaded. See documentation of `snapshot_download`. + + Returns: + The `fastai.Learner` model in the `repo_id` repo. + """ + _check_fastai_fastcore_versions() + + # Load the `repo_id` repo. + # `snapshot_download` returns the folder where the model was stored. + # `cache_dir` will be the default '/root/.cache/huggingface/hub' + if not os.path.isdir(repo_id): + storage_folder = snapshot_download( + repo_id=repo_id, + revision=revision, + library_name="fastai", + library_version=get_fastai_version(), + ) + else: + storage_folder = repo_id + + _check_fastai_fastcore_pyproject_versions(storage_folder) + + from fastai.learner import load_learner # type: ignore + + return load_learner(os.path.join(storage_folder, "model.pkl")) + + +@validate_hf_hub_args +def push_to_hub_fastai( + learner, + *, + repo_id: str, + commit_message: str = "Push FastAI model using huggingface_hub.", + private: bool | None = None, + token: str | None = None, + config: dict | None = None, + branch: str | None = None, + create_pr: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + api_endpoint: str | None = None, +): + """ + Upload learner checkpoint files to the Hub. + + Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use + `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more + details. + + Args: + learner (`Learner`): + The `fastai.Learner' you'd like to push to the Hub. + repo_id (`str`): + The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de'). + commit_message (`str`, *optional*): + Message to commit while pushing. Will default to :obj:`"add model"`. + private (`bool`, *optional*): + Whether or not the repository created should be private. + If `None` (default), will default to been public except if the organization's default is private. + token (`str`, *optional*): + The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt. + config (`dict`, *optional*): + Configuration object to be saved alongside the model weights. + branch (`str`, *optional*): + The git branch on which to push the model. This defaults to + the default branch as specified in your repository, which + defaults to `"main"`. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `branch` with that commit. + Defaults to `False`. + api_endpoint (`str`, *optional*): + The API endpoint to use when pushing the model to the hub. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are pushed. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not pushed. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo. + + Returns: + The url of the commit of your model in the given repository. + + > [!TIP] + > Raises the following error: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if the user is not log on to the Hugging Face Hub. + """ + _check_fastai_fastcore_versions() + api = HfApi(endpoint=api_endpoint) + repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id + + # Push the files to the repo in a single commit + with SoftTemporaryDirectory() as tmp: + saved_path = Path(tmp) / repo_id + _save_pretrained_fastai(learner, saved_path, config=config) + return api.upload_folder( + repo_id=repo_id, + token=token, + folder_path=saved_path, + commit_message=commit_message, + revision=branch, + create_pr=create_pr, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + delete_patterns=delete_patterns, + ) diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hf_api.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hf_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce5948a1587849156d1300961dadae837c0dbd3 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hf_api.py @@ -0,0 +1,15227 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import inspect +import itertools +import json +import re +import struct +import time +import warnings +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator +from concurrent.futures import Future, ThreadPoolExecutor +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +from functools import wraps +from itertools import islice +from pathlib import Path +from secrets import token_hex +from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, overload +from urllib.parse import quote + +import httpcore +import httpx +from tqdm.auto import tqdm as base_tqdm + +from . import constants +from ._buckets import ( + BucketFile, + BucketFileMetadata, + BucketFolder, + BucketInfo, + BucketUrl, + SyncPlan, + _BucketAddFile, + _BucketCopyFile, + _BucketDeleteFile, + _parse_bucket_uri, + sync_bucket_internal, +) +from ._commit_api import ( + DUPLICATE_LFS_BATCH_SIZE, + CommitOperation, + CommitOperationAdd, + CommitOperationCopy, + CommitOperationDelete, + _CopySource, + _fetch_files_to_copy, + _fetch_upload_modes, + _send_commit, + _upload_files, + _warn_on_overwriting_operations, +) +from ._dataset_viewer import DatasetParquetEntry +from ._eval_results import EvalResultEntry, parse_eval_result_entries +from ._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetric, InferenceEndpointType +from ._jobs_api import ( + TERMINAL_JOB_STAGES, + JobHardware, + JobHardwareInfo, + JobInfo, + JobSpec, + JobStage, + ScheduledJobInfo, + _create_job_spec, + _default_job_name_from_image, + _default_job_name_from_script, + _derive_job_volume_name, +) +from ._revision import ResolvedRevision +from ._space_api import ( + INTERMEDIATE_SPACE_STAGES, + SpaceHardware, + SpaceRuntime, + SpaceSearchResult, + SpaceSecret, + SpaceStorage, + SpaceTemplate, + SpaceVariable, + Volume, +) +from ._upload_large_folder import upload_large_folder_internal +from ._upload_pipeline import pipelined_upload +from .community import ( + Discussion, + DiscussionComment, + DiscussionStatusChange, + DiscussionTitleChange, + DiscussionWithDetails, + deserialize_event, +) +from .errors import ( + BadRequestError, + EntryNotFoundError, + FileDuplicationError, + GatedRepoError, + HfHubHTTPError, + HfUriError, + LocalTokenNotFoundError, + OfflineModeIsEnabled, + RemoteEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, + RevisionResolutionError, +) +from .file_download import ( + REGEX_COMMIT_HASH, + DryRunFileInfo, + HfFileMetadata, + _cache_commit_hash_for_specific_revision, + get_hf_file_metadata, + hf_hub_url, + repo_folder_name, +) +from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData +from .utils import ( + DEFAULT_IGNORE_PATTERNS, + HfUri, + NotASafetensorsRepoError, + SafetensorsFileMetadata, + SafetensorsParsingError, + SafetensorsRepoMetadata, + TensorInfo, + are_progress_bars_disabled, + build_hf_headers, + chunk_iterable, + experimental, + filter_repo_objects, + fix_hf_endpoint_in_url, + get_session, + get_token, + hf_raise_for_status, + hf_thread_map, + http_backoff, + logging, + paginate, + parse_datetime, + parse_hf_uri, + parse_xet_file_data_from_response, + silent_tqdm, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm +from .utils._auth import _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab +from .utils._deprecation import _deprecate_arguments, _deprecate_method +from .utils._http import _httpx_follow_relative_redirects_with_backoff +from .utils._runtime import is_xet_available +from .utils._typing import CallableT +from .utils._verification import collect_local_files, resolve_local_root, verify_maps +from .utils.endpoint_helpers import _is_emission_within_threshold + + +if TYPE_CHECKING: + from .inference._providers import PROVIDER_T + from .utils._verification import FolderVerification + from .utils._xet_progress_reporting import XetUploadProgressReporter + +R = TypeVar("R") # Return type +CollectionItemType_T = Literal["model", "dataset", "space", "paper", "collection", "bucket"] +CollectionSort_T = Literal["lastModified", "trending", "upvotes"] +RepoVisibility_T = Literal["public", "private", "protected"] + +ExpandModelProperty_T = Literal[ + "author", + "baseModels", + "cardData", + "childrenModelCount", + "config", + "createdAt", + "disabled", + "downloads", + "downloadsAllTime", + "evalResults", + "gated", + "gguf", + "inference", + "inferenceProviderMapping", + "lastModified", + "library_name", + "likes", + "mask_token", + "model-index", + "pipeline_tag", + "private", + "resourceGroup", + "safetensors", + "sha", + "siblings", + "spaces", + "tags", + "transformersInfo", + "trendingScore", + "usedStorage", + "widgetData", +] + +ExpandDatasetProperty_T = Literal[ + "author", + "cardData", + "citation", + "createdAt", + "description", + "disabled", + "downloads", + "downloadsAllTime", + "gated", + "lastModified", + "likes", + "mainSize", + "paperswithcode_id", + "private", + "resourceGroup", + "sha", + "siblings", + "tags", + "trendingScore", + "usedStorage", +] + +ExpandSpaceProperty_T = Literal[ + "author", + "cardData", + "createdAt", + "datasets", + "disabled", + "lastModified", + "likes", + "models", + "private", + "resourceGroup", + "runtime", + "sdk", + "sha", + "siblings", + "subdomain", + "tags", + "trendingScore", + "usedStorage", +] + +ModelSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"] +DatasetSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"] +SpaceSort_T = Literal["created_at", "last_modified", "likes", "trending_score"] +DailyPapersSort_T = Literal["publishedAt", "trending"] + +REPO_REGIONS = Literal["us", "eu"] + +USERNAME_PLACEHOLDER = "hf_user" +_REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$") +_REGEX_HTTP_PROTOCOL = re.compile(r"https?://") + +_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = ( + "\nNote: Creating a commit assumes that the repo already exists on the" + " Huggingface Hub. Please use `create_repo` if it's not the case." +) +_AUTH_CHECK_NO_REPO_ERROR_MESSAGE = ( + "\nNote: The repository either does not exist or you do not have access rights." + " Please check the repository ID and your access permissions." + " If this is a private repository, ensure that your token is correct." +) +_BUCKET_PATHS_INFO_BATCH_SIZE = 1000 +_BUCKET_BATCH_ADD_CHUNK_SIZE = 1000 +_BUCKET_BATCH_DELETE_CHUNK_SIZE = 1000 + +# Regex used to match special revisions with "/" in them (see #1710) +SPECIAL_REFS_REVISION_REGEX = re.compile( + r""" + (^refs\/convert\/\w+) # `refs/convert/parquet` revisions + | + (^refs\/pr\/\d+) # PR revisions + """, + re.VERBOSE, +) + +logger = logging.get_logger(__name__) + + +def _resolve_repo_visibility( + *, + private: bool | None, + visibility: RepoVisibility_T | None, + repo_type: str | None, +) -> RepoVisibility_T | None: + if private is not None and visibility is not None: + raise ValueError("Received both `private` and `visibility` arguments. Please provide only one of them.") + + if visibility is None: + if private is None: + return None + return "private" if private else "public" + + if visibility == "protected" and repo_type != constants.REPO_TYPE_SPACE: + raise ValueError("Only Spaces can be 'protected'. Please set visibility to 'public' or 'private'.") + return visibility + + +def repo_type_and_id_from_hf_id(hf_id: str, hub_url: str | None = None) -> tuple[str | None, str | None, str]: + """ + Returns the repo type and ID from a huggingface.co URL linking to a + repository + + > [!WARNING] + > Deprecated: prefer [`parse_hf_uri`], which parses both `hf://` URIs and Hugging Face web URLs into a structured [`HfUri`]. + > See https://huggingface.co/docs/huggingface_hub/package_reference/hf_uris for more details. + + Args: + hf_id (`str`): + An URL or ID of a repository on the HF hub. Accepted values are: + + - https://huggingface.co/// + - https://huggingface.co// + - hf://// + - hf:/// + - // + - / + - + hub_url (`str`, *optional*): + The URL of the HuggingFace Hub, defaults to https://huggingface.co + + Returns: + A tuple with three items: repo_type (`str` or `None`), namespace (`str` or + `None`) and repo_id (`str`). + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If URL cannot be parsed. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `repo_type` is unknown. + """ + input_hf_id = hf_id + + # Get the hub_url (with or without protocol) + full_hub_url = hub_url if hub_url is not None else constants.ENDPOINT + hub_url_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", full_hub_url) + + # Check if hf_id is a URL containing the hub_url (check both with and without protocol) + hf_id_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", hf_id) + is_hf_url = hub_url_without_protocol in hf_id_without_protocol and "@" not in hf_id + + HFFS_PREFIX = "hf://" + if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists + hf_id = hf_id[len(HFFS_PREFIX) :] + + # If it's a URL, strip the endpoint prefix to get the path + if is_hf_url: + # Remove protocol if present + hf_id_normalized = _REGEX_HTTP_PROTOCOL.sub("", hf_id) + + # Remove the hub_url prefix to get the relative path + if hf_id_normalized.startswith(hub_url_without_protocol): + # Strip the hub URL and any leading slashes + hf_id = hf_id_normalized[len(hub_url_without_protocol) :].lstrip("/") + + url_segments = hf_id.split("/") + is_hf_id = len(url_segments) <= 3 + + namespace: str | None + if is_hf_url: + # For URLs, we need to extract repo_type, namespace, repo_id + # Expected format after stripping endpoint: [repo_type]/namespace/repo_id or namespace/repo_id + + if len(url_segments) >= 3: + # Check if first segment is a repo type + if url_segments[0] in constants.REPO_TYPES_MAPPING: + repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]] + namespace = url_segments[1] + repo_id = url_segments[2] + elif url_segments[0] == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = url_segments[1] + repo_id = url_segments[2] + else: + # First segment is namespace + namespace = url_segments[0] + repo_id = url_segments[1] + repo_type = None + elif len(url_segments) == 2: + namespace = url_segments[0] + repo_id = url_segments[1] + + # Check if namespace is actually a repo type mapping + if namespace in constants.REPO_TYPES_MAPPING: + # Mean canonical dataset or model + repo_type = constants.REPO_TYPES_MAPPING[namespace] + namespace = None + elif namespace == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = None + else: + repo_type = None + else: + # Single segment + repo_id = url_segments[0] + namespace = None + repo_type = None + elif is_hf_id: + if len(url_segments) == 3: + # Passed // or // + repo_type, namespace, repo_id = url_segments[-3:] + elif len(url_segments) == 2: + if url_segments[0] in constants.REPO_TYPES_MAPPING: + # Passed '' or 'datasets/' for a canonical model or dataset + repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]] + namespace = None + repo_id = hf_id.split("/")[-1] + elif url_segments[0] == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = None + repo_id = hf_id.split("/")[-1] + else: + # Passed / or / + namespace, repo_id = hf_id.split("/")[-2:] + repo_type = None + else: + # Passed + repo_id = url_segments[0] + namespace, repo_type = None, None + else: + raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}") + + # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`) + if repo_type in constants.REPO_TYPES_MAPPING: + repo_type = constants.REPO_TYPES_MAPPING[repo_type] # type: ignore + if repo_type == "": + repo_type = None + if repo_type not in constants.REPO_TYPES_WITH_KERNEL and repo_type != "bucket": + raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')") + + return repo_type, namespace, repo_id + + +@dataclass +class LastCommitInfo(dict): + oid: str + title: str + date: datetime + + def __post_init__(self): # hack to make LastCommitInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobLfsInfo(dict): + size: int + sha256: str + pointer_size: int + + def __post_init__(self): # hack to make BlobLfsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobSecurityInfo(dict): + safe: bool # duplicate information with "status" field, keeping it for backward compatibility + status: str + av_scan: dict | None + pickle_import_scan: dict | None + + def __post_init__(self): # hack to make BlogSecurityInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class TransformersInfo(dict): + auto_model: str + custom_class: str | None = None + # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72 + pipeline_tag: str | None = None + processor: str | None = None + + def __post_init__(self): # hack to make TransformersInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class SafeTensorsInfo(dict): + parameters: dict[str, int] + total: int + + def __post_init__(self): # hack to make SafeTensorsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class CommitInfo(str): + """Data structure containing information about a newly created commit. + + Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`], + [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific + to `str` is deprecated. + + Attributes: + commit_url (`str`): + Url where to find the commit. + + commit_message (`str`): + The summary (first line) of the commit that has been created. + + commit_description (`str`): + Description of the commit that has been created. Can be empty. + + oid (`str`): + Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`. + + pr_url (`str`, *optional*): + Url to the PR that has been created, if any. Populated when `create_pr=True` + is passed. + + pr_revision (`str`, *optional*): + Revision of the PR that has been created, if any. Populated when + `create_pr=True` is passed. Example: `"refs/pr/1"`. + + pr_num (`int`, *optional*): + Number of the PR discussion that has been created, if any. Populated when + `create_pr=True` is passed. Can be passed as `discussion_num` in + [`get_discussion_details`]. Example: `1`. + + repo_url (`RepoUrl`): + Repo URL of the commit containing info like repo_id, repo_type, etc. + """ + + commit_url: str + commit_message: str + commit_description: str + oid: str + _endpoint: str | None = field(default=None, repr=False) + pr_url: str | None = None + + # Computed from `commit_url` in `__post_init__` + repo_url: RepoUrl = field(init=False) + + # Computed from `pr_url` in `__post_init__` + pr_revision: str | None = field(init=False) + pr_num: int | None = field(init=False) + + def __new__(cls, *args, commit_url: str, **kwargs): + return str.__new__(cls, commit_url) + + def __post_init__(self): + """Populate pr-related fields after initialization. + + See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing. + """ + # Repo info + self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0], endpoint=self._endpoint) + + # PR info + if self.pr_url is not None: + self.pr_revision = _parse_revision_from_pr_url(self.pr_url) + self.pr_num = int(self.pr_revision.split("/")[-1]) + else: + self.pr_revision = None + self.pr_num = None + + +@dataclass +class AccessRequest: + """Data structure containing information about a user access request. + + Attributes: + username (`str`): + Username of the user who requested access. + fullname (`str`): + Fullname of the user who requested access. + email (`Optional[str]`): + Email of the user who requested access. + Can only be `None` in the /accepted list if the user was granted access manually. + timestamp (`datetime`): + Timestamp of the request. + status (`Literal["pending", "accepted", "rejected"]`): + Status of the request. Can be one of `["pending", "accepted", "rejected"]`. + fields (`dict[str, Any]`, *optional*): + Additional fields filled by the user in the gate form. + """ + + username: str + fullname: str + email: str | None + timestamp: datetime + status: Literal["pending", "accepted", "rejected"] + + # Additional fields filled by the user in the gate form + fields: dict[str, Any] | None = None + + +@dataclass +class WebhookWatchedItem: + """Data structure containing information about the items watched by a webhook. + + Attributes: + type (`Literal["dataset", "model", "org", "space", "user"]`): + Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`. + name (`str`): + Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name. + """ + + type: Literal["dataset", "model", "org", "space", "user"] + name: str + + +@dataclass +class WebhookInfo: + """Data structure containing information about a webhook. + + One of `url` or `job` is specified, but not both. + + Attributes: + id (`str`): + ID of the webhook. + url (`str`, *optional*): + URL of the webhook. + job (`JobSpec`, *optional*): + Specifications of the Job to trigger. + watched (`list[WebhookWatchedItem]`): + List of items watched by the webhook, see [`WebhookWatchedItem`]. + domains (`list[WEBHOOK_DOMAIN_T]`): + List of domains the webhook is watching. Can be one of `["repo", "discussions"]`. + secret (`str`, *optional*): + Secret of the webhook. + disabled (`bool`): + Whether the webhook is disabled or not. + """ + + id: str + url: str | None + job: JobSpec | None + watched: list[WebhookWatchedItem] + domains: list[constants.WEBHOOK_DOMAIN_T] + secret: str | None + disabled: bool + + +class RepoUrl(str): + """Subclass of `str` describing a repo URL on the Hub. + + `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward + compatibility. At initialization, the URL is parsed to populate properties: + - endpoint (`str`) + - namespace (`str`) + - repo_name (`str`) + - repo_id (`str`) + - repo_type (`Literal["model", "dataset", "space"]`) + - url (`str`) + + Args: + url (`Any`): + String value of the repo url. + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + + Example: + ```py + >>> RepoUrl('https://huggingface.co/openai-community/gpt2') + RepoUrl('https://huggingface.co/openai-community/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='openai-community/gpt2') + + >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co') + RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset') + + >>> RepoUrl('hf://datasets/my-user/my-dataset') + RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset') + + >>> HfApi.create_repo("dummy_model") + RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model') + ``` + + Raises: + [`~errors.HfUriError`]: + If the URL cannot be parsed (e.g. canonical single-segment repo, or unknown `repo_type`). + """ + + def __new__(cls, url: Any, endpoint: str | None = None): + url = fix_hf_endpoint_in_url(url, endpoint=endpoint) + return super().__new__(cls, url) + + def __init__(self, url: Any, endpoint: str | None = None) -> None: + super().__init__() + self.endpoint = endpoint or constants.ENDPOINT + + # Parse with the shared 'parse_hf_uri' parser, which handles 'hf://' URIs as well as Hugging + # Face web URLs (including ones on this custom 'endpoint'). If that fails, the input is a bare + # '/' id, which we reparse as an 'hf://' URI. + raw = str(self) + try: + parsed = parse_hf_uri(raw, endpoint=self.endpoint) + except HfUriError: + if "://" in raw: + raise # it was a URL: the original error is authoritative, don't retry as a bare id + parsed = parse_hf_uri(f"{constants.HF_PROTOCOL}{raw}") + + # Populate fields ('parsed.id' is always '/'). + self.namespace, self.repo_name = parsed.id.split("/") + self.repo_id = parsed.id + self.repo_type = parsed.type + self.url = str(self) # just in case it's needed + + def __repr__(self) -> str: + return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')" + + +def _resolve_copy_target_path( + src_file_path: str, + src_root_path: str | None, + is_single_file: bool, + destination_path: str, + destination_is_directory: bool, + destination_exists_as_directory: bool, + merge_contents: bool, +) -> str: + basename = src_file_path.rsplit("/", 1)[-1] + if is_single_file: + if destination_path == "": + return basename + if destination_is_directory: + return f"{destination_path.rstrip('/')}/{basename}" + return destination_path + + if src_root_path is None: + rel_path = src_file_path + elif src_file_path.startswith(src_root_path + "/"): + rel_path = src_file_path[len(src_root_path) + 1 :] + elif src_file_path == src_root_path: + rel_path = src_file_path.rsplit("/", 1)[-1] + else: + raise ValueError(f"Unexpected source path while copying folder: '{src_file_path}'.") + + if rel_path == "": + raise ValueError("Cannot copy an empty relative path.") + + # Rsync-style trailing slash on source means "copy contents of" — skip nesting. + # Without trailing slash, match `cp -r` behavior: nest source folder inside + # existing destination directory. Non-existing destination always uses rename semantics. + if destination_exists_as_directory and src_root_path is not None and not merge_contents: + src_dir_basename = src_root_path.rsplit("/", 1)[-1] + rel_path = f"{src_dir_basename}/{rel_path}" + + if destination_path == "": + return rel_path + return f"{destination_path.rstrip('/')}/{rel_path}" + + +@dataclass +class RepoSibling: + """ + Contains basic information about a repo file inside a repo on the Hub. + + > [!TIP] + > All attributes of this class are optional except `rfilename`. This is because only the file names are returned when + > listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more + > information like file size, blob id or lfs details, you must request them specifically from one repo at a time + > (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to + > retrieve these. + + Attributes: + rfilename (str): + file name, relative to the repo root. + size (`int`, *optional*): + The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set + to `True`. It's `None` otherwise. + blob_id (`str`, *optional*): + The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to + `True`. It's `None` otherwise. + lfs (`BlobLfsInfo`, *optional*): + The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to + `True` and the file is stored with Git LFS. It's `None` otherwise. + """ + + rfilename: str + size: int | None = None + blob_id: str | None = None + lfs: BlobLfsInfo | None = None + + +@dataclass +class RepoFile: + """ + Contains information about a file on the Hub. + + Attributes: + path (str): + file path relative to the repo root. + size (`int`): + The file's size, in bytes. + blob_id (`str`): + The file's git OID. + lfs (`BlobLfsInfo`, *optional*): + The file's LFS metadata. + xet_hash (`str`, *optional*): + The file's Xet hash. + last_commit (`LastCommitInfo`, *optional*): + The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + security (`BlobSecurityInfo`, *optional*): + The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + size: int + blob_id: str + lfs: BlobLfsInfo | None = None + xet_hash: str | None = None + last_commit: LastCommitInfo | None = None + security: BlobSecurityInfo | None = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.size = kwargs.pop("size") + self.blob_id = kwargs.pop("oid") + lfs = kwargs.pop("lfs", None) + if lfs is not None: + lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"]) + self.lfs = lfs + self.xet_hash = kwargs.pop("xetHash", None) + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + security = kwargs.pop("securityFileStatus", None) + if security is not None: + safe = security["status"] == "safe" + security = BlobSecurityInfo( + safe=safe, + status=security["status"], + av_scan=security["avScan"], + pickle_import_scan=security["pickleImportScan"], + ) + self.security = security + + # backwards compatibility + self.rfilename = self.path + self.lastCommit = self.last_commit + + +@dataclass +class RepoFolder: + """ + Contains information about a folder on the Hub. + + Attributes: + path (str): + folder path relative to the repo root. + tree_id (`str`): + The folder's git OID. + last_commit (`LastCommitInfo`, *optional*): + The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + tree_id: str + last_commit: LastCommitInfo | None = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.tree_id = kwargs.pop("oid") + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + + +@dataclass +class InferenceProviderMapping: + provider: PROVIDER_T # Provider name + hf_model_id: str # ID of the model on the Hugging Face Hub + provider_id: str # ID of the model on the provider's side + status: Literal["error", "live", "staging"] + task: str + + adapter: str | None = None + adapter_weights_path: str | None = None + type: Literal["single-model", "tag-filter"] | None = None + + def __init__(self, **kwargs): + self.provider = kwargs.pop("provider") + self.hf_model_id = kwargs.pop("hf_model_id") + self.provider_id = kwargs.pop("providerId") + self.status = kwargs.pop("status") + self.task = kwargs.pop("task") + + self.adapter = kwargs.pop("adapter", None) + self.adapter_weights_path = kwargs.pop("adapterWeightsPath", None) + self.type = kwargs.pop("type", None) + self.__dict__.update(**kwargs) + + +@dataclass +class ModelInfo: + """ + Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing models + > using [`list_models`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of model. + author (`str`, *optional*): + Author of the model. + base_models (`list[str]`, *optional*): + List of base models this model is derived from. + card_data (`ModelCardData`, *optional*): + Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object. + children_model_count (`int`, *optional*): + Number of children models derived from this model. + config (`dict`, *optional*): + Model configuration. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + disabled (`bool`, *optional*): + Is the repo disabled. + downloads (`int`): + Number of downloads of the model over the last 30 days. + downloads_all_time (`int`): + Cumulated number of downloads of the model since its creation. + eval_results (`list[EvalResultEntry]`, *optional*): + Model's evaluation results. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + gguf (`dict`, *optional*): + GGUF information of the model. + inference (`Literal["warm"]`, *optional*): + Status of the model on Inference Providers. Warm if the model is served by at least one provider. + inference_provider_mapping (`list[InferenceProviderMapping]`, *optional*): + A list of [`InferenceProviderMapping`] ordered after the user's provider order. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + library_name (`str`, *optional*): + Library associated with the model. + likes (`int`): + Number of likes of the model. + mask_token (`str`, *optional*): + Mask token used by the model. + model_index (`dict`, *optional*): + Model index for evaluation. + pipeline_tag (`str`, *optional*): + Pipeline tag associated with the model. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the model. + safetensors (`SafeTensorsInfo`, *optional*): + Model's safetensors information. + security_repo_status (`dict`, *optional*): + Model's security scan status. + sha (`str`, *optional*): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model. + spaces (`list[str]`, *optional*): + List of spaces using the model. + tags (`list[str]`): + List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub + (e.g. supported libraries, model's arXiv). + transformers_info (`TransformersInfo`, *optional*): + Transformers-specific info (auto class, processor, etc.) associated with the model. + trending_score (`int`, *optional*): + Trending score of the model. + used_storage (`int`, *optional*): + Size in bytes of the model on the Hub. + widget_data (`Any`, *optional*): + Widget data associated with the model. + """ + + id: str + author: str | None + base_models: list[str] | None + card_data: ModelCardData | None + children_model_count: int | None + config: dict | None + created_at: datetime | None + disabled: bool | None + downloads: int | None + downloads_all_time: int | None + eval_results: list[EvalResultEntry] | None + gated: Literal["auto", "manual", False] | None + gguf: dict | None + inference: Literal["warm"] | None + inference_provider_mapping: list[InferenceProviderMapping] | None + last_modified: datetime | None + library_name: str | None + likes: int | None + mask_token: str | None + model_index: dict | None + pipeline_tag: str | None + private: bool | None + resource_group: dict | None + safetensors: SafeTensorsInfo | None + security_repo_status: dict | None + sha: str | None + siblings: list[RepoSibling] | None + spaces: list[str] | None + tags: list[str] | None + transformers_info: TransformersInfo | None + trending_score: int | None + used_storage: int | None + widget_data: Any | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads", None) + self.downloads_all_time = kwargs.pop("downloadsAllTime", None) + self.likes = kwargs.pop("likes", None) + self.library_name = kwargs.pop("library_name", None) + self.gguf = kwargs.pop("gguf", None) + + self.inference = kwargs.pop("inference", None) + + # little hack to simplify Inference Providers logic and make it backward and forward compatible + # right now, API returns a dict on model_info and a list on list_models. Let's harmonize to list. + mapping = kwargs.pop("inferenceProviderMapping", None) + if isinstance(mapping, list): + self.inference_provider_mapping = [ + InferenceProviderMapping(**{**value, "hf_model_id": self.id}) for value in mapping + ] + elif isinstance(mapping, dict): + self.inference_provider_mapping = [ + InferenceProviderMapping(**{**value, "hf_model_id": self.id, "provider": provider}) + for provider, value in mapping.items() + ] + elif mapping is None: + self.inference_provider_mapping = None + else: + raise ValueError( + f"Unexpected type for `inferenceProviderMapping`. Expecting `dict` or `list`. Got {mapping}." + ) + + self.tags = kwargs.pop("tags", None) + self.pipeline_tag = kwargs.pop("pipeline_tag", None) + self.mask_token = kwargs.pop("mask_token", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + + self.widget_data = kwargs.pop("widgetData", None) + self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None) + self.config = kwargs.pop("config", None) + transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None) + self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + self.spaces = kwargs.pop("spaces", None) + safetensors = kwargs.pop("safetensors", None) + self.safetensors = ( + SafeTensorsInfo( + parameters=safetensors["parameters"], + total=safetensors["total"], + ) + if safetensors + else None + ) + self.security_repo_status = kwargs.pop("securityRepoStatus", None) + eval_results = kwargs.pop("evalResults", None) + self.eval_results = parse_eval_result_entries(eval_results) if eval_results else None + self.base_models = kwargs.pop("baseModels", None) + self.children_model_count = kwargs.pop("childrenModelCount", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.transformersInfo = self.transformers_info + self.__dict__.update(**kwargs) + + +@dataclass +class DatasetInfo: + """ + Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets + > using [`list_datasets`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of dataset. + author (`str`): + Author of the dataset. + card_data (`DatasetCardData`, *optional*): + Dataset Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object. + citation (`str`, *optional*): + Citation information for the dataset. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + description (`str`, *optional*): + Description of the dataset. + disabled (`bool`, *optional*): + Is the repo disabled. + downloads (`int`): + Number of downloads of the dataset over the last 30 days. + downloads_all_time (`int`): + Cumulated number of downloads of the dataset since its creation. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`): + Number of likes of the dataset. + main_size (`int`, *optional*): + Size in bytes of the main branch of the dataset. + paperswithcode_id (`str`, *optional*): + Papers with code ID of the dataset. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the dataset. + sha (`str`): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset. + tags (`list[str]`): + List of tags of the dataset. + trending_score (`int`, *optional*): + Trending score of the dataset. + used_storage (`int`, *optional*): + Size in bytes of the dataset on the Hub. + """ + + id: str + author: str | None + card_data: DatasetCardData | None + citation: str | None + created_at: datetime | None + description: str | None + disabled: bool | None + downloads: int | None + downloads_all_time: int | None + gated: Literal["auto", "manual", False] | None + last_modified: datetime | None + likes: int | None + main_size: int | None + paperswithcode_id: str | None + private: bool | None + resource_group: dict | None + sha: str | None + siblings: list[RepoSibling] | None + tags: list[str] | None + trending_score: int | None + used_storage: int | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads", None) + self.downloads_all_time = kwargs.pop("downloadsAllTime", None) + self.likes = kwargs.pop("likes", None) + self.main_size = kwargs.pop("mainSize", None) + self.paperswithcode_id = kwargs.pop("paperswithcode_id", None) + self.tags = kwargs.pop("tags", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + self.citation = kwargs.pop("citation", None) + self.description = kwargs.pop("description", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class SpaceInfo: + """ + Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces + > using [`list_spaces`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of the Space. + author (`str`, *optional*): + Author of the Space. + card_data (`SpaceCardData`, *optional*): + Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + datasets (`list[str]`, *optional*): + List of datasets used by the Space. + disabled (`bool`, *optional*): + Is the Space disabled. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + host (`str`, *optional*): + Host URL of the Space. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`): + Number of likes of the Space. + models (`list[str]`, *optional*): + List of models used by the Space. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the Space. + runtime (`SpaceRuntime`, *optional*): + Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object. + sdk (`str`, *optional*): + SDK used by the Space. + sha (`str`, *optional*): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space. + subdomain (`str`, *optional*): + Subdomain of the Space. + tags (`list[str]`): + List of tags of the Space. + trending_score (`int`, *optional*): + Trending score of the Space. + used_storage (`int`, *optional*): + Size in bytes of the Space on the Hub. + """ + + id: str + author: str | None + card_data: SpaceCardData | None + created_at: datetime | None + datasets: list[str] | None + disabled: bool | None + gated: Literal["auto", "manual", False] | None + host: str | None + last_modified: datetime | None + likes: int | None + models: list[str] | None + private: bool | None + resource_group: dict | None + runtime: SpaceRuntime | None + sdk: str | None + sha: str | None + siblings: list[RepoSibling] | None + subdomain: str | None + tags: list[str] | None + trending_score: int | None + used_storage: int | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.host = kwargs.pop("host", None) + self.subdomain = kwargs.pop("subdomain", None) + self.likes = kwargs.pop("likes", None) + self.sdk = kwargs.pop("sdk", None) + self.tags = kwargs.pop("tags", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + runtime = kwargs.pop("runtime", None) + self.runtime = SpaceRuntime(runtime) if runtime else None + self.models = kwargs.pop("models", None) + self.datasets = kwargs.pop("datasets", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class KernelInfo: + """ + Contains information about a kernel repo on the Hub. This object is returned by [`kernel_info`]. + + Attributes: + id (`str`): + ID of the kernel repo. + author (`str`, *optional*): + Author of the kernel repo. + downloads (`int`, *optional*): + Number of downloads of the kernel repo over the last 30 days. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. If so, whether there is manual or automatic approval. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`, *optional*): + Number of likes of the kernel repo. + private (`bool`, *optional*): + Is the repo private. + sha (`str`, *optional*): + Repo SHA at this particular revision. + """ + + id: str + author: str | None + downloads: int | None + gated: Literal["auto", "manual", False] | None + last_modified: datetime | None + likes: int | None + private: bool | None + sha: str | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.downloads = kwargs.pop("downloads", None) + self.gated = kwargs.pop("gated", None) + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.likes = kwargs.pop("likes", None) + self.private = kwargs.pop("private", None) + self.sha = kwargs.pop("sha", None) + + # future compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class CollectionItem: + """ + Contains information about an item of a Collection (model, dataset, Space, paper, collection or bucket). + + Attributes: + item_object_id (`str`): + Unique ID of the item in the collection. + item_id (`str`): + ID of the underlying object on the Hub. Can be either a repo_id, a paper id, a collection slug + or a bucket id. + e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`. + item_type (`str`): + Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"` + or `"bucket"`. + position (`int`): + Position of the item in the collection. + note (`str`, *optional*): + Note associated with the item, as plain text. + """ + + item_object_id: str # id in database + item_id: str # repo_id or paper id + item_type: str + position: int + note: str | None = None + + def __init__( + self, + _id: str, + id: str, + type: CollectionItemType_T, + position: int, + note: dict | None = None, + **kwargs, + ) -> None: + self.item_object_id: str = _id # id in database + self.item_id: str = id # repo_id or paper id + # if the item is a collection, override item_id with the slug + slug = kwargs.get("slug") + if slug is not None: + self.item_id = slug # collection slug + self.item_type: CollectionItemType_T = type + self.position: int = position + note_text = note.get("text") if note is not None else None + self.note = note_text if isinstance(note_text, str) else None + + +@dataclass +class Collection: + """ + Contains information about a Collection on the Hub. + + Attributes: + slug (`str`): + Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection. E.g. `"Recent models"`. + owner (`str`): + Owner of the collection. E.g. `"TheBloke"`. + items (`list[CollectionItem]`): + List of items in the collection. + last_updated (`datetime`): + Date of the last update of the collection. + position (`int`): + Position of the collection in the list of collections of the owner. + private (`bool`): + Whether the collection is private or not. + theme (`str`): + Theme of the collection. E.g. `"green"`. + upvotes (`int`): + Number of upvotes of the collection. + description (`str`, *optional*): + Description of the collection, as plain text. + url (`str`): + (property) URL of the collection on the Hub. + """ + + slug: str + title: str + owner: str + items: list[CollectionItem] + last_updated: datetime + position: int + private: bool + theme: str + upvotes: int + description: str | None = None + + def __init__(self, **kwargs) -> None: + self.slug = kwargs.pop("slug") + self.title = kwargs.pop("title") + self.owner = kwargs.pop("owner") + self.items = [CollectionItem(**item) for item in kwargs.pop("items")] + self.last_updated = parse_datetime(kwargs.pop("lastUpdated")) + self.position = kwargs.pop("position") + self.private = kwargs.pop("private") + self.theme = kwargs.pop("theme") + self.upvotes = kwargs.pop("upvotes") + self.description = kwargs.pop("description", None) + endpoint = kwargs.pop("endpoint", None) + if endpoint is None: + endpoint = constants.ENDPOINT + self._url = f"{endpoint}/collections/{self.slug}" + + @property + def url(self) -> str: + """Returns the URL of the collection on the Hub.""" + return self._url + + +@dataclass +class GitRefInfo: + """ + Contains information about a git reference for a repo on the Hub. + + Attributes: + name (`str`): + Name of the reference (e.g. tag name or branch name). + ref (`str`): + Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`). + target_commit (`str`): + OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + """ + + name: str + ref: str + target_commit: str + + +@dataclass +class GitRefs: + """ + Contains information about all git references for a repo on the Hub. + + Object is returned by [`list_repo_refs`]. + + Attributes: + branches (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about branches on the repo. + converts (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about "convert" refs on the repo. + Converts are refs used (internally) to push preprocessed data in Dataset repos. + tags (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about tags on the repo. + pull_requests (`list[GitRefInfo]`, *optional*): + A list of [`GitRefInfo`] containing information about pull requests on the repo. + Only returned if `include_prs=True` is set. + """ + + branches: list[GitRefInfo] + converts: list[GitRefInfo] + tags: list[GitRefInfo] + pull_requests: list[GitRefInfo] | None = None + + +@dataclass +class GitCommitInfo: + """ + Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details. + + Attributes: + commit_id (`str`): + OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + authors (`list[str]`): + List of authors of the commit. + created_at (`datetime`): + Datetime when the commit was created. + title (`str`): + Title of the commit. This is a free-text value entered by the authors. + message (`str`): + Description of the commit. This is a free-text value entered by the authors. + formatted_title (`str`): + Title of the commit formatted as HTML. Only returned if `formatted=True` is set. + formatted_message (`str`): + Description of the commit formatted as HTML. Only returned if `formatted=True` is set. + """ + + commit_id: str + + authors: list[str] + created_at: datetime + title: str + message: str + + formatted_title: str | None + formatted_message: str | None + + +@dataclass +class UserLikes: + """ + Contains information about a user likes on the Hub. + + Attributes: + user (`str`): + Name of the user for which we fetched the likes. + total (`int`): + Total number of likes. + datasets (`list[str]`): + List of datasets liked by the user (as repo_ids). + kernels (`list[str]`): + List of kernels liked by the user (as repo_ids). + models (`list[str]`): + List of models liked by the user (as repo_ids). + spaces (`list[str]`): + List of spaces liked by the user (as repo_ids). + """ + + # Metadata + user: str + total: int + + # User likes + datasets: list[str] + kernels: list[str] + models: list[str] + spaces: list[str] + + +@dataclass +class RepoStorageInfo: + """ + Contains storage information about a repository on the Hub. + + Returned by [`list_user_repos`]. + + Attributes: + id (`str`): + ID of the repo (e.g. `username/repo-name`). + type (`str`): + Type of the repo (`model`, `dataset`, `space`, or `bucket`). + updated_at (`datetime`): + Last update time of the repo. + visibility (`str`): + Visibility of the repo (`public` or `private`). + storage (`int`): + Storage used by the repo in bytes. + storage_percent (`float`): + Percentage of the namespace's total storage used by this repo. + """ + + id: str + type: str + updated_at: datetime + visibility: str + storage: int + storage_percent: float + + def __init__(self, **kwargs: Any) -> None: + self.id = kwargs["id"] + self.type = kwargs["type"] + self.updated_at = parse_datetime(kwargs["updatedAt"]) + self.visibility = kwargs["visibility"] + self.storage = kwargs["storage"] + self.storage_percent = kwargs.get("storagePercent") or 0 + + +@dataclass +class Organization: + """ + Contains information about an organization on the Hub. + + Attributes: + avatar_url (`str`): + URL of the organization's avatar. + name (`str`): + Name of the organization on the Hub (unique). + fullname (`str`): + Organization's full name. + details (`str`, *optional*): + Organization's description. + is_verified (`bool`, *optional*): + Whether the organization is verified. + is_following (`bool`, *optional*): + Whether the authenticated user follows this organization. + num_users (`int`, *optional*): + Number of members in the organization. + num_models (`int`, *optional*): + Number of models owned by the organization. + num_spaces (`int`, *optional*): + Number of Spaces owned by the organization. + num_datasets (`int`, *optional*): + Number of datasets owned by the organization. + num_followers (`int`, *optional*): + Number of followers of the organization. + num_papers (`int`, *optional*): + Number of papers authored by the organization. + plan (`str`, *optional*): + The organization's plan (e.g., "enterprise", "team"). + """ + + avatar_url: str + name: str + fullname: str + details: str | None = None + is_verified: bool | None = None + is_following: bool | None = None + num_users: int | None = None + num_models: int | None = None + num_spaces: int | None = None + num_datasets: int | None = None + num_followers: int | None = None + num_papers: int | None = None + plan: str | None = None + + def __init__(self, **kwargs) -> None: + self.avatar_url = kwargs.pop("avatarUrl", "") + self.name = kwargs.pop("name", "") + self.fullname = kwargs.pop("fullname", "") + self.details = kwargs.pop("details", None) + self.is_verified = kwargs.pop("isVerified", None) + self.is_following = kwargs.pop("isFollowing", None) + self.num_users = kwargs.pop("numUsers", None) + self.num_models = kwargs.pop("numModels", None) + self.num_spaces = kwargs.pop("numSpaces", None) + self.num_datasets = kwargs.pop("numDatasets", None) + self.num_followers = kwargs.pop("numFollowers", None) + self.num_papers = kwargs.pop("numPapers", None) + self.plan = kwargs.pop("plan", None) + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class User: + """ + Contains information about a user on the Hub. + + Attributes: + username (`str`): + Name of the user on the Hub (unique). + fullname (`str`): + User's full name. + avatar_url (`str`): + URL of the user's avatar. + details (`str`, *optional*): + User's details. + is_following (`bool`, *optional*): + Whether the authenticated user is following this user. + is_pro (`bool`, *optional*): + Whether the user is a pro user. + num_models (`int`, *optional*): + Number of models created by the user. + num_datasets (`int`, *optional*): + Number of datasets created by the user. + num_spaces (`int`, *optional*): + Number of spaces created by the user. + num_discussions (`int`, *optional*): + Number of discussions initiated by the user. + num_papers (`int`, *optional*): + Number of papers authored by the user. + num_upvotes (`int`, *optional*): + Number of upvotes received by the user. + num_likes (`int`, *optional*): + Number of likes given by the user. + num_following (`int`, *optional*): + Number of users this user is following. + num_followers (`int`, *optional*): + Number of users following this user. + orgs (list of [`Organization`]): + List of organizations the user is part of. + """ + + # Metadata + username: str + fullname: str + avatar_url: str + details: str | None = None + is_following: bool | None = None + is_pro: bool | None = None + num_models: int | None = None + num_datasets: int | None = None + num_spaces: int | None = None + num_discussions: int | None = None + num_papers: int | None = None + num_upvotes: int | None = None + num_likes: int | None = None + num_following: int | None = None + num_followers: int | None = None + orgs: list[Organization] = field(default_factory=list) + + def __init__(self, **kwargs) -> None: + self.username = kwargs.pop("user", "") + self.fullname = kwargs.pop("fullname", "") + self.avatar_url = kwargs.pop("avatarUrl", "") + self.is_following = kwargs.pop("isFollowing", None) + self.is_pro = kwargs.pop("isPro", None) + self.details = kwargs.pop("details", None) + self.num_models = kwargs.pop("numModels", None) + self.num_datasets = kwargs.pop("numDatasets", None) + self.num_spaces = kwargs.pop("numSpaces", None) + self.num_discussions = kwargs.pop("numDiscussions", None) + self.num_papers = kwargs.pop("numPapers", None) + self.num_upvotes = kwargs.pop("numUpvotes", None) + self.num_likes = kwargs.pop("numLikes", None) + self.num_following = kwargs.pop("numFollowing", None) + self.num_followers = kwargs.pop("numFollowers", None) + self.user_type = kwargs.pop("type", None) + self.orgs = [Organization(**org) for org in kwargs.pop("orgs", [])] + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class PaperAuthor: + """ + Contains information about a paper author on the Hub. + + Attributes: + name (`str`): + Name of the author. + user (`User`, *optional*): + Information about the author as a [`User`] object. + status (`str`, *optional*): + Status of the author on the Hub. + status_last_changed_at (`datetime`, *optional*): + Date when the status of the author changed. + hidden (`bool`, *optional*): + Whether the author is hidden on the Hub. + """ + + name: str + user: User | None + status: str | None + status_last_changed_at: datetime | None + hidden: bool | None + + def __init__(self, **kwargs) -> None: + self.name = kwargs.pop("name", "") + user = kwargs.pop("user", None) + self.user = User(**user) if user else None + self.status = kwargs.pop("status", None) + status_last_changed_at = kwargs.pop("statusLastChangedAt", None) + self.status_last_changed_at = parse_datetime(status_last_changed_at) if status_last_changed_at else None + self.hidden = kwargs.pop("hidden", None) + + self.__dict__.update(**kwargs) + + +@dataclass +class PaperInfo: + """ + Contains information about a paper on the Hub. + + Attributes: + id (`str`): + arXiv paper ID. + authors (`list[PaperAuthor]`, *optional*): + Authors of the paper. + published_at (`datetime`, *optional*): + Date paper published. + title (`str`, *optional*): + Title of the paper. + summary (`str`, *optional*): + Summary of the paper. + upvotes (`int`, *optional*): + Number of upvotes for the paper on the Hub. + discussion_id (`str`, *optional*): + Discussion ID for the paper on the Hub. + source (`str`, *optional*): + Source of the paper. + comments (`int`, *optional*): + Number of comments for the paper on the Hub. + submitted_at (`datetime`, *optional*): + Date paper appeared in daily papers on the Hub. + submitted_by (`User`, *optional*): + Information about who submitted the daily paper. + ai_summary (`str`, *optional*): + AI summary of the paper. + ai_keywords (`list[str]`, *optional*): + AI keywords of the paper. + organization (`Organization`, *optional*): + Information about the organization associated with the paper. + project_page (`str`, *optional*): + URL of the project page for the paper. + github_repo (`str`, *optional*): + URL of the GitHub repository for the paper. + github_stars (`int`, *optional*): + Number of stars of the GitHub repository for the paper. + linked_models (`list[ModelInfo]`, *optional*): + Models linked to the paper. Only returned by [`paper_info`]. + num_total_models (`int`, *optional*): + Total number of models linked to the paper. Only returned by [`paper_info`]. + linked_datasets (`list[DatasetInfo]`, *optional*): + Datasets linked to the paper. Only returned by [`paper_info`]. + num_total_datasets (`int`, *optional*): + Total number of datasets linked to the paper. Only returned by [`paper_info`]. + linked_spaces (`list[SpaceInfo]`, *optional*): + Spaces linked to the paper. Only returned by [`paper_info`]. + """ + + id: str + authors: list[PaperAuthor] | None + published_at: datetime | None + title: str | None + summary: str | None + upvotes: int | None + discussion_id: str | None + source: str | None + comments: int | None + submitted_at: datetime | None + submitted_by: User | None + ai_summary: str | None + ai_keywords: list[str] | None + organization: Organization | None + project_page: str | None + github_repo: str | None + github_stars: int | None + linked_models: list[ModelInfo] | None + num_total_models: int | None + linked_datasets: list[DatasetInfo] | None + num_total_datasets: int | None + linked_spaces: list[SpaceInfo] | None + + def __init__(self, **kwargs) -> None: + paper = kwargs.pop("paper", {}) + self.id = kwargs.pop("id", None) or paper.pop("id", None) + authors = paper.pop("authors", None) or kwargs.pop("authors", None) + self.authors = [PaperAuthor(**author) for author in authors] if authors else None + published_at = paper.pop("publishedAt", None) or kwargs.pop("publishedAt", None) + self.published_at = parse_datetime(published_at) if published_at else None + self.title = kwargs.pop("title", None) + self.source = kwargs.pop("source", None) + self.summary = paper.pop("summary", None) or kwargs.pop("summary", None) + self.upvotes = paper.pop("upvotes", None) or kwargs.pop("upvotes", None) + self.discussion_id = paper.pop("discussionId", None) or kwargs.pop("discussionId", None) + self.comments = kwargs.pop("numComments", 0) + submitted_at = kwargs.pop("publishedAt", None) or kwargs.pop("submittedOnDailyAt", None) + self.submitted_at = parse_datetime(submitted_at) if submitted_at else None + submitted_by = kwargs.pop("submittedBy", None) or kwargs.pop("submittedOnDailyBy", None) + self.submitted_by = User(**submitted_by) if submitted_by else None + self.ai_summary = kwargs.pop("ai_summary", None) + self.ai_keywords = kwargs.pop("ai_keywords", None) + organization = kwargs.pop("organization", None) + self.organization = Organization(**organization) if organization else None + self.project_page = kwargs.pop("projectPage", None) + self.github_repo = kwargs.pop("githubRepo", None) + self.github_stars = kwargs.pop("githubStars", None) + linked_models = kwargs.pop("linkedModels", None) + self.linked_models = [ModelInfo(**m) for m in linked_models] if linked_models is not None else None + self.num_total_models = kwargs.pop("numTotalModels", None) + linked_datasets = kwargs.pop("linkedDatasets", None) + self.linked_datasets = [DatasetInfo(**d) for d in linked_datasets] if linked_datasets is not None else None + self.num_total_datasets = kwargs.pop("numTotalDatasets", None) + linked_spaces = kwargs.pop("linkedSpaces", None) + self.linked_spaces = [SpaceInfo(**s) for s in linked_spaces] if linked_spaces is not None else None + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class LFSFileInfo: + """ + Contains information about a file stored as LFS on a repo on the Hub. + + Used in the context of listing and permanently deleting LFS files from a repo to free-up space. + See [`list_lfs_files`] and [`permanently_delete_lfs_files`] for more details. + + Git LFS files are tracked using SHA-256 object IDs, rather than file paths, to optimize performance + This approach is necessary because a single object can be referenced by multiple paths across different commits, + making it impractical to search and resolve these connections. Check out [our documentation](https://huggingface.co/docs/hub/storage-limits#advanced-track-lfs-file-references) + to learn how to know which filename(s) is(are) associated with each SHA. + + Attributes: + file_oid (`str`): + SHA-256 object ID of the file. This is the identifier to pass when permanently deleting the file. + filename (`str`): + Possible filename for the LFS object. See the note above for more information. + oid (`str`): + OID of the LFS object. + pushed_at (`datetime`): + Date the LFS object was pushed to the repo. + ref (`str`, *optional*): + Ref where the LFS object has been pushed (if any). + size (`int`): + Size of the LFS object. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + + file_oid: str + filename: str + oid: str + pushed_at: datetime + ref: str | None + size: int + + def __init__(self, **kwargs) -> None: + self.file_oid = kwargs.pop("fileOid") + self.filename = kwargs.pop("filename") + self.oid = kwargs.pop("oid") + self.pushed_at = parse_datetime(kwargs.pop("pushedAt")) + self.ref = kwargs.pop("ref", None) + self.size = kwargs.pop("size") + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class DatasetLeaderboardEntry: + """Contains information about a single entry in a dataset leaderboard on the Hub. + + A leaderboard ranks models based on their evaluation scores on a given benchmark dataset. + This object is returned by [`get_dataset_leaderboard`]. To get evaluation results for a + specific model across benchmarks, see [`ModelInfo.eval_results`] (via [`model_info`] with + `expand=["evalResults"]`) and [`EvalResultEntry`]. + + Attributes: + rank (`int`): + Rank of the model on the leaderboard (1-indexed). + model_id (`str`): + ID of the model (e.g. `"meta-llama/Llama-3-8b"`). + value (`float`): + Evaluation score value. + filename (`str`): + Name of the result file containing the evaluation data. + verified (`bool`): + Whether the result has been verified. + source (`dict[str, Any]`, *optional*): + Information about the source of the evaluation result. Contains keys like + `"url"`, `"name"`, and `"isExternal"`. Not all entries have a source. + author (`User` or `Organization`): + The model author, parsed based on the `"type"` field in the API response. + pull_request (`int`, *optional*): + Pull request number associated with the leaderboard entry, if any. + notes (`str`, *optional*): + Notes associated with the leaderboard entry, if any. + """ + + rank: int + model_id: str + value: float + filename: str + verified: bool + source: dict[str, Any] | None + author: User | Organization + pull_request: int | None = None + notes: str | None = None + + def __init__(self, **kwargs) -> None: + self.rank = kwargs.pop("rank") + self.model_id = kwargs.pop("modelId") + self.value = kwargs.pop("value") + self.filename = kwargs.pop("filename") + self.verified = kwargs.pop("verified") + self.source = kwargs.pop("source", None) + author_data = dict(kwargs.pop("author")) + author_type = author_data.get("type") + if author_type == "org": + self.author = Organization(**author_data) + else: + author_data["user"] = author_data.pop("name", "") + self.author = User(**author_data) + self.pull_request = kwargs.pop("pullRequest", None) + self.notes = kwargs.pop("notes", None) + + # forward compatibility + self.__dict__.update(**kwargs) + + +def future_compatible(fn: CallableT) -> CallableT: + """Wrap a method of `HfApi` to handle `run_as_future=True`. + + A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a + `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result. + """ + sig = inspect.signature(fn) + args_params = list(sig.parameters)[1:] # remove "self" from list + + @wraps(fn) + def _inner(self, *args, **kwargs): + # Get `run_as_future` value if provided (default to False) + if "run_as_future" in kwargs: + run_as_future = kwargs["run_as_future"] + kwargs["run_as_future"] = False # avoid recursion error + else: + run_as_future = False + for param, value in zip(args_params, args): + if param == "run_as_future": + run_as_future = value + break + + # Call the function in a thread if `run_as_future=True` + if run_as_future: + return self.run_as_future(fn, self, *args, **kwargs) + + # Otherwise, call the function normally + return fn(self, *args, **kwargs) + + _inner.is_future_compatible = True # type: ignore + return _inner # type: ignore + + +def _get_safetensors_metadata_size(size_bytes: bytes, filename: str, context_msg: str) -> int: + """ + Parse and validate safetensors metadata size from the first 8 bytes. + + This is a shared helper function used by both remote and local safetensors parsing. + + Args: + size_bytes: First 8 bytes of the safetensors file. + filename: Filename for error messages. + context_msg: Additional context for error messages. + + Returns: + The metadata size as an integer. + + Raises: + SafetensorsParsingError: If size_bytes is too short or metadata size exceeds limit. + """ + if len(size_bytes) < 8: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is too small to be a valid " + "safetensors file." + ) + + metadata_size = struct.unpack(" constants.SAFETENSORS_MAX_HEADER_LENGTH: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): safetensors header is too big. " + f"Maximum supported size is {constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})." + ) + + return metadata_size + + +def _parse_safetensors_header(metadata_as_bytes: bytes, filename: str, context_msg: str) -> SafetensorsFileMetadata: + """ + Parse safetensors metadata from raw header bytes. + + This is a shared helper function used by both remote and local safetensors parsing. + + Args: + metadata_as_bytes: Raw bytes of the JSON metadata header (without the 8-byte size prefix). + filename: Filename for error messages. + context_msg: Additional context for error messages (e.g., repo info or local path). + + Returns: + SafetensorsFileMetadata object. + + Raises: + SafetensorsParsingError: If the header cannot be parsed. + """ + # Parse json header + try: + metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore")) + except json.JSONDecodeError as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): header is not json-encoded string. " + "Please make sure this is a correctly formatted safetensors file." + ) from e + + try: + return SafetensorsFileMetadata( + metadata=metadata_as_dict.get("__metadata__", {}), + tensors={ + key: TensorInfo( + dtype=tensor["dtype"], + shape=tensor["shape"], + data_offsets=tuple(tensor["data_offsets"]), # type: ignore + ) + for key, tensor in metadata_as_dict.items() + if key != "__metadata__" + }, + ) + except (KeyError, IndexError) as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): header format not recognized. " + "Please make sure this is a correctly formatted safetensors file." + ) from e + + +class HfApi: + """ + Client to interact with the Hugging Face Hub via HTTP. + + The client is initialized with some high-level settings used in all requests + made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi` + client is preferred but not mandatory as all of its public methods are exposed + directly at the root of `huggingface_hub`. + + Args: + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to + the user-agent header. Example: `"transformers"`. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added + to the user-agent header. Example: `"4.24.0"`. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will + be completed with information about the installed packages. + headers (`dict`, *optional*): + Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`. + Headers passed here are taking precedence over the default headers. + """ + + def __init__( + self, + endpoint: str | None = None, + token: str | bool | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + headers: dict[str, str] | None = None, + ) -> None: + self.endpoint = endpoint if endpoint is not None else constants.ENDPOINT + self.token = token + self.library_name = library_name + self.library_version = library_version + self.user_agent = user_agent + self.headers = headers + self._thread_pool: ThreadPoolExecutor | None = None + + # /whoami-v2 is the only endpoint for which we may want to cache results + self._whoami_cache: dict[str, dict] = {} + + def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]: + """ + Run a method in the background and return a Future instance. + + The main goal is to run methods without blocking the main thread (e.g. to push data during a training). + Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts + by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor). + + Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool` + argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them + but less verbose. + + Args: + fn (`Callable`): + The method to run in the background. + *args, **kwargs: + Arguments with which the method will be called. + + Return: + `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to + get the result of the task. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> future = api.run_as_future(api.whoami) # instant + >>> future.done() + False + >>> future.result() # wait until complete and return result + (...) + >>> future.done() + True + ``` + """ + if self._thread_pool is None: + self._thread_pool = ThreadPoolExecutor(max_workers=1) + self._thread_pool + return self._thread_pool.submit(fn, *args, **kwargs) + + @validate_hf_hub_args + def whoami(self, token: bool | str | None = None, *, cache: bool = False) -> dict: + """ + Call HF API to know "whoami". + + If passing `cache=True`, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call + `whoami` multiple times as this endpoint is heavily rate-limited for security reasons. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + cache (`bool`, *optional*): + Whether to cache the result of the `whoami` call for subsequent calls. + If an error occurs during the first call, it won't be cached. + Defaults to `False`. + """ + # Get the effective token using the helper function get_token + token = self.token if token is None else token + if token is False: + raise ValueError("Cannot use `token=False` with `whoami` method as it requires authentication.") + if token is True or token is None: + token = get_token() + if token is None: + raise LocalTokenNotFoundError( + "Token is required to call the /whoami-v2 endpoint, but no token found. You must provide a token or be logged in to " + "Hugging Face with `hf auth login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens." + ) + + if cache and (cached_token := self._whoami_cache.get(token)): + return cached_token + + # Call Hub + output = self._inner_whoami(token=token) + + # Cache result and return + if cache: + self._whoami_cache[token] = output + return output + + def _inner_whoami(self, token: str) -> dict: + r = get_session().get( + f"{self.endpoint}/api/whoami-v2", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as e: + if e.response.status_code == 401: + error_message = "Invalid user token." + # Check which token is the effective one and generate the error message accordingly + if token == _get_token_from_google_colab(): + error_message += " The token from Google Colab vault is invalid. Please update it from the UI." + elif token == _get_token_from_environment(): + error_message += ( + " The token from HF_TOKEN environment variable is invalid. " + "Note that HF_TOKEN takes precedence over `hf auth login`." + ) + elif token == _get_token_from_file(): + error_message += ( + " The token stored is invalid. Please run `hf auth login --force` to set a new token." + ) + raise HfHubHTTPError(error_message, response=e.response) from e + if e.response.status_code == 429: + error_message = ( + "You've hit the rate limit for the /whoami-v2 endpoint, which is intentionally strict for security reasons." + " If you're calling it often, consider caching the response with `whoami(..., cache=True)`." + ) + raise HfHubHTTPError(error_message, response=e.response) from e + raise + return r.json() + + def get_model_tags(self) -> dict: + """ + List all valid model tags as a nested namespace object + """ + path = f"{self.endpoint}/api/models-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + def get_dataset_tags(self) -> dict: + """ + List all valid dataset tags as a nested namespace object. + """ + path = f"{self.endpoint}/api/datasets-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + @_deprecate_arguments(version="2.0", deprecated_args=["model_name"], custom_message="Use `search` instead.") + @validate_hf_hub_args + def list_models( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + apps: str | list[str] | None = None, + gated: bool | None = None, + inference: Literal["warm"] | None = None, + inference_provider: Literal["all"] | PROVIDER_T | list[PROVIDER_T] | None = None, + model_name: str | None = None, + trained_dataset: str | list[str] | None = None, + search: str | None = None, + pipeline_tag: str | None = None, + num_parameters: str | None = None, + emissions_thresholds: tuple[float, float] | None = None, + # Sorting and pagination parameters + sort: ModelSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandModelProperty_T] | None = None, + full: bool | None = None, + cardData: bool = False, + fetch_config: bool = False, + token: bool | str | None = None, + ) -> Iterable[ModelInfo]: + """ + List models hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable[str]`, *optional*): + A string or list of string to filter models on the Hub. + Models can be filtered by library, language, task, tags, and more. + author (`str`, *optional*): + A string which identify the author (user or organization) of the + returned models. + apps (`str` or `List`, *optional*): + A string or list of strings to filter models on the Hub that + support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`. + gated (`bool`, *optional*): + A boolean to filter models on the Hub that are gated or not. By default, all models are returned. + If `gated=True` is passed, only gated models are returned. + If `gated=False` is passed, only non-gated models are returned. + inference (`Literal["warm"]`, *optional*): + If "warm", filter models on the Hub currently served by at least one provider. + inference_provider (`Literal["all"]` or `str`, *optional*): + A string to filter models on the Hub that are served by a specific provider. + Pass `"all"` to get all models served by at least one provider. + trained_dataset (`str` or `List`, *optional*): + A string tag or a list of string tags of the trained dataset for a + model on the Hub. + search (`str`, *optional*): + A string that will be contained in the returned model ids. + pipeline_tag (`str`, *optional*): + A string pipeline tag to filter models on the Hub by, such as `summarization`. + num_parameters (`str`, *optional*): + Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example + `"min:6B,max:128B"`, `"min:6B"` or `"max:128B"`. + emissions_thresholds (`Tuple`, *optional*): + A tuple of two ints or floats representing a minimum and maximum + carbon footprint to filter the resulting models with in grams. + sort (`ModelSort_T`, *optional*): + The key with which to sort the resulting models. Possible values are "created_at", "downloads", + "last_modified", "likes" and "trending_score". + limit (`int`, *optional*): + The limit on the number of models fetched. Leaving this option + to `None` fetches all models. + expand (`list[ExpandModelProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed. + Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, and `"resourceGroup"`. + full (`bool`, *optional*): + Whether to fetch all model data, including the `last_modified`, + the `sha`, the files and the `tags`. This is set to `True` by + default when using a filter. + cardData (`bool`, *optional*): + Whether to grab the metadata for the model as well. Can contain + useful information such as carbon emissions, metrics, and + datasets trained on. + fetch_config (`bool`, *optional*): + Whether to fetch the model configs as well. This is not included + in `full` due to its size. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + model_name (`str`, *optional*): + (deprecated). Use `search` instead. + + Returns: + `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all models + >>> api.list_models() + + # List text classification models + >>> api.list_models(filter="text-classification") + + # List models from the KerasHub library + >>> api.list_models(filter="keras-hub") + + # List models served by Cohere + >>> api.list_models(inference_provider="cohere") + + # List models with "bert" in their name + >>> api.list_models(search="bert") + + # List models with "bert" in their name and pushed by google + >>> api.list_models(search="bert", author="google") + + # List models with 6B to 128B parameters + >>> api.list_models(num_parameters="min:6B,max:128B", sort="likes") + ``` + """ + if expand and (full or cardData or fetch_config): + raise ValueError("`expand` cannot be used if `full`, `cardData` or `fetch_config` are passed.") + + if emissions_thresholds is not None and not cardData: + raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.") + + path = f"{self.endpoint}/api/models" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + + # Build the filter list + filter_list: list[str] = [] + if filter: + filter_list.extend([filter] if isinstance(filter, str) else filter) + if trained_dataset: + datasets = [trained_dataset] if isinstance(trained_dataset, str) else trained_dataset + filter_list.extend(f"dataset:{d}" if not d.startswith("dataset:") else d for d in datasets) + if len(filter_list) > 0: + params["filter"] = filter_list + + # Handle other query params + if author: + params["author"] = author + if apps: + if isinstance(apps, str): + apps = [apps] + params["apps"] = apps + if gated is not None: + params["gated"] = gated + if inference is not None: + params["inference"] = inference + if inference_provider is not None: + params["inference_provider"] = inference_provider + if pipeline_tag: + params["pipeline_tag"] = pipeline_tag + if num_parameters is not None: + params["num_parameters"] = num_parameters + search_list = [] + if model_name: # deprecated + search_list.append(model_name) + if search: + search_list.append(search) + if len(search_list) > 0: + params["search"] = search_list + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + + # Request additional data + if full: + params["full"] = True + if fetch_config: + params["config"] = True + if cardData: + params["cardData"] = True + if expand: + params["expand"] = expand + + # `items` is a generator + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + model_info = ModelInfo(**item) + if emissions_thresholds is None or _is_emission_within_threshold(model_info, *emissions_thresholds): + yield model_info + + @validate_hf_hub_args + def list_datasets( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + benchmark: Literal[True] | Literal["official"] | str | None = None, + dataset_name: str | None = None, + gated: bool | None = None, + language_creators: str | list[str] | None = None, + language: str | list[str] | None = None, + multilinguality: str | list[str] | None = None, + size_categories: str | list[str] | None = None, + task_categories: str | list[str] | None = None, + task_ids: str | list[str] | None = None, + search: str | None = None, + # Sorting and pagination parameters + sort: DatasetSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandDatasetProperty_T] | None = None, + full: bool | None = None, + token: bool | str | None = None, + ) -> Iterable[DatasetInfo]: + """ + List datasets hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable[str]`, *optional*): + A string or list of string to filter datasets on the hub. + author (`str`, *optional*): + A string which identify the author of the returned datasets. + benchmark (`True`, `"official"`, `str`, *optional*): + Filter datasets by benchmark. Can be `True` or `"official"` to return official benchmark datasets. + For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported). + dataset_name (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by its name, such as `SQAC` or `wikineural` + gated (`bool`, *optional*): + A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned. + If `gated=True` is passed, only gated datasets are returned. + If `gated=False` is passed, only non-gated datasets are returned. + language_creators (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub with how the data was curated, such as `crowdsourced` or + `machine_generated`. + language (`str` or `List`, *optional*): + A string or list of strings representing a two-character language to + filter datasets by on the Hub. + multilinguality (`str` or `List`, *optional*): + A string or list of strings representing a filter for datasets that + contain multiple languages. + size_categories (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the size of the dataset such as `100K>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all datasets + >>> api.list_datasets() + + + # List only the text classification datasets + >>> api.list_datasets(filter="task_categories:text-classification") + + + # List only the datasets in russian for language modeling + >>> api.list_datasets( + ... filter=("language:ru", "task_ids:language-modeling") + ... ) + + # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card) + >>> api.list_datasets(tags="fiftyone") + ``` + + Example usage with the `search` argument: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all datasets with "text" in their name + >>> api.list_datasets(search="text") + + # List all datasets with "text" in their name made by google + >>> api.list_datasets(search="text", author="google") + ``` + """ + if expand and full: + raise ValueError("`expand` cannot be used if `full` is passed.") + + path = f"{self.endpoint}/api/datasets" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + + # Build `filter` list + filter_list = [] + if filter is not None: + if isinstance(filter, str): + filter_list.append(filter) + else: + filter_list.extend(filter) + for key, value in ( + ("language_creators", language_creators), + ("language", language), + ("multilinguality", multilinguality), + ("size_categories", size_categories), + ("task_categories", task_categories), + ("task_ids", task_ids), + ): + if value: + if isinstance(value, str): + value = [value] + for value_item in value: + if not value_item.startswith(f"{key}:"): + data = f"{key}:{value_item}" + else: + data = value_item + filter_list.append(data) + if benchmark is not None: + if benchmark is True: # alias for official benchmark + benchmark = "official" + filter_list.append(f"benchmark:{benchmark}") + if len(filter_list) > 0: + params["filter"] = filter_list + + # Handle other query params + if author: + params["author"] = author + if gated is not None: + params["gated"] = gated + search_list = [] + if dataset_name: + search_list.append(dataset_name) + if search: + search_list.append(search) + if len(search_list) > 0: + params["search"] = search_list + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + + # Request additional data + if expand: + params["expand"] = expand + if full: + params["full"] = True + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield DatasetInfo(**item) + + @validate_hf_hub_args + def list_dataset_parquet_files( + self, + repo_id: str, + *, + config: str | None = None, + token: bool | str | None = None, + ) -> list[DatasetParquetEntry]: + """List parquet files available for a dataset on the Hub. + + All datasets hosted on the Hub are auto-converted to Parquet by the + [Dataset Viewer](https://huggingface.co/docs/dataset-viewer/parquet). + This method returns the list of parquet files with their URLs, configs, + splits and sizes. + + Args: + repo_id (`str`): + The dataset repository ID (e.g. `"username/dataset-name"`). + config (`str`, *optional*): + Filter by a specific config/subset name. When provided, only + parquet files for that config are returned. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[DatasetParquetEntry]`: a list of [`DatasetParquetEntry`] objects + containing config, split, url and size for each parquet file. + + Example: + ```python + >>> from huggingface_hub import list_dataset_parquet_files + >>> list_dataset_parquet_files("lhoestq/demo1") + >>> entries[0] + DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038) + ``` + """ + if self.endpoint != constants._HF_DEFAULT_ENDPOINT: + raise ValueError( + "The Dataset Viewer is only available on the Hugging Face Hub" + f" (endpoint='{constants._HF_DEFAULT_ENDPOINT}'). It is not supported on" + f" third-party endpoints. (endpoint={self.endpoint})" + ) + + url = f"{constants.DATASETS_SERVER_ENDPOINT}/parquet" + params: dict[str, str] = {"dataset": repo_id} + if config is not None: + params["config"] = config + response = get_session().get(url, params=params, headers=self._build_hf_headers(token=token)) + hf_raise_for_status(response) + payload = response.json() + + return [ + DatasetParquetEntry( + config=file_info["config"], + split=file_info["split"], + url=file_info["url"], + size=file_info["size"], + ) + for file_info in payload.get("parquet_files", []) + ] + + @validate_hf_hub_args + def list_spaces( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + search: str | None = None, + datasets: str | Iterable[str] | None = None, + models: str | Iterable[str] | None = None, + linked: bool = False, + # Sorting and pagination parameters + sort: SpaceSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandSpaceProperty_T] | None = None, + full: bool | None = None, + token: bool | str | None = None, + ) -> Iterable[SpaceInfo]: + """ + List spaces hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable`, *optional*): + A string tag or list of tags that can be used to identify Spaces on the Hub. + author (`str`, *optional*): + A string which identify the author of the returned Spaces. + search (`str`, *optional*): + A string that will be contained in the returned Spaces. + datasets (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a dataset. + The name of a specific dataset can be passed as a string. + models (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a model. + The name of a specific model can be passed as a string. + linked (`bool`, *optional*): + Whether to return Spaces that make use of either a model or a dataset. + sort (`SpaceSort_T`, *optional*): + The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified", + "likes" and "trending_score". + limit (`int`, *optional*): + The limit on the number of Spaces fetched. Leaving this option + to `None` fetches all Spaces. + expand (`list[ExpandSpaceProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full` is passed. + Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + full (`bool`, *optional*): + Whether to fetch all Spaces data, including the `last_modified`, `siblings` + and `card_data` fields. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects. + """ + if expand and full: + raise ValueError("`expand` cannot be used if `full` is passed.") + + path = f"{self.endpoint}/api/spaces" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + if filter is not None: + params["filter"] = filter + if author is not None: + params["author"] = author + if search is not None: + params["search"] = search + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + if linked: + params["linked"] = True + if datasets is not None: + params["datasets"] = datasets + if models is not None: + params["models"] = models + + # Request additional data + if expand: + params["expand"] = expand + if full: + params["full"] = True + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield SpaceInfo(**item) + + @validate_hf_hub_args + def search_spaces( + self, + query: str, + *, + filter: str | Iterable[str] | None = None, + sdk: str | list[str] | None = None, + include_non_running: bool = False, + token: bool | str | None = None, + ) -> Iterable[SpaceSearchResult]: + """Search Spaces on the Hub using semantic search. + + This endpoint uses semantic search (embedding-based) for multi-word queries + and full-text search for single-word queries. + + Args: + query (`str`): + The search query string. + filter (`str` or `Iterable[str]`, *optional*): + A string tag or list of tags to filter by. + sdk (`str` or `list[str]`, *optional*): + Filter by SDK (e.g. `"gradio"`, `"docker"`, `"static"`). + include_non_running (`bool`, *optional*): + Whether to include non-running Spaces in results. Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[SpaceSearchResult]`: an iterable of [`SpaceSearchResult`] objects. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> results = list(api.search_spaces("generate image")) + >>> results[0].id + 'mrfakename/Z-Image-Turbo' + >>> results[0].ai_category + 'Image Generation' + ``` + """ + path = f"{self.endpoint}/api/spaces/semantic-search" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {"q": query} + if filter is not None: + params["filter"] = filter + if sdk is not None: + params["sdk"] = sdk + if include_non_running: + params["includeNonRunning"] = True + + r = get_session().get(path, headers=headers, params=params) + hf_raise_for_status(r) + for item in r.json(): + yield SpaceSearchResult(item) + + @validate_hf_hub_args + def unlike( + self, + repo_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Unlike a given repo on the Hub (e.g. remove from favorite list). + + To prevent spam usage, it is not possible to `like` a repository from a script. + + See also [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to unlike. Example: `"user/my-cool-model"`. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or + `"model"` if unliking a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + + Example: + ```python + >>> from huggingface_hub import list_liked_repos, unlike + >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2 + True + >>> unlike("gpt2") + >>> "gpt2" in list_liked_repos().models + False + ``` + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + response = get_session().delete( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_liked_repos( + self, + user: str | None = None, + *, + token: bool | str | None = None, + ) -> UserLikes: + """ + List all public repos liked by a user on huggingface.co. + + This list is public so token is optional. If `user` is not passed, it defaults to + the logged in user. + + See also [`unlike`]. + + Args: + user (`str`, *optional*): + Name of the user for which you want to fetch the likes. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for + models, 1 for datasets and 1 for Spaces). + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `user` is not passed and no token found (either from argument or from machine). + + Example: + ```python + >>> from huggingface_hub import list_liked_repos + + >>> likes = list_liked_repos("julien-c") + + >>> likes.user + "julien-c" + + >>> likes.models + ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...] + ``` + """ + # User is either provided explicitly or retrieved from current token. + if user is None: + me = self.whoami(token=token) + if me["type"] == "user": + user = me["name"] + else: + raise ValueError( + "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user." + ) + + path = f"{self.endpoint}/api/users/{user}/likes" + headers = self._build_hf_headers(token=token) + + likes = list(paginate(path, params={}, headers=headers)) + # Looping over a list of items similar to: + # { + # 'createdAt': '2021-09-09T21:53:27.000Z', + # 'repo': { + # 'name': 'PaddlePaddle/PaddleOCR', + # 'type': 'space' + # } + # } + # Let's loop 3 times over the received list. Less efficient but more straightforward to read. + return UserLikes( + user=user, + total=len(likes), + kernels=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "kernel"], + models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"], + datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"], + spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"], + ) + + def list_user_repos( + self, + namespace: str | None = None, + *, + token: bool | str | None = None, + ) -> Iterable[RepoStorageInfo]: + """List all repositories (models, datasets, spaces, buckets) for a user or organization with storage info. + + Uses the `/api/settings/repositories` endpoint for the authenticated user or + `/api/organizations/{namespace}/settings/repositories` for an organization. + + Args: + namespace (`str`, *optional*): + Organization name. If not provided, lists repos for the authenticated user. + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved token. + + Returns: + `Iterable[RepoStorageInfo]`: An iterable of [`RepoStorageInfo`] objects. + + Example: + ```python + >>> from huggingface_hub import list_user_repos + + >>> repos = list(list_user_repos()) + >>> repos[0] + RepoStorageInfo(id='username/my-model', type='model', ...) + + >>> # List repos from an organization + >>> repos = list(list_user_repos(namespace="my-org")) + ``` + """ + if namespace is not None: + path = f"{self.endpoint}/api/organizations/{namespace}/settings/repositories" + else: + path = f"{self.endpoint}/api/settings/repositories" + headers = self._build_hf_headers(token=token) + for item in paginate(path, params={}, headers=headers): + yield RepoStorageInfo(**item) + + @validate_hf_hub_args + def list_repo_likers( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[User]: + """ + List all users who liked a given repo on the hugging Face Hub. + + See also [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to retrieve . Example: `"user/my-cool-model"`. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: + `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects. + """ + + # Construct the API endpoint + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers" + for liker in paginate(path, params={}, headers=self._build_hf_headers(token=token)): + yield User(username=liker["user"], fullname=liker["fullname"], avatar_url=liker["avatarUrl"]) + + @validate_hf_hub_args + def model_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + securityStatus: bool | None = None, + files_metadata: bool = False, + expand: list[ExpandModelProperty_T] | None = None, + token: bool | str | None = None, + ) -> ModelInfo: + """ + Get info on one specific model on huggingface.co + + Model can be private if you pass an acceptable token or are logged in. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the model repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + securityStatus (`bool`, *optional*): + Whether to retrieve the security status from the model + repository as well. The security status will be returned in the `security_repo_status` field. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandModelProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `securityStatus` or `files_metadata` are passed. + Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`huggingface_hub.hf_api.ModelInfo`]: The model repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and (securityStatus or files_metadata): + raise ValueError("`expand` cannot be used if `securityStatus` or `files_metadata` are set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/models/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if securityStatus: + params["securityStatus"] = True + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return ModelInfo(**data) + + @validate_hf_hub_args + def dataset_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: list[ExpandDatasetProperty_T] | None = None, + token: bool | str | None = None, + ) -> DatasetInfo: + """ + Get info on one specific dataset on huggingface.co. + + Dataset can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the dataset repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandDatasetProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `files_metadata` is passed. + Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`hf_api.DatasetInfo`]: The dataset repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and files_metadata: + raise ValueError("`expand` cannot be used if `files_metadata` is set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/datasets/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return DatasetInfo(**data) + + @validate_hf_hub_args + def get_dataset_leaderboard( + self, + repo_id: str, + *, + base_model_only: bool | None = None, + token: bool | str | None = None, + timeout: float | None = None, + ) -> list[DatasetLeaderboardEntry]: + """Get the leaderboard for a dataset on the Hub. + + The leaderboard ranks models based on their evaluation scores on the given benchmark + dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation + results submitted to them. This gives a dataset-centric view of scores; for a model-centric + view, use [`model_info`] with `expand=["evalResults"]`. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. For example: `"allenai/olmOCR-bench"`. + base_model_only (`bool` or `None`, *optional*): + By default, the leaderboard only includes models that have no declared `base_model` relation + (i.e. canonical/root repos), matching the Hub's default leaderboard view. Fine-tuned or derivative + repos that declare a parent model are excluded. Pass `base_model_only=False` to disable this filter and + include every submitted result, regardless of whether the model declares a base model relation. + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + Returns: + `list[DatasetLeaderboardEntry]`: A list of [`DatasetLeaderboardEntry`] objects representing + the leaderboard entries, sorted by rank. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.HfHubHTTPError`] + > If the dataset does not have a leaderboard. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench") + >>> leaderboard[0].model_id + 'datalab-to/chandra-ocr-2' + >>> leaderboard[0].rank + 1 + + # Include fine-tuned / derivative models too + >>> full_leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench", base_model_only=False) + ``` + """ + headers = self._build_hf_headers(token=token) + path = f"{self.endpoint}/api/datasets/{repo_id}/leaderboard" + params = {} + if base_model_only is not None: + params["base_model"] = base_model_only + r = get_session().get(path, headers=headers, params=params, timeout=timeout) + hf_raise_for_status(r) + data = r.json() + return [DatasetLeaderboardEntry(**entry) for entry in data] + + @validate_hf_hub_args + def space_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: list[ExpandSpaceProperty_T] | None = None, + token: bool | str | None = None, + ) -> SpaceInfo: + """ + Get info on one specific Space on huggingface.co. + + Space can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the space repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandSpaceProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full` is passed. + Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`~hf_api.SpaceInfo`]: The space repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and files_metadata: + raise ValueError("`expand` cannot be used if `files_metadata` is set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/spaces/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return SpaceInfo(**data) + + @validate_hf_hub_args + def kernel_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + token: bool | str | None = None, + ) -> KernelInfo: + """ + Get info on one specific kernel on huggingface.co. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + revision (`str`, *optional*): + The revision of the kernel repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`~hf_api.ModelInfo`]: The kernel repository information. + """ + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/kernels/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/kernels/{repo_id}/revision/{quote(revision, safe='')}") + ) + r = get_session().get(path, headers=headers, timeout=timeout) + hf_raise_for_status(r) + data = r.json() + return KernelInfo(**data) + + @validate_hf_hub_args + def repo_info( + self, + repo_id: str, + *, + revision: str | None = None, + repo_type: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None = None, + token: bool | str | None = None, + ) -> ModelInfo | DatasetInfo | SpaceInfo | KernelInfo: + """ + Get the info object for a given repo of a given type. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the repository from which to get the + information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `files_metadata` is passed. + For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`]. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a + [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`] + or [`huggingface_hub.hf_api.SpaceInfo`] object. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + match repo_type: + case None | "model": + method = self.model_info + case "dataset": + method = self.dataset_info # type: ignore + case "space": + method = self.space_info # type: ignore + case "kernel": + # No expand/files_metadata for kernels + return self.kernel_info(repo_id, revision=revision, token=token, timeout=timeout) + case _: + raise ValueError("Unsupported repo type.") + return method( + repo_id, + revision=revision, + token=token, + timeout=timeout, + expand=expand, # type: ignore + files_metadata=files_metadata, + ) + + @validate_hf_hub_args + def resolve_revision( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_files_only: bool = False, + token: bool | str | None = None, + ) -> ResolvedRevision: + """Resolve a revision (branch, tag, PR ref) to a commit hash. + + This is meant for libraries that download and load several components of a repo separately (config, + weights, tokenizer, ...). Resolving the revision once and passing the returned [`ResolvedRevision`] around + guarantees that every subsequent call targets the exact same commit, even if the repo is updated in the + meantime. It also saves HTTP calls, as downloads made with a commit hash can be served from the local + cache without contacting the Hub. + + The `revision` -> `commit hash` mapping is cached on disk (in the `refs/` folder of the cache), on a + best-effort basis. If the Hub cannot be reached later on (offline mode, connection error, timeout, Hub + downtime, ...), the cached value is used as a fallback. + + > [!TIP] + > If you only need to download a full repo snapshot, a single [`snapshot_download`] call is enough and + > already does the right thing. `resolve_revision` is only useful when downloading files separately. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if the repo is a dataset, space or kernel repo, + `None` or `"model"` if it is a model. Default is `None`. + revision (`str`, *optional*): + The revision to resolve. Can be a branch name, a tag, a PR ref or a commit hash. Defaults to the + default branch. If a [`ResolvedRevision`] is passed, it is returned as is. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. Defaults to the value of `HF_HUB_CACHE`. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, resolve the revision from the local cache only, without contacting the Hub. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`ResolvedRevision`]: A `str` subclass holding both the requested revision and the commit hash it resolves to. + + Raises: + [`~errors.RevisionResolutionError`] + If the revision cannot be resolved: the Hub could not be reached and nothing is cached locally. + [`~errors.RevisionNotFoundError`] + If the revision does not exist on the Hub. + [`~errors.RepositoryNotFoundError`] + If the repository cannot be found. This may be because it doesn't exist, or because it is set to + `private` and you do not have access. + + Example: + ```py + >>> from huggingface_hub import hf_hub_download, resolve_revision + >>> revision = resolve_revision("openai-community/gpt2") + >>> revision + ResolvedRevision(initial=None, resolved='607a30d783dfa663caf39e06633721c8d4cfcd7e') + + # Pass it around: every download is pinned to the same commit + >>> config = hf_hub_download("openai-community/gpt2", "config.json", revision=revision) + >>> weights = hf_hub_download("openai-community/gpt2", "model.safetensors", revision=revision) + ``` + """ + if isinstance(revision, ResolvedRevision): + return revision + if revision is not None and REGEX_COMMIT_HASH.match(revision): + return ResolvedRevision(resolved=revision, initial=revision) + + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + storage_folder = str( + Path(cache_dir).expanduser().resolve() / repo_folder_name(repo_id=repo_id, repo_type=repo_type) + ) + + error: Exception | None = None + if not local_files_only: + try: + sha = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision, token=token).sha + assert sha is not None, "Repo info returned from server must have a revision sha." + try: # best-effort caching, e.g. cache folder might be read-only + _cache_commit_hash_for_specific_revision( + storage_folder, revision or constants.DEFAULT_REVISION, sha + ) + except OSError as e: + logger.warning(f"Ignored error while caching commit hash for '{repo_id}': {e}.") + return ResolvedRevision(resolved=sha, initial=revision) + except httpx.ProxyError: + # Actually raise on proxy error: a misconfigured proxy is not an unreachable Hub + raise + except (httpx.TransportError, OfflineModeIsEnabled) as e: + # Hub cannot be reached (offline mode, connection error, timeout, ...) => fallback on cache + error = e + except HfHubHTTPError as e: + if e.response.status_code < 500: + raise # the Hub answered: repo/revision not found, missing permissions, ... => raise as is + error = e # Hub is down => fallback on cache + + ref_path = Path(storage_folder) / "refs" / (revision or constants.DEFAULT_REVISION) + if ref_path.is_file(): + if error is not None: + logger.warning(f"Could not reach the Hub ({error}). Using cached commit hash for '{repo_id}'.") + return ResolvedRevision(resolved=ref_path.read_text().strip(), initial=revision) + + reason = ( + "'local_files_only=True' is set" + if error is None + else f"the Hub could not be reached ({error.__class__.__name__}: {error})" + ) + raise RevisionResolutionError( + f"Cannot resolve revision '{revision or constants.DEFAULT_REVISION}' for {repo_type} '{repo_id}':" + f" {reason} and no matching entry was found in the local cache ('{ref_path}')." + ) from error + + @validate_hf_hub_args + def repo_exists( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a repository exists on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the repository exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import repo_exists + >>> repo_exists("google/gemma-7b") + True + >>> repo_exists("google/not-a-repo") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + return True + except GatedRepoError: + return True # we don't have access but it exists + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def revision_exists( + self, + repo_id: str, + revision: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a specific revision exists on a repo on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`): + The revision of the repository to check. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the repository and the revision exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import revision_exists + >>> revision_exists("google/gemma-7b", "float16") + True + >>> revision_exists("google/gemma-7b", "not-a-revision") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + return True + except RevisionNotFoundError: + return False + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def file_exists( + self, + repo_id: str, + filename: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a file exists in a repository on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + filename (`str`): + The name of the file to check, for example: + `"config.json"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the file exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import file_exists + >>> file_exists("bigcode/starcoder", "config.json") + True + >>> file_exists("bigcode/starcoder", "not-a-file") + False + >>> file_exists("bigcode/not-a-repo", "config.json") + False + ``` + """ + url = hf_hub_url( + repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint + ) + try: + if token is None: + token = self.token + get_hf_file_metadata(url, token=token) + return True + except GatedRepoError: # raise specifically on gated repo + raise + except (RepositoryNotFoundError, RemoteEntryNotFoundError, RevisionNotFoundError): + return False + + @validate_hf_hub_args + def list_repo_files( + self, + repo_id: str, + *, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> list[str]: + """ + Get the list of files in a given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + revision (`str`, *optional*): + The revision of the repository from which to get the information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to + a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[str]`: the list of files in a given repository. + """ + return [ + f.rfilename + for f in self.list_repo_tree( + repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token + ) + if isinstance(f, RepoFile) + ] + + @validate_hf_hub_args + def list_repo_tree( + self, + repo_id: str, + path_in_repo: str | None = None, + *, + recursive: bool = False, + expand: bool = False, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> Iterable[RepoFile | RepoFolder]: + """ + List a repo tree's files and folders and get information about them. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + path_in_repo (`str`, *optional*): + Relative path of the tree (folder) in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository. + recursive (`bool`, *optional*, defaults to `False`): + Whether to list tree's files and folders recursively. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the tree. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the tree (`"model"`, `"dataset"`, `"space"` or `"kernel"`). + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Union[RepoFile, RepoFolder]]`: + The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is + not guaranteed. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.RemoteEntryNotFoundError`]: + If the tree (folder) does not exist (error 404) on the repo. + + Examples: + + Get information about a repo's tree. + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp") + >>> repo_tree + + >>> list(repo_tree) + [ + RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None), + RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None), + RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None), + RepoFile( + path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e', + lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None), + RepoFile( + path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523', + lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)] + ] + ``` + + Get even more information about a repo's tree (last commit and files' security scan results) + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True) + >>> list(repo_tree) + [ + RepoFolder( + path='feature_extractor', + tree_id='aa536c4ea18073388b5b0bc791057a7296a00398', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFolder( + path='safety_checker', + tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFile( + path='model_index.json', + size=582, + blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1', + lfs=None, + last_commit={ + 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e', + 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)', + 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc) + }, + security={ + 'safe': True, + 'av_scan': {'virusFound': False, 'virusNames': None}, + 'pickle_import_scan': None + } + ) + ... + ] + ``` + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else "" + tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}" + for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}): + yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)) + + @validate_hf_hub_args + def verify_repo_checksums( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + local_dir: str | Path | None = None, + cache_dir: str | Path | None = None, + token: str | bool | None = None, + ) -> FolderVerification: + """ + Verify local files for a repo against Hub checksums. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + repo_type (`str`, *optional*): + The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + revision (`str`, *optional*): + The revision of the repository from which to get the tree. Defaults to `"main"` branch. + local_dir (`str` or `Path`, *optional*): + The local directory to verify. + cache_dir (`str` or `Path`, *optional*): + The cache directory to verify. + token (Union[bool, str, None], optional): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`FolderVerification`]: a structured result containing the verification details. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + """ + + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + if local_dir is not None and cache_dir is not None: + raise ValueError("Pass either `local_dir` or `cache_dir`, not both.") + + root, remote_revision = resolve_local_root( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + cache_dir=Path(cache_dir) if cache_dir is not None else None, + local_dir=Path(local_dir) if local_dir is not None else None, + ) + local_by_path = collect_local_files(root) + + # get remote entries (only files, not folders) + remote_by_path: dict[str, RepoFile] = {} + for entry in self.list_repo_tree( + repo_id=repo_id, recursive=True, revision=remote_revision, repo_type=repo_type, token=token + ): + if isinstance(entry, RepoFile): + remote_by_path[entry.path] = entry + + return verify_maps( + remote_by_path=remote_by_path, + local_by_path=local_by_path, + revision=remote_revision, + verified_path=root, + ) + + @validate_hf_hub_args + def list_repo_refs( + self, + repo_id: str, + *, + repo_type: str | None = None, + include_pull_requests: bool = False, + token: str | bool | None = None, + ) -> GitRefs: + """ + Get the list of refs of a given repo (both tags and branches). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if listing refs from a dataset, a Space or a Kernel, + `None` or `"model"` if listing from a model. Default is `None`. + include_pull_requests (`bool`, *optional*): + Whether to include refs from pull requests in the list. Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_repo_refs("gpt2") + GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[]) + + >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset') + GitRefs( + branches=[ + GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'), + GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714') + ], + converts=[], + tags=[ + GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da') + ] + ) + ``` + + Returns: + [`GitRefs`]: object containing all information about branches and tags for a + repo on the Hub. + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + response = get_session().get( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs", + headers=self._build_hf_headers(token=token), + params={"include_prs": 1} if include_pull_requests else {}, + ) + hf_raise_for_status(response) + data = response.json() + + def _format_as_git_ref_info(item: dict) -> GitRefInfo: + return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"]) + + return GitRefs( + branches=[_format_as_git_ref_info(item) for item in data["branches"]], + converts=[_format_as_git_ref_info(item) for item in data["converts"]], + tags=[_format_as_git_ref_info(item) for item in data["tags"]], + pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]] + if include_pull_requests + else None, + ) + + @validate_hf_hub_args + def list_repo_commits( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + revision: str | None = None, + formatted: bool = False, + ) -> list[GitCommitInfo]: + """ + Get the list of commits of a given revision for a repo on the Hub. + + Commits are sorted by date (last commit first). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + formatted (`bool`): + Whether to return the HTML-formatted title and description of the commits. Defaults to False. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Commits are sorted by date (last commit first) + >>> initial_commit = api.list_repo_commits("gpt2")[-1] + + # Initial commit is always a system commit containing the `.gitattributes` file. + >>> initial_commit + GitCommitInfo( + commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8', + authors=['system'], + created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc), + title='initial commit', + message='', + formatted_title=None, + formatted_message=None + ) + + # Create an empty branch by deriving from initial commit + >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id) + ``` + + Returns: + list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + + # Paginate over results and return the list of commits. + return [ + GitCommitInfo( + commit_id=item["id"], + authors=[author["user"] for author in item["authors"]], + created_at=parse_datetime(item["date"]), + title=item["title"], + message=item["message"], + formatted_title=item.get("formatted", {}).get("title"), + formatted_message=item.get("formatted", {}).get("message"), + ) + for item in paginate( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}", + headers=self._build_hf_headers(token=token), + params={"expand[]": "formatted"} if formatted else {}, + ) + ] + + @validate_hf_hub_args + def get_paths_info( + self, + repo_id: str, + paths: list[str] | str, + *, + expand: bool = False, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> list[RepoFile | RepoFolder]: + """ + Get information about a repo's paths. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + paths (`Union[list[str], str]`, *optional*): + The paths to get information about. If a path do not exist, it is ignored without raising + an exception. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[Union[RepoFile, RepoFolder]]`: + The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + Example: + ```py + >>> from huggingface_hub import get_paths_info + >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset") + >>> paths_info + [ + RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None), + RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None) + ] + ``` + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + response = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}", + data={ + "paths": paths if isinstance(paths, list) else [paths], + "expand": expand, + }, + headers=headers, + ) + hf_raise_for_status(response) + paths_info = response.json() + return [ + RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info) + for path_info in paths_info + ] + + @validate_hf_hub_args + def super_squash_history( + self, + repo_id: str, + *, + branch: str | None = None, + commit_message: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> None: + """Squash commit history on a branch for a repo on the Hub. + + Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to + clutter the history. Squashing commits can only be performed from the head of a branch. + + > [!WARNING] + > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation. + + > [!WARNING] + > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since + > their history will have diverged. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + branch (`str`, *optional*): + The branch to squash. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The commit message to use for the squashed commit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If the branch to squash cannot be found. + [`~utils.BadRequestError`]: + If invalid reference for a branch. You cannot squash history on tags. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Create repo + >>> repo_id = api.create_repo("test-squash").repo_id + + # Make a lot of commits. + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content") + + # Squash history + >>> api.super_squash_history(repo_id=repo_id) + ``` + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError("Invalid repo type") + if branch is None: + branch = constants.DEFAULT_REVISION + + # Prepare request + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}" + headers = self._build_hf_headers(token=token) + commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub" + + # Super-squash + response = get_session().post(url=url, headers=headers, json={"message": commit_message}) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_lfs_files( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[LFSFileInfo]: + """ + List all LFS files in a repo on the Hub. + + This is primarily useful to count how much storage a repo is using and to eventually clean up large files + with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits + referencing this deleted files and that cannot be undone. + + Args: + repo_id (`str`): + The repository for which you are listing LFS files. + repo_type (`str`, *optional*): + Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or + `"model"` if listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + # Prepare request + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files" + headers = self._build_hf_headers(token=token) + + # Paginate over LFS items + for item in paginate(url, params={}, headers=headers): + yield LFSFileInfo(**item) + + @validate_hf_hub_args + def permanently_delete_lfs_files( + self, + repo_id: str, + lfs_files: Iterable[LFSFileInfo], + *, + rewrite_history: bool = True, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Permanently delete LFS files from a repo on the Hub. + + > [!WARNING] + > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your + > repository. This is a non-revertible operation. Use it only if you know what you are doing. + + Args: + repo_id (`str`): + The repository for which you are listing LFS files. + lfs_files (`Iterable[LFSFileInfo]`): + An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list + all LFS files from a repo. + rewrite_history (`bool`, *optional*, default to `True`): + Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended). + repo_type (`str`, *optional*): + Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or + `"model"` if listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + # Prepare request + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files/batch" + headers = self._build_hf_headers(token=token) + + # Delete LFS items by batches of 1000 + for batch in chunk_iterable(lfs_files, 1000): + shas = [item.file_oid for item in batch] + if len(shas) == 0: + return + payload = { + "deletions": { + "sha": shas, + "rewriteHistory": rewrite_history, + } + } + response = get_session().post(url, headers=headers, json=payload) + hf_raise_for_status(response) + + def list_space_templates(self, *, token: str | bool | None = None) -> list[SpaceTemplate]: + """List the official Space templates available on the Hub. + + The `repo_id` of a returned template (or its short `name`) can be passed as `space_template` + to [`HfApi.create_repo`] to seed a new Space from that template. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[SpaceTemplate]`: The list of available Space templates. + + Example: + ```py + >>> from huggingface_hub import list_space_templates + >>> templates = list_space_templates() + >>> templates[0] + SpaceTemplate(name='Streamlit', repo_id='streamlit/streamlit-template-space', sdk='docker', preferred_private=False) + ``` + """ + r = get_session().get(f"{self.endpoint}/api/spaces/templates", headers=self._build_hf_headers(token=token)) + hf_raise_for_status(r) + return [SpaceTemplate(item) for item in r.json()["templates"]] + + @_deprecate_arguments( + version="2.0", + deprecated_args={"space_storage"}, + custom_message="Use `space_volumes` to mount volumes on a Space.", + ) + @validate_hf_hub_args + def create_repo( + self, + repo_id: str, + *, + token: str | bool | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + resource_group_id: str | None = None, + region: REPO_REGIONS | None = None, + space_sdk: str | None = None, + space_hardware: SpaceHardware | None = None, + space_storage: SpaceStorage | None = None, + space_sleep_time: int | None = None, + space_secrets: list[dict[str, str]] | None = None, + space_variables: list[dict[str, str]] | None = None, + space_volumes: list[Volume] | None = None, + space_template: str | None = None, + ) -> RepoUrl: + """Create an empty repo on the HuggingFace Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + private (`bool`, *optional*): + Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. If `None` + (default), the repo will be public unless the organization's default is private. This value is ignored + if the repo already exists. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + resource_group_id (`str`, *optional*): + Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and + allow to define which members of the organization can access the resource. The ID of a resource group + can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`). + To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups. + region (`Literal["us", "eu"]`, *optional*): + Cloud region in which to create the repo. Can be one of `"us"` or `"eu"`. If not specified, the repo will be + created in the default region. Requires Team plan or above. + space_sdk (`str`, *optional*): + Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static". + space_hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list. + space_storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + space_sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + space_secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + space_variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + space_volumes (`list[Volume]`, *optional*): + A list of [`Volume`] objects to mount in the Space at creation time. Each volume has a `type` + (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path` + (path inside the container), and optional `revision`, `read_only`, and `path` fields. + Only applicable if repo_type is "space". + space_template (`str`, *optional*): + Seed the new Space from an official template. Can be either the template repo id + (e.g. `"SpacesExamples/jupyterlab"`) or its short name (e.g. `"JupyterLab"`). Use + [`HfApi.list_space_templates`] to list available templates. Only applicable if repo_type is + "space". If the template is recommended to be private and visibility is not explicitly set, the Space + is created as private. + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/create" + + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError("Invalid repo type") + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + resolved_space_template: str | None = None + if space_template is not None: + if repo_type != constants.REPO_TYPE_SPACE: + raise ValueError(f"space_template can only be used with repo_type 'space'. Got repo_type={repo_type}.") + + # space_template passed => resolve it + all_templates = self.list_space_templates(token=token) + for candidate in all_templates: + if candidate.repo_id == space_template: + template = candidate + break + if candidate.name.lower() == space_template.lower(): + template = candidate + break + else: + raise ValueError( + f"Unknown Space template '{space_template}'. Expected one of {', '.join(sorted(t.name for t in all_templates))}. Use `HfApi.list_space_templates()` to list templates." + ) + + resolved_space_template = template.repo_id + # If the chosen template is recommended to be private and the user did not explicitly set a + # visibility, default to private (mirrors the recommendation shown in the web UI). + if template.preferred_private and private is None and visibility is None: + resolved_visibility = "private" + # space_sdk can be omitted by the user, we set it following server info + if space_sdk is not None and space_sdk != template.sdk: + raise ValueError( + f"space_sdk must match the SDK of the chosen space_template. Got {space_sdk}, expected {template.sdk}." + ) + space_sdk = template.sdk + + payload: dict[str, Any] = {"name": name, "organization": organization} + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + if repo_type is not None: + payload["type"] = repo_type + if repo_type == "space": + if space_sdk is None: + raise ValueError( + "No space_sdk provided. `create_repo` expects space_sdk to be one" + f" of {constants.SPACES_SDK_TYPES} when repo_type is 'space'`" + ) + if space_sdk not in constants.SPACES_SDK_TYPES: + raise ValueError(f"Invalid space_sdk. Please choose one of {constants.SPACES_SDK_TYPES}.") + payload["sdk"] = space_sdk + if resolved_space_template is not None: + payload["template"] = resolved_space_template + + if space_sdk is not None and repo_type != "space": + warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.") + + space_args: list[tuple[str, str, Any]] = [ + # input arg, payload key, value + ("space_hardware", "hardware", space_hardware), + ("space_storage", "storageTier", space_storage), + ("space_sleep_time", "sleepTimeSeconds", space_sleep_time), + ("space_secrets", "secrets", space_secrets), + ("space_variables", "variables", space_variables), + ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None), + ] + + if repo_type == constants.REPO_TYPE_SPACE: + for _, key, value in space_args: + if value is not None: + payload[key] = value + if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + else: + if provided_space_args := [arg for arg, _, value in space_args if value is not None]: + warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.") + + if resource_group_id is not None: + payload["resourceGroupId"] = resource_group_id + if region is not None: + payload["region"] = region + + headers = self._build_hf_headers(token=token) + while True: + r = get_session().post(path, headers=headers, json=payload) + if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text: + # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to + # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running + # tests. To avoid any inconvenience, we retry to create the repo for this specific error. + # NOTE: This could have been fixed directly in the tests, but adding it here should fix CIs for all + # dependent libraries. + # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism. + logger.debug("Create repo failed due to a concurrency issue. Retrying...") + continue + break + + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + # Repo already exists and `exist_ok=True` + pass + elif exist_ok and err.response.status_code in (401, 402, 403): + # 401 -> if JWT token without create repo scope + # 402 -> if payment required (e.g. if Gradio/Docker Space and free user) + # 403 -> if no write permission on the namespace + # In all 3 cases, repo might already exist + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + if repo_type is None or repo_type == constants.REPO_TYPE_MODEL: + return RepoUrl(f"{self.endpoint}/{repo_id}") + return RepoUrl(f"{self.endpoint}/{constants.REPO_TYPES_URL_PREFIXES[repo_type]}{repo_id}") + except HfHubHTTPError: + raise err + else: + raise + + d = r.json() + return RepoUrl(d["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def delete_repo( + self, + repo_id: str, + *, + token: str | bool | None = None, + repo_type: str | None = None, + missing_ok: bool = False, + ) -> None: + """ + Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. + missing_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo does not exist. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to delete from cannot be found and `missing_ok` is set to False (default). + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/delete" + + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError("Invalid repo type") + + json = {"name": name, "organization": organization} + if repo_type is not None: + json["type"] = repo_type + + headers = self._build_hf_headers(token=token) + r = get_session().request("DELETE", path, headers=headers, json=json) + try: + hf_raise_for_status(r) + except RepositoryNotFoundError: + if not missing_ok: + raise + + @validate_hf_hub_args + def update_repo_settings( + self, + repo_id: str, + *, + gated: Literal["auto", "manual", False] | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + ) -> None: + """ + Update the settings of a repository, including gated access and visibility. + + To give more control over how repos are used, the Hub allows repo authors to enable + access requests for their repos, and also to change the visibility of the repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a /. + gated (`Literal["auto", "manual", False]`, *optional*): + The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated. + * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria. + * "manual": The repository is gated, and access requests require manual approval. + * False : The repository is not gated, and anyone can access it. + private (`bool`, *optional*): + Whether the repository should be private. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the repository. Can be `"public"` or `"private"`, or `"protected"` for Spaces. + token (`Union[str, bool, None]`, *optional*): + A valid user access token (string). Defaults to the locally saved token, + which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass False. + repo_type (`str`, *optional*): + The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`). + Defaults to `"model"`. + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If gated is not one of "auto", "manual", or False. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If repo_type is not one of the values in constants.REPO_TYPES. + [`~utils.HfHubHTTPError`]: + If the request to the Hugging Face Hub API fails. + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + """ + + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL # default repo type + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + # Prepare the JSON payload for the PUT request + payload: dict = {} + + if gated is not None: + if gated not in ["auto", "manual", False]: + raise ValueError(f"Invalid gated status, must be one of 'auto', 'manual', or False. Got '{gated}'.") + payload["gated"] = gated + + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + + if len(payload) == 0: + raise ValueError("At least one setting must be updated.") + + # Build headers + headers = self._build_hf_headers(token=token) + + r = get_session().put( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings", + headers=headers, + json=payload, + ) + hf_raise_for_status(r) + + def move_repo( + self, + from_id: str, + to_id: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ): + """ + Moving a repository from namespace1/repo_name1 to namespace2/repo_name2 + + Note there are certain limitations. For more information about moving + repositories, please see + https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo. + + Args: + from_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Original repository identifier. + to_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Final repository identifier. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if len(from_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)") + + if len(to_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)") + + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL # Hub won't accept `None`. + + json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type} + + path = f"{self.endpoint}/api/repos/move" + headers = self._build_hf_headers(token=token) + r = get_session().post(path, headers=headers, json=json) + try: + hf_raise_for_status(r) + except HfHubHTTPError as e: + e.append_to_message( + "\nFor additional documentation please see" + " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo." + ) + raise + + @overload + def create_commit( # type: ignore + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: Literal[False] = ..., + _hot_reload: bool | None = None, + ) -> CommitInfo: ... + + @overload + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: Literal[True] = ..., + _hot_reload: bool | None = None, + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: bool = False, + _hot_reload: bool | None = None, + ) -> CommitInfo | Future[CommitInfo]: + """ + Creates a commit in the given repo, deleting & uploading files as needed. + + > [!WARNING] + > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects + > for multiple commits. + + > [!WARNING] + > `create_commit` assumes that the repo already exists on the Hub. If you get a + > Client error 404, please make sure you are authenticated, that your token has the required permissions, + > and that `repo_id` and `repo_type` are set correctly. If repo does not exist, + > create it first using [`~hf_api.create_repo`]. + + > [!WARNING] + > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files. + + Args: + repo_id (`str`): + The repository in which the commit will be created, for example: + `"username/custom_transformers"` + + operations (`Iterable` of [`~hf_api.CommitOperation`]): + An iterable of operations to include in the commit, either: + + - [`~hf_api.CommitOperationAdd`] to upload a file + - [`~hf_api.CommitOperationDelete`] to delete a file + - [`~hf_api.CommitOperationCopy`] to copy a file + + Operation objects will be mutated to include information relative to the upload. Do not reuse the + same objects for multiple commits. + + commit_message (`str`): + The summary (first line) of the commit that will be created. + + commit_description (`str`, *optional*): + The description of the commit that will be created + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. + Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`, + the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr` + is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit` + ensures the repo has not changed before committing the changes, and can be especially useful + if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If commit message is empty. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If parent commit is not a valid commit OID. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If a README.md file with an invalid metadata section is committed. In this case, the commit will fail + early, before trying to upload any file. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `create_pr` is `True` and revision is neither `None` nor `"main"`. + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + """ + if parent_commit is not None and not constants.REGEX_COMMIT_OID.fullmatch(parent_commit): + raise ValueError( + f"`parent_commit` is not a valid commit OID. It must match the following regex: {constants.REGEX_COMMIT_OID}" + ) + + if commit_message is None or len(commit_message) == 0: + raise ValueError("`commit_message` can't be empty, please pass a value.") + + commit_description = commit_description if commit_description is not None else "" + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + unquoted_revision = revision or constants.DEFAULT_REVISION + revision = quote(unquoted_revision, safe="") + create_pr = create_pr if create_pr is not None else False + _hot_reload = _hot_reload if _hot_reload is not None else False + + headers = self._build_hf_headers(token=token) + + operations = list(operations) + additions = [op for op in operations if isinstance(op, CommitOperationAdd)] + copies = [op for op in operations if isinstance(op, CommitOperationCopy)] + nb_additions = len(additions) + nb_copies = len(copies) + nb_deletions = len(operations) - nb_additions - nb_copies + + for addition in additions: + if addition._is_committed: + raise ValueError( + f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a" + " new CommitOperationAdd object if you want to create a new commit." + ) + + if repo_type != "dataset": + for addition in additions: + if addition.path_in_repo.endswith((".arrow", ".parquet")): + warnings.warn( + f"It seems that you are about to commit a data file ({addition.path_in_repo}) to a {repo_type}" + " repository. You are sure this is intended? If you are trying to upload a dataset, please" + " set `repo_type='dataset'` or `--repo-type=dataset` in a CLI." + ) + + logger.debug( + f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copy(ies) and" + f" {nb_deletions} deletion(s)." + ) + + # If updating a README.md file, make sure the metadata format is valid + # It's better to fail early than to fail after all the files have been uploaded. + for addition in additions: + if addition.path_in_repo == "README.md": + with addition.as_file() as file: + content = file.read().decode() + self._validate_yaml(content, repo_type=repo_type, token=token) + # Skip other additions after `README.md` has been processed + break + + # If updating twice the same file or update then delete a file in a single commit + _warn_on_overwriting_operations(operations) + + self.preupload_lfs_files( + repo_id=repo_id, + additions=additions, + token=token, + repo_type=repo_type, + revision=unquoted_revision, # first-class methods take unquoted revision + create_pr=create_pr, + num_threads=num_threads, + free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users + ) + + files_to_copy = _fetch_files_to_copy( + copies=copies, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=unquoted_revision, + endpoint=self.endpoint, + ) + + self._duplicate_lfs_files( + repo_id=repo_id, copies=copies, files_to_copy=files_to_copy, token=token, repo_type=repo_type + ) + + # Remove no-op operations (files that have not changed) + operations_without_no_op = [] + for operation in operations: + if ( + isinstance(operation, CommitOperationAdd) + and operation._remote_oid is not None + and operation._remote_oid == operation._local_oid + ): + # File already exists on the Hub and has not changed: we can skip it. + logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.") + continue + if ( + isinstance(operation, CommitOperationCopy) + and operation._dest_oid is not None + and operation._dest_oid == operation._src_oid + ): + # Source and destination files are identical - skip + logger.debug( + f"Skipping copy for '{operation.src_path_in_repo}' -> '{operation.path_in_repo}' as the content of the source file is the same as the destination file." + ) + continue + operations_without_no_op.append(operation) + if len(operations) != len(operations_without_no_op): + logger.info( + f"Removing {len(operations) - len(operations_without_no_op)} file(s) from commit that have not changed." + ) + + # Return early if empty commit + if len(operations_without_no_op) == 0: + logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.") + + # Get latest commit info + try: + info = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=unquoted_revision, token=token) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + + # Return commit info based on latest commit + url_prefix = self.endpoint + if repo_type is not None and repo_type != constants.REPO_TYPE_MODEL: + url_prefix = f"{url_prefix}/{repo_type}s" + return CommitInfo( + commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}", + commit_message=commit_message, + commit_description=commit_description, + oid=info.sha, # type: ignore + _endpoint=self.endpoint, + ) + + try: + commit_info = _send_commit( + operations=operations_without_no_op, + files_to_copy=files_to_copy, + commit_message=commit_message, + commit_description=commit_description, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=revision, + endpoint=self.endpoint, + parent_commit=parent_commit, + create_pr=create_pr, + hot_reload=_hot_reload, + ) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + except RemoteEntryNotFoundError as e: + if nb_deletions > 0 and "A file with this name doesn't exist" in str(e): + e.append_to_message( + "\nMake sure to differentiate file and folder paths in delete" + " operations with a trailing '/' or using `is_folder=True/False`." + ) + raise + + # Mark additions as committed (cannot be reused in another commit) + for addition in additions: + addition._is_committed = True + + return commit_info + + def preupload_lfs_files( + self, + repo_id: str, + additions: Iterable[CommitOperationAdd], + *, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + free_memory: bool = True, + gitignore_content: str | None = None, + ): + """Pre-upload LFS files to S3 in preparation on a future commit. + + This method is useful if you are generating the files to upload on-the-fly and you don't want to store them + in memory before uploading them all at once. + + > [!WARNING] + > This is a power-user method. You shouldn't need to call it directly to make a normal commit. + > Use [`create_commit`] directly instead. + + > [!WARNING] + > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be + > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same + > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the + > commit operation object, pass `free_memory=False`. + + Args: + repo_id (`str`): + The repository in which you will commit the files, for example: `"username/custom_transformers"`. + + additions (`Iterable` of [`CommitOperationAdd`]): + The list of files to upload. Warning: the objects in this list will be mutated to include information + relative to the upload. Do not reuse the same objects for multiple commits. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`). + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not you plan to create a Pull Request with that commit. Defaults to `False`. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + free_memory (`bool`, *optional*, defaults to `True`): + If `True`, the `path_or_fileobj` attribute of each `CommitOperationAdd` is replaced by an empty + `bytes` object after upload to save memory. Set to `False` if you need to reuse the operation + objects outside of a subsequent [`create_commit`] call. + + gitignore_content (`str`, *optional*): + The content of the `.gitignore` file to know which files should be ignored. The order of priority + is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present + in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub + (if any). + + Example: + ```py + >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo + + >>> repo_id = create_repo("test_preupload").repo_id + + # Generate and preupload LFS files one by one + >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated + >>> for i in range(5): + ... content = ... # generate binary content + ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content) + ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory + ... operations.append(addition) + + # Create commit + >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards") + ``` + """ + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + create_pr = create_pr if create_pr is not None else False + headers = self._build_hf_headers(token=token) + + # Check if a `gitignore` file is being committed to the Hub. + additions = list(additions) + if gitignore_content is None: + for addition in additions: + if addition.path_in_repo == ".gitignore": + with addition.as_file() as f: + gitignore_content = f.read().decode() + break + + # Filter out already uploaded files + new_additions = [addition for addition in additions if not addition._is_uploaded] + + # Check which new files are LFS + # For some items, we might have already fetched the upload mode (in case of upload_large_folder) + additions_no_upload_mode = [addition for addition in new_additions if addition._upload_mode is None] + if len(additions_no_upload_mode) > 0: + try: + _fetch_upload_modes( + additions=additions_no_upload_mode, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=revision, + endpoint=self.endpoint, + create_pr=create_pr or False, + gitignore_content=gitignore_content, + ) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + + # Filter out regular files + new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"] + + # Filter out files listed in .gitignore + new_lfs_additions_to_upload = [] + for addition in new_lfs_additions: + if addition._should_ignore: + logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).") + else: + new_lfs_additions_to_upload.append(addition) + if len(new_lfs_additions) != len(new_lfs_additions_to_upload): + logger.info( + f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) " + "(ignored by gitignore file)." + ) + # If no LFS files remain to upload, keep previous behavior and log explicitly + if len(new_lfs_additions_to_upload) == 0: + logger.debug("No LFS files to upload.") + return + # Prepare upload parameters + upload_kwargs = { + "additions": new_lfs_additions_to_upload, + "repo_type": repo_type, + "repo_id": repo_id, + "headers": headers, + "endpoint": self.endpoint, + # If `create_pr`, we don't want to check user permission on the revision as users with read permission + # should still be able to create PRs even if they don't have write permission on the target branch of the + # PR (i.e. `revision`). + "revision": revision if not create_pr else None, + } + _upload_files( + **upload_kwargs, # type: ignore[arg-type] + num_threads=num_threads, + create_pr=create_pr, + ) + for addition in new_lfs_additions_to_upload: + addition._is_uploaded = True + if free_memory: + addition.path_or_fileobj = b"" + + @validate_hf_hub_args + def _duplicate_lfs_files( + self, + repo_id: str, + copies: Iterable[CommitOperationCopy], + *, + files_to_copy: dict, + token: str | bool | None = None, + repo_type: str | None = None, + ) -> None: + """Duplicate LFS files from source repositories to the destination repository. + + This method is the equivalent of [`preupload_lfs_files`] for cross-repo copy operations. It must be called + before [`create_commit`] to ensure that LFS files from the source repositories are available in the destination + repository before the commit is created. + + Args: + repo_id (`str`): + The destination repository in which you will commit the files, for example: + `"username/custom_transformers"`. + + copies (`Iterable` of [`CommitOperationCopy`]): + The list of copy operations describing which files to duplicate. Only cross-repo copies (where + `src_repo_id` is set) with LFS files will be processed. Warning: the objects in this list will be + mutated to include information relative to the duplication. Do not reuse the same objects for multiple + commits. + + files_to_copy (`dict`): + Pre-fetched file info from [`_fetch_files_to_copy`]. LFS metadata is extracted from this dict instead + of making additional API calls. Keys are `_CopySource` tuples, values are `RepoFile` (for LFS files) + or `bytes` (for regular files). + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + The type of the destination repository (e.g. `"model"` -default-, `"dataset"` or `"space"`). + """ + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + headers = self._build_hf_headers(token=token) + + copies = list(copies) + # Filter to cross-repo copies that haven't been duplicated yet + cross_repo_copies = [op for op in copies if op.src_repo_id is not None and not op._is_duplicated] + if not cross_repo_copies: + logger.debug("No cross-repo LFS files to duplicate.") + return + + # The /lfs-files/duplicate endpoint lives on the *source* repo and takes the destination as `target`. + cross_repo_copies.sort(key=lambda op: (op.src_repo_id or "", op.src_repo_type or "", op.src_revision or "")) + + for (src_repo_id, src_repo_type, src_revision), group in itertools.groupby( + cross_repo_copies, key=lambda op: (op.src_repo_id, op.src_repo_type, op.src_revision) + ): + operations = list(group) + + lfs_files: list[dict] = [] + seen_oids: set[str] = set() + + for op in operations: + key = _CopySource(op.src_repo_id, op.src_repo_type, op.src_path_in_repo, op.src_revision) + src_file = files_to_copy.get(key) + if src_file is None or isinstance(src_file, bytes): + continue + if not src_file.lfs: + continue + if not src_file.xet_hash: + raise ValueError( + f"Cannot duplicate LFS file '{src_file.path}' from {src_repo_type}s/{src_repo_id}: file has no xet hash." + f" (file: {src_file})" + ) + oid = src_file.lfs.sha256 + if oid not in seen_oids: + seen_oids.add(oid) + lfs_files.append({"xetHash": src_file.xet_hash, "sha256": oid, "filename": src_file.path}) + + if not lfs_files: + continue + + # Call the duplicate endpoint on the *source* repo, in batches + duplicate_url = f"{self.endpoint}/api/{src_repo_type}s/{src_repo_id}/lfs-files/duplicate" + for batch in chunk_iterable(lfs_files, DUPLICATE_LFS_BATCH_SIZE): + response = get_session().post( + duplicate_url, + headers=headers, + json={"target": {"type": repo_type, "name": repo_id}, "files": list(batch)}, + ) + hf_raise_for_status(response) + data = response.json() + failures = data.get("failed", []) + if failures: + messages = [f" - {f['sha256']}: {f['error']}" for f in failures] + raise FileDuplicationError( + f"Failed to duplicate files from {src_repo_type}s/{src_repo_id} " + f"to {repo_type}s/{repo_id}:\n" + "\n".join(messages) + ) + + for op in cross_repo_copies: + op._is_duplicated = True + + @overload + def upload_file( # type: ignore + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: Literal[False] = ..., + _hot_reload: bool | None = None, + ) -> CommitInfo: ... + + @overload + def upload_file( + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: Literal[True] = ..., + _hot_reload: bool | None = None, + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def upload_file( + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: bool = False, + _hot_reload: bool | None = None, + ) -> CommitInfo | Future[CommitInfo]: + """ + Upload a local file (up to 50 GB) to the given repo. The upload is done + through a HTTP post request, and doesn't require git or git-lfs to be + installed. + + Args: + path_or_fileobj (`str`, `Path`, `bytes`, or `IO`): + Path to a file on the local machine or binary data stream / + fileobj / buffer. + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + + > [!WARNING] + > `upload_file` assumes that the repo already exists on the Hub. If you get a + > Client error 404, please make sure you are authenticated, that your token has the required permissions, + > and that `repo_id` and `repo_type` are set correctly. If repo does not exist, + > create it first using [`~hf_api.create_repo`]. + + Example: + + ```python + >>> from huggingface_hub import upload_file + + >>> with open("./local/filepath", "rb") as fobj: + ... upload_file( + ... path_or_fileobj=fileobj, + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-dataset", + ... repo_type="dataset", + ... token="my_token", + ... ) + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... ) + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... create_pr=True, + ... ) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + + commit_message = ( + commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub" + ) + operation = CommitOperationAdd( + path_or_fileobj=path_or_fileobj, + path_in_repo=path_in_repo, + ) + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + operations=[operation], + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + _hot_reload=_hot_reload, + parent_commit=parent_commit, + ) + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: Literal[False] = ..., + ) -> CommitInfo: ... + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: Literal[True] = ..., + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def upload_folder( + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: bool = False, + ) -> CommitInfo | Future[CommitInfo]: + """ + Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or + git-lfs to be installed. + + The structure of the folder will be preserved. Files with the same name already present in the repository will + be overwritten. Others will be left untouched. + + Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters + accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as + documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and + `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded. + + Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for + `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths + relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")` + will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted + even if it matches the patterns. + + Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore` + file is not taken into account. + + When `hf_xet` is installed (the default), files are uploaded through a streamed pipeline: uploads start while + the folder is still being checked against the Hub, files are hashed while being chunked for upload (single + read pass), and large folders are automatically committed in several batches to stay below server limits + (follow-up commits get a ` (part N)` suffix on the commit message). If the upload is interrupted, re-running + the same call resumes it: already-committed files are skipped and already-uploaded data is deduplicated. When + `hf_xet` is not installed, falls back to a single commit created with [`create_commit`]. + + Args: + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + folder_path (`str` or `Path`): + Path to the folder to upload on the local file system + path_in_repo (`str`, *optional*): + Relative path of the directory in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to: + `f"Upload {path_in_repo} with huggingface_hub"` + commit_description (`str` *optional*): + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. The PR is always + opened against the default branch: setting both `create_pr=True` and `revision` raises a + `ValueError`. Note that each call with `create_pr=True` opens a new pull request: to resume an + interrupted upload into the existing PR, re-run with `revision="refs/pr/N"` instead. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. If the upload is split into + several commits (large folders), `parent_commit` only applies to the first one. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo while committing + new files. This is useful if you don't know which files have already been uploaded. + Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + + > [!WARNING] + > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make + > sure you are authenticated, that your token has the required permissions, and that `repo_id` and `repo_type` + > are set correctly. If repo does not exist, create it first using [`~hf_api.create_repo`]. + + Example: + + ```python + # Upload checkpoints folder except the log files + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... ignore_patterns="**/logs/*.txt", + ... ) + + # Upload checkpoints folder including logs while deleting existing logs from the repo + # Useful if you don't know exactly which log files have already being pushed + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... delete_patterns="**/logs/*.txt", + ... ) + + # Upload checkpoints folder while creating a PR + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... create_pr=True, + ... ) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if create_pr and revision is not None and revision != constants.DEFAULT_REVISION: + raise ValueError( + f"Cannot use `create_pr=True` with `revision='{revision}'`: pull requests created by" + " `upload_folder` are always opened against the default branch. Don't set `revision` when" + " `create_pr=True`." + ) + + # By default, upload folder to the root directory in repo. + if path_in_repo is None: + path_in_repo = "" + + # Do not upload .git folder + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + ignore_patterns += DEFAULT_IGNORE_PATTERNS + + delete_operations = self._prepare_folder_deletions( + repo_id=repo_id, + repo_type=repo_type, + revision=constants.DEFAULT_REVISION if create_pr else revision, + token=token, + path_in_repo=path_in_repo, + delete_patterns=delete_patterns, + ) + add_operations = self._prepare_upload_folder_additions( + folder_path, + path_in_repo, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + token=token, + repo_type=repo_type, + ) + + # Optimize operations: if some files will be overwritten, we don't need to delete them first + if len(add_operations) > 0: + added_paths = {op.path_in_repo for op in add_operations} + delete_operations = [ + delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths + ] + commit_operations = delete_operations + add_operations + + commit_message = commit_message or "Upload folder using huggingface_hub" + + if is_xet_available(): + # Streamed multi-commit pipeline: uploads and commits overlap, large folders are + # committed in adaptive batches, interrupted uploads resume by re-running. + return pipelined_upload( + self, + repo_id=repo_id, + repo_type=repo_type or constants.REPO_TYPE_MODEL, + add_operations=add_operations, + delete_operations=delete_operations, + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr or False, + parent_commit=parent_commit, + ) + + # Legacy single-commit path (hf_xet not installed). + if len(add_operations) > 30: + log = logger.warning if len(add_operations) > 200 else logger.info + log( + "It seems you are trying to upload a large folder at once. This might take some time and then fail if " + "the folder is too large. Installing `hf_xet` (`pip install hf_xet`) enables a more robust, resumable " + "upload that handles large folders in multiple commits." + ) + return self.create_commit( + repo_type=repo_type, + repo_id=repo_id, + operations=commit_operations, + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_file( + self, + path_in_repo: str, + repo_id: str, + *, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Deletes a file in the given repo. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository from which the file will be deleted, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + > - [`~utils.EntryNotFoundError`] + > If the file to download cannot be found. + + """ + commit_message = ( + commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub" + ) + + operations = [CommitOperationDelete(path_in_repo=path_in_repo)] + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=operations, + revision=revision, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_files( + self, + repo_id: str, + delete_patterns: list[str], + *, + token: bool | str | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Delete files from a repository on the Hub. + + If a folder path is provided, the entire folder is deleted as well as + all files it contained. + + Args: + repo_id (`str`): + The repository from which the folder will be deleted, for example: + `"username/custom_transformers"` + delete_patterns (`list[str]`): + List of files or folders to delete. Each string can either be + a file path, a folder path, or a wildcard pattern. Patterns are Standard + Wildcards (globbing patterns) as documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). + The pattern matching is based on [`fnmatch`](https://docs.python.org/3/library/fnmatch.html). + Note that `fnmatch` matches `*` across path boundaries, unlike traditional Unix shell globbing. + E.g. `["file.txt", "folder/", "data/*.parquet"]` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + to the stored token. + repo_type (`str`, *optional*): + Type of the repo to delete files from. Can be `"model"`, + `"dataset"` or `"space"`. Defaults to `"model"`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary (first line) of the generated commit. Defaults to + `f"Delete files using huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + """ + operations = self._prepare_folder_deletions( + repo_id=repo_id, repo_type=repo_type, delete_patterns=delete_patterns, path_in_repo="", revision=revision + ) + + if commit_message is None: + commit_message = f"Delete files {' '.join(delete_patterns)} with huggingface_hub" + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=operations, + revision=revision, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_folder( + self, + path_in_repo: str, + repo_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Deletes a folder in the given repo. + + Simple wrapper around [`create_commit`] method. + + Args: + path_in_repo (`str`): + Relative folder path in the repo, for example: `"checkpoints/1fec34a"`. + repo_id (`str`): + The repository from which the folder will be deleted, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the folder is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete folder {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + """ + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)], + revision=revision, + commit_message=( + commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub" + ), + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + def upload_large_folder( + self, + repo_id: str, + folder_path: str | Path, + *, + repo_type: str, # Repo type is required! + revision: str | None = None, + private: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + num_workers: int | None = None, + print_report: bool = True, + print_report_every: int = 60, + ) -> None: + """Upload a large folder to the Hub in the most resilient way possible. + + > [!WARNING] + > `upload_large_folder` is deprecated and will be removed in a future release. [`upload_folder`] is now multi-commits + > by default and resilient to interruptions so it is the recommended way to upload large folders. + + Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be + hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder. + At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/` + to be able to resume the process if interrupted. The whole process might result in several commits. + + Args: + repo_id (`str`): + The repository to which the file will be uploaded. + E.g. `"HuggingFaceTB/smollm-corpus"`. + folder_path (`str` or `Path`): + Path to the folder to upload on the local file system. + repo_type (`str`): + Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`. + Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid + any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload + everything. + revision (`str`, `optional`): + The branch to commit to. If not provided, the `main` branch will be used. + private (`bool`, `optional`): + Whether the repository should be private. + If `None` (default), the repo will be public unless the organization's default is private. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + num_workers (`int`, *optional*): + Number of workers to start. Defaults to half of CPU cores (minimum 1). + A higher number of workers may speed up the process if your machine allows it. However, on machines with a + slower connection, it is recommended to keep the number of workers low to ensure better resumability. + Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted. + print_report (`bool`, *optional*): + Whether to print a report of the upload progress. Defaults to True. + Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report. + print_report_every (`int`, *optional*): + Frequency at which the report is printed. Defaults to 60 seconds. + + > [!TIP] + > A few things to keep in mind: + > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations + > - Do not start several processes in parallel. + > - You can interrupt and resume the process at any time. + > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first. + + > [!WARNING] + > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice: + > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally. + > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created. + > - you cannot delete from the repo while uploading. Please make a separate commit first. + > - you cannot create a PR directly. Please create a PR first (from the UI or using [`create_pull_request`]) and then commit to it by passing `revision`. + + **Technical details:** + + `upload_large_folder` process is as follow: + 1. (Check parameters and setup.) + 2. Create repo if missing. + 3. List local files to upload. + 4. Run validation checks and display warnings if repository limits might be exceeded: + - Warns if the total number of files exceeds 100k (recommended limit). + - Warns if any folder contains more than 10k files (recommended limit). + - Warns about files larger than 20GB (recommended) or 50GB (hard limit). + 5. Start workers. Workers can perform the following tasks: + - Hash a file. + - Get upload mode (regular or LFS) for a list of files. + - Pre-upload an LFS file. + - Commit a bunch of files. + Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until + all files are uploaded and committed. + 6. While workers are up, regularly print a report to sys.stdout. + + Order of priority: + 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file). + 2. Commit if at least 150 files are ready to commit. + 3. Get upload mode if at least 10 files have been hashed. + 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading. + 5. Hash file if at least 1 file and no worker is hashing. + 6. Get upload mode if at least 1 file and no worker is getting upload mode. + 7. Pre-upload LFS file if at least 1 file. + 8. Hash file if at least 1 file to hash. + 9. Get upload mode if at least 1 file to get upload mode. + 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt. + 11. Commit if at least 1 file to commit and all other queues are empty. + + Special rules: + - Only one worker can commit at a time. + - If no tasks are available, the worker waits for 10 seconds before checking again. + """ + warnings.warn( + "\n" + "================================================================================\n" + "`upload_large_folder` is DEPRECATED and will be removed in a future release.\n" + "\n" + "Use `upload_folder` instead:\n" + "\n" + f' api.upload_folder(repo_id="{repo_id}", repo_type="{repo_type}", folder_path="{folder_path}")\n' + "================================================================================\n", + FutureWarning, + stacklevel=2, + ) + return upload_large_folder_internal( + self, + repo_id=repo_id, + folder_path=folder_path, + repo_type=repo_type, + revision=revision, + private=private, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + num_workers=num_workers, + print_report=print_report, + print_report_every=print_report_every, + ) + + @validate_hf_hub_args + def get_hf_file_metadata( + self, + *, + url: str, + token: bool | str | None = None, + timeout: float | None = constants.HF_HUB_ETAG_TIMEOUT, + ) -> HfFileMetadata: + """Fetch metadata of a file versioned on the Hub for a given url. + + Args: + url (`str`): + File url, for example returned by [`hf_hub_url`]. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send metadata before giving up. + + Returns: + A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return get_hf_file_metadata( + url=url, + token=token, + timeout=timeout, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + endpoint=self.endpoint, + ) + + @overload + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[False] = False, + ) -> str: ... + + @overload + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[True], + ) -> DryRunFileInfo: ... + + @validate_hf_hub_args + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, + ) -> str | DryRunFileInfo: + """Download a given file if it's not already present in the local cache. + + The new cache file layout looks like this: + - The cache directory contains one subfolder per repo_id (namespaced by repo type) + - inside each repo folder: + - refs is a list of the latest known revision => commit_hash pairs + - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on + whether they're LFS files or not) + - snapshots contains one subfolder per commit, each "commit" contains the subset of the files + that have been resolved at that particular commit. Each filename is a symlink to the blob + at that particular commit. + + ``` + [ 96] . + └── [ 160] models--julien-c--EsperBERTo-small + ├── [ 160] blobs + │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e + │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812 + ├── [ 96] refs + │ └── [ 40] main + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48 + ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e + └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + ``` + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files. While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the repository. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded file will be placed under this directory. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `httpx.request`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the file. Returns a + [`DryRunFileInfo`] object containing information about what would be downloaded. + + Returns: + `str` or [`DryRunFileInfo`]: + - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk. + - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`~utils.RemoteEntryNotFoundError`] + If the file to download cannot be found. + [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` but the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + If ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If some parameter value is invalid. + """ + from .file_download import hf_hub_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return hf_hub_download( + repo_id=repo_id, + filename=filename, + subfolder=subfolder, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + library_name=self.library_name, + library_version=self.library_version, + cache_dir=cache_dir, + local_dir=local_dir, + user_agent=self.user_agent, + force_download=force_download, + etag_timeout=etag_timeout, + token=token, + headers=self.headers, + local_files_only=local_files_only, + tqdm_class=tqdm_class, + dry_run=dry_run, + ) + + @overload + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[False] = False, + ) -> str: ... + + @overload + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[True], + ) -> list[DryRunFileInfo]: ... + + @validate_hf_hub_args + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, + ) -> str | list[DryRunFileInfo]: + """Download repo files. + + Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from + a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order + to keep their actual filename relative to that folder. You can also filter which files to download using + `allow_patterns` and `ignore_patterns`. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files.While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly + configured. It is also not possible to filter which files to download when cloning a repository using git. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded files will be placed under this directory. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `httpx.request`. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in the local cache. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are downloaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not downloaded. + max_workers (`int`, *optional*): + Number of concurrent threads to download files (1 thread = 1 file download). + Defaults to 8. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Note that the `tqdm_class` is not passed to each individual download. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the files. Returns a list of + [`DryRunFileInfo`] objects containing information about what would be downloaded. + + Returns: + `str` or list of [`DryRunFileInfo`]: + - If `dry_run=False`: Folder path of the repo snapshot. + - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` and the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if + ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid. + """ + from ._snapshot_download import snapshot_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return snapshot_download( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + cache_dir=cache_dir, + local_dir=local_dir, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + etag_timeout=etag_timeout, + force_download=force_download, + token=token, + local_files_only=local_files_only, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + max_workers=max_workers, + tqdm_class=tqdm_class, + headers=self.headers, + dry_run=dry_run, + ) + + def get_safetensors_metadata( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + timeout: float | None = constants.HF_HUB_DOWNLOAD_TIMEOUT, + ) -> SafetensorsRepoMetadata: + """ + Parse metadata for a safetensors repo on the Hub. + + We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single + safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the + metadata from the index file and then parse the metadata from each shard. + + To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send data before giving up, passed to each request that + fetches a safetensors file header. Set to `None` to disable the timeout (not recommended, as a stalled + connection can hang the call indefinitely). + + Returns: + [`SafetensorsRepoMetadata`]: information related to safetensors repo. + + Raises: + [`NotASafetensorsRepoError`] + If the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + [`SafetensorsParsingError`] + If a safetensors file header couldn't be parsed correctly. + + Example: + ```py + # Parse repo with single weights file + >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m") + >>> metadata + SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...}, + files_metadata={'model.safetensors': SafetensorsFileMetadata(...)} + ) + >>> metadata.files_metadata["model.safetensors"].metadata + {'format': 'pt'} + + # Parse repo with sharded model + >>> metadata = get_safetensors_metadata("bigscience/bloom") + Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s] + >>> metadata + SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...}) + >>> len(metadata.files_metadata) + 72 # All safetensors files have been fetched + + # Parse repo with sharded model + >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5") + NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files. + ``` + """ + if self.file_exists( # Single safetensors file => non-sharded model + repo_id=repo_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ): + file_metadata = self.parse_safetensors_file_metadata( + repo_id=repo_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + repo_type=repo_type, + revision=revision, + token=token, + timeout=timeout, + ) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={ + tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys() + }, + files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata}, + ) + elif self.file_exists( # Multiple safetensors files => sharded with index + repo_id=repo_id, + filename=constants.SAFETENSORS_INDEX_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ): + # Fetch index + index_file = self.hf_hub_download( + repo_id=repo_id, + filename=constants.SAFETENSORS_INDEX_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ) + with open(index_file) as f: + index = json.load(f) + + weight_map = index.get("weight_map", {}) + + # Fetch metadata per shard + files_metadata = {} + + def _parse(filename: str) -> None: + files_metadata[filename] = self.parse_safetensors_file_metadata( + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + token=token, + timeout=timeout, + ) + + hf_thread_map( + _parse, + set(weight_map.values()), + desc="Parse safetensors files", + tqdm_class=hf_tqdm, + ) + + return SafetensorsRepoMetadata( + metadata=index.get("metadata", None), + sharded=True, + weight_map=weight_map, + files_metadata=files_metadata, + ) + else: + # Not a safetensors repo + raise NotASafetensorsRepoError( + f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files." + ) + + def parse_safetensors_file_metadata( + self, + repo_id: str, + filename: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + timeout: float | None = constants.HF_HUB_DOWNLOAD_TIMEOUT, + ) -> SafetensorsFileMetadata: + """ + Parse metadata from a safetensors file on the Hub. + + To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send data before giving up. Set to `None` to disable the + timeout (not recommended, as a stalled connection can hang the call indefinitely). + + Returns: + [`SafetensorsFileMetadata`]: information related to a safetensors file. + + Raises: + [`NotASafetensorsRepoError`]: + If the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + [`SafetensorsParsingError`]: + If a safetensors file header couldn't be parsed correctly. + """ + url = hf_hub_url( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint + ) + _headers = self._build_hf_headers(token=token) + + context_msg = f"repo '{repo_id}', revision '{revision or constants.DEFAULT_REVISION}'" + + # 1. Fetch first 100kb + # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub). + # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to + # avoid the 2nd GET in most cases. + # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419. + response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"}, timeout=timeout) + hf_raise_for_status(response) + + # 2. Parse and validate metadata size using shared helper + metadata_size = _get_safetensors_metadata_size(response.content[:8], filename, context_msg) + + # 3.a. Get metadata from payload, if fully contained in the response (minus the 8-byte size prefix) + if metadata_size <= len(response.content) - 8: + metadata_as_bytes = response.content[8 : 8 + metadata_size] + else: # 3.b. Request full metadata + response = get_session().get( + url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"}, timeout=timeout + ) + hf_raise_for_status(response) + metadata_as_bytes = response.content + + # 4. Parse json header using shared helper + return _parse_safetensors_header(metadata_as_bytes, filename, context_msg) + + @validate_hf_hub_args + def create_branch( + self, + repo_id: str, + *, + branch: str, + revision: str | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + ) -> None: + """ + Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`). + To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`]. + + Args: + repo_id (`str`): + The repository in which the branch will be created. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to create. + + revision (`str`, *optional*): + The git revision to create the branch from. It can be a branch name or + the OID/SHA of a commit, as a hexadecimal string. Defaults to the head + of the `"main"` branch. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if branch already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.BadRequestError`]: + If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + payload = {} + if revision is not None: + payload["startingPoint"] = revision + + # Create branch + response = get_session().post(url=branch_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if exist_ok and e.response.status_code == 409: + return + elif exist_ok and e.response.status_code == 403: + # No write permission on the namespace but branch might already exist + try: + refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token) + for branch_ref in refs.branches: + if branch_ref.name == branch: + return # Branch already exists => do not raise + except HfHubHTTPError: + pass # We raise the original error if the branch does not exist + raise + + @validate_hf_hub_args + def delete_branch( + self, + repo_id: str, + *, + branch: str, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Delete a branch from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a branch will be deleted. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to delete. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.HfHubHTTPError`]: + If trying to delete a protected branch. Ex: `main` cannot be deleted. + [`~utils.HfHubHTTPError`]: + If trying to delete a branch that does not exist. + + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + + # Delete branch + response = get_session().delete(url=branch_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def create_tag( + self, + repo_id: str, + *, + tag: str, + tag_message: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + ) -> None: + """ + Tag a given commit of a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a commit will be tagged. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to create. + + tag_message (`str`, *optional*): + The description of the tag to create. + + revision (`str`, *optional*): + The git revision to tag. It can be a branch name or the OID/SHA of a + commit, as a hexadecimal string. Shorthands (7 first characters) are + also supported. Defaults to the head of the `"main"` branch. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or + space, `None` or `"model"` if tagging a model. Default is + `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if tag already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}" + headers = self._build_hf_headers(token=token) + payload = {"tag": tag} + if tag_message is not None: + payload["message"] = tag_message + + # Tag + response = get_session().post(url=tag_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if not (e.response.status_code == 409 and exist_ok): + raise + + @validate_hf_hub_args + def delete_tag( + self, + repo_id: str, + *, + tag: str, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Delete a tag from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a tag will be deleted. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to delete. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or + `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If tag is not found. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + tag = quote(tag, safe="") + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}" + headers = self._build_hf_headers(token=token) + + # Un-tag + response = get_session().delete(url=tag_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def get_full_repo_name( + self, + model_id: str, + *, + organization: str | None = None, + token: bool | str | None = None, + ): + """ + Returns the repository name for a given model ID and optional + organization. + + Args: + model_id (`str`): + The name of the model. + organization (`str`, *optional*): + If passed, the repository name will be in the organization + namespace instead of the user namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `str`: The repository name in the user's namespace + ({username}/{model_id}) if no organization is passed, and under the + organization namespace ({organization}/{model_id}) otherwise. + """ + if organization is None: + if "/" in model_id: + username = model_id.split("/")[0] + else: + username = self.whoami(token=token)["name"] # type: ignore + return f"{username}/{model_id}" + else: + return f"{organization}/{model_id}" + + @validate_hf_hub_args + def get_repo_discussions( + self, + repo_id: str, + *, + author: str | None = None, + discussion_type: constants.DiscussionTypeFilter | None = None, + discussion_status: constants.DiscussionStatusFilter | None = None, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterator[Discussion]: + """ + Fetches Discussions and Pull Requests for the given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + author (`str`, *optional*): + Pass a value to filter by discussion author. `None` means no filter. + Default is `None`. + discussion_type (`str`, *optional*): + Set to `"pull_request"` to fetch only pull requests, `"discussion"` + to fetch only discussions. Set to `"all"` or `None` to fetch both. + Default is `None`. + discussion_status (`str`, *optional*): + Set to `"open"` (respectively `"closed"`) to fetch only open + (respectively closed) discussions. Set to `"all"` or `None` + to fetch both. + Default is `None`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if fetching from a dataset or + space, `None` or `"model"` if fetching from a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterator[Discussion]`: An iterator of [`Discussion`] objects. + + Example: + Collecting all discussions of a repo in a list: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased")) + ``` + + Iterating over discussions of a repo: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"): + ... print(discussion.num, discussion.title) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES: + raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}") + if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS: + raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}") + + headers = self._build_hf_headers(token=token) + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions" + + params: dict[str, str | int] = {} + if discussion_type is not None: + params["type"] = discussion_type + if discussion_status is not None: + params["status"] = discussion_status + if author is not None: + params["author"] = author + + def _fetch_discussion_page(page_index: int): + params["p"] = page_index + resp = get_session().get(path, headers=headers, params=params) + hf_raise_for_status(resp) + paginated_discussions = resp.json() + total = paginated_discussions["count"] + start = paginated_discussions["start"] + discussions = paginated_discussions["discussions"] + has_next = (start + len(discussions)) < total + return discussions, has_next + + has_next, page_index = True, 0 + + while has_next: + discussions, has_next = _fetch_discussion_page(page_index=page_index) + for discussion in discussions: + yield Discussion( + title=discussion["title"], + num=discussion["num"], + author=discussion.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion["createdAt"]), + status=discussion["status"], + repo_id=discussion["repo"]["name"], + repo_type=discussion["repo"]["type"], + is_pull_request=discussion["isPullRequest"], + endpoint=self.endpoint, + ) + page_index = page_index + 1 + + @validate_hf_hub_args + def get_discussion_details( + self, + repo_id: str, + discussion_num: int, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> DiscussionWithDetails: + """Fetches a Discussion's / Pull Request 's details from the Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}" + headers = self._build_hf_headers(token=token) + resp = get_session().get(path, params={"diff": "1"}, headers=headers) + hf_raise_for_status(resp) + + discussion_details = resp.json() + is_pull_request = discussion_details["isPullRequest"] + + target_branch = discussion_details["changes"]["base"] if is_pull_request else None + conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None + merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None + + return DiscussionWithDetails( + title=discussion_details["title"], + num=discussion_details["num"], + author=discussion_details.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion_details["createdAt"]), + status=discussion_details["status"], + repo_id=discussion_details["repo"]["name"], + repo_type=discussion_details["repo"]["type"], + is_pull_request=discussion_details["isPullRequest"], + events=[deserialize_event(evt) for evt in discussion_details["events"]], + conflicting_files=conflicting_files, + target_branch=target_branch, + merge_commit_oid=merge_commit_oid, + diff=discussion_details.get("diff"), + endpoint=self.endpoint, + ) + + @validate_hf_hub_args + def create_discussion( + self, + repo_id: str, + title: str, + *, + token: bool | str | None = None, + description: str | None = None, + repo_type: str | None = None, + pull_request: bool = False, + ) -> DiscussionWithDetails: + """Creates a Discussion or Pull Request. + + Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + pull_request (`bool`, *optional*): + Whether to create a Pull Request or discussion. If `True`, creates a Pull Request. + If `False`, creates a discussion. Defaults to `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access.""" + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + if description is not None: + description = description.strip() + description = ( + description + if description + else ( + f"{'Pull Request' if pull_request else 'Discussion'} opened with the" + " [huggingface_hub Python" + " library](https://huggingface.co/docs/huggingface_hub)" + ) + ) + + headers = self._build_hf_headers(token=token) + resp = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions", + json={ + "title": title.strip(), + "description": description, + "pullRequest": pull_request, + }, + headers=headers, + ) + hf_raise_for_status(resp) + num = resp.json()["num"] + return self.get_discussion_details( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=num, + token=token, + ) + + @validate_hf_hub_args + def create_pull_request( + self, + repo_id: str, + title: str, + *, + token: bool | str | None = None, + description: str | None = None, + repo_type: str | None = None, + ) -> DiscussionWithDetails: + """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]; + + This is a wrapper around [`HfApi.create_discussion`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access.""" + return self.create_discussion( + repo_id=repo_id, + title=title, + token=token, + description=description, + repo_type=repo_type, + pull_request=True, + ) + + def _post_discussion_changes( + self, + *, + repo_id: str, + discussion_num: int, + resource: str, + body: dict | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> httpx.Response: + """Internal utility to POST changes to a Discussion or Pull Request""" + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + repo_id = f"{repo_type}s/{repo_id}" + + path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}" + + headers = self._build_hf_headers(token=token) + resp = get_session().post(path, headers=headers, json=body) + hf_raise_for_status(resp) + return resp + + @validate_hf_hub_args + def comment_discussion( + self, + repo_id: str, + discussion_num: int, + comment: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Creates a new comment on the given Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`): + The content of the comment to create. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the newly created comment + + + Examples: + ```python + + >>> comment = \"\"\" + ... Hello @otheruser! + ... + ... # This is a title + ... + ... **This is bold**, *this is italic* and ~this is strikethrough~ + ... And [this](http://url) is a link + ... \"\"\" + + >>> HfApi().comment_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... comment=comment + ... ) + # DiscussionComment(id='deadbeef0000000', type='comment', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="comment", + body={"comment": comment}, + ) + return deserialize_event(resp.json()["newMessage"]) # type: ignore + + @validate_hf_hub_args + def rename_discussion( + self, + repo_id: str, + discussion_num: int, + new_title: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionTitleChange: + """Renames a Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_title (`str`): + The new title for the discussion + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionTitleChange`]: the title change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="title", + body={"title": new_title}, + ) + return deserialize_event(resp.json()["newTitle"]) # type: ignore + + @validate_hf_hub_args + def change_discussion_status( + self, + repo_id: str, + discussion_num: int, + new_status: Literal["open", "closed"], + *, + token: bool | str | None = None, + comment: str | None = None, + repo_type: str | None = None, + ) -> DiscussionStatusChange: + """Closes or re-opens a Discussion or Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_status (`str`): + The new status for the discussion, either `"open"` or `"closed"`. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionStatusChange`]: the status change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if new_status not in ["open", "closed"]: + raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'") + body: dict[str, str] = {"status": new_status} + if comment and comment.strip(): + body["comment"] = comment.strip() + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="status", + body=body, + ) + return deserialize_event(resp.json()["newStatus"]) # type: ignore + + @validate_hf_hub_args + def merge_pull_request( + self, + repo_id: str, + discussion_num: int, + *, + token: bool | str | None = None, + comment: str | None = None, + repo_type: str | None = None, + ): + """Merges a Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionStatusChange`]: the status change event + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="merge", + body={"comment": comment.strip()} if comment and comment.strip() else None, + ) + + @validate_hf_hub_args + def edit_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + new_content: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Edits a comment on a Discussion / Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + new_content (`str`): + The new content of the comment. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the edited comment + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/edit", + body={"content": new_content}, + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def hide_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Hides a comment on a Discussion / Pull Request. + + > [!WARNING] + > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the hidden comment + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + warnings.warn( + "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.", + UserWarning, + ) + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/hide", + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def add_space_secret( + self, + repo_id: str, + key: str, + value: str, + *, + description: str | None = None, + token: bool | str | None = None, + ) -> None: + """Adds or updates a secret in a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"` + value (`str`): + Secret value. Example: `"your_github_api_key"`. + description (`str`, *optional*): + Secret description. Example: `"Github API key to access the Github API"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def delete_space_secret(self, repo_id: str, key: str, *, token: bool | str | None = None) -> None: + """Deletes a secret from a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().request( + "DELETE", + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def get_space_secrets(self, repo_id: str, *, token: bool | str | None = None) -> dict[str, SpaceSecret]: + """Gets all secrets from a Space. + + Secret values are write-only and cannot be read back. Only the key, description, and last update time + are returned. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to query. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `dict[str, SpaceSecret]`: Dictionary of [`SpaceSecret`] objects keyed by secret name. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.get_space_secrets("username/my-space") + {'HF_TOKEN': SpaceSecret(key='HF_TOKEN', description='...', updated_at=datetime.datetime(...))} + ``` + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return {k: SpaceSecret(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def get_space_variables(self, repo_id: str, *, token: bool | str | None = None) -> dict[str, SpaceVariable]: + """Gets all variables from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to query. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def add_space_variable( + self, + repo_id: str, + key: str, + value: str, + *, + description: str | None = None, + token: bool | str | None = None, + ) -> dict[str, SpaceVariable]: + """Adds or updates a variable in a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + value (`str`): + Variable value. Example: `"the_model_repo_id"`. + description (`str`): + Description of the variable. Example: `"Model Repo ID of the implemented model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def delete_space_variable( + self, repo_id: str, key: str, *, token: bool | str | None = None + ) -> dict[str, SpaceVariable]: + """Deletes a variable from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().request( + "DELETE", + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def get_space_runtime(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Gets runtime information about a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + def list_spaces_hardware(self, token: bool | str | None = None) -> list[JobHardwareInfo]: + """List available hardware options for Spaces. + + Returns: + `list[JobHardwareInfo]`: A list of available hardware configurations. + + Example: + + ```python + >>> from huggingface_hub import list_spaces_hardware + >>> hardware_list = list_spaces_hardware() + >>> hardware_list[0] + JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ...) + >>> hardware_list[0].name + 'cpu-basic' + ``` + """ + response = get_session().get( + f"{self.endpoint}/api/spaces/hardware", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(response) + return [JobHardwareInfo(**hardware) for hardware in response.json()] + + @validate_hf_hub_args + def request_space_hardware( + self, + repo_id: str, + hardware: SpaceHardware, + *, + token: bool | str | None = None, + sleep_time: int | None = None, + ) -> SpaceRuntime: + """Request new hardware for a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + hardware (`str` or [`SpaceHardware`]): + Hardware on which to run the Space. Example: `"t4-medium"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + > [!TIP] + > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details. + """ + if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + payload: dict[str, Any] = {"flavor": hardware} + if sleep_time is not None: + payload["sleepTimeSeconds"] = sleep_time + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/hardware", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def set_space_sleep_time(self, repo_id: str, sleep_time: int, *, token: bool | str | None = None) -> SpaceRuntime: + """Set a custom sleep time for a Space running on upgraded hardware.. + + Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep" + mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a + configurable sleep time. To know more about the sleep stage, please refer to + https://huggingface.co/docs/hub/spaces-gpus#sleep-time. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + > [!TIP] + > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`]. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/sleeptime", + headers=self._build_hf_headers(token=token), + json={"seconds": sleep_time}, + ) + hf_raise_for_status(r) + runtime = SpaceRuntime(r.json()) + + hardware = runtime.requested_hardware or runtime.hardware + if hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + return runtime + + @validate_hf_hub_args + def pause_space(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Pause your Space. + + A paused Space stops executing until manually restarted by its owner. This is different from the sleeping + state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the + hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to pause. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def enable_space_dev_mode(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Enable dev mode on a Space. + + Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you + to restart your application without stopping the Space container itself. This feature is available as part of + a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details. + + Args: + repo_id (`str`): + ID of the Space to enable dev mode. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/dev-mode", + headers=self._build_hf_headers(token=token), + json={"enabled": True}, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def disable_space_dev_mode( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Disable dev mode on a Space. + + Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you + to restart your application without stopping the Space container itself. This feature is available as part of + a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details. + + Args: + repo_id (`str`): + ID of the Space to disable dev mode. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/dev-mode", + headers=self._build_hf_headers(token=token), + json={"enabled": False}, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def restart_space( + self, repo_id: str, *, token: bool | str | None = None, factory_reboot: bool = False + ) -> SpaceRuntime: + """Restart your Space. + + This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You + must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be + billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to restart. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + factory_reboot (`bool`, *optional*): + If `True`, the Space will be rebuilt from scratch without caching any requirements. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + params = {} + if factory_reboot: + params["factory"] = "true" + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + def _stream_sse_events( + self, + *, + url: str, + log_label: str, + timeout: int, + follow: bool, + token: bool | str | None = None, + skip_previous_events_on_retry: bool = True, + tolerated_status_codes: tuple[int, ...] = (), + tolerated_exception_types: tuple[type[Exception], ...] = (), + on_iteration_end: Callable[[], bool] | None = None, + params: dict[str, Any] | None = None, + ) -> Iterable[dict[str, Any]]: + # Shared SSE streaming loop with retry/backoff and event-index dedup. + # Used by Spaces logs and Jobs logs/metrics. Two retry styles: + # - on_iteration_end is None: retries are the only backstop (Spaces). + # - on_iteration_end is set: it polls authoritative state after every + # failed iteration; ReadTimeouts/tolerated errors fall through to it + # instead of consuming retries (Jobs). + nb_tries = 0 + max_retries = 5 if follow else 0 + min_wait_time = 1 + max_wait_time = 10 + sleep_time = 0 + start_event_idx = 0 + error_to_retry: Exception | None = None + while True: + if error_to_retry is not None: + logger.warning(f"'{error_to_retry}' thrown while requesting {log_label}") + logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].") + error_to_retry = None + time.sleep(sleep_time) + try: + with get_session().stream( + "GET", + url, + headers=self._build_hf_headers(token=token), + timeout=timeout, + params=params, + ) as response: + if response.status_code == 200: + event_idx = -1 + for line in response.iter_lines(): + if line and line.startswith("data: {"): + event_idx += 1 + if event_idx >= start_event_idx: + if skip_previous_events_on_retry: + start_event_idx += 1 + yield json.loads(line[len("data: ") :]) + break + elif response.status_code not in tolerated_status_codes: + hf_raise_for_status(response) + except HfHubHTTPError: + # Permanent HTTP error (404/403/...). Never retry — fail fast. + raise + except httpx.DecodingError: + # Response ended prematurely. + break + except KeyboardInterrupt: + break + except (httpx.HTTPError, httpcore.TimeoutException) as err: + is_no_new_line_timeout = isinstance(err, (httpx.ReadTimeout, httpcore.ReadTimeout)) + if is_no_new_line_timeout and not follow: + break # no-follow: timeout means the buffer is drained + if on_iteration_end is not None: + # Authoritative-state mode: ReadTimeouts and tolerated errors + # fall through to the post-iteration check without consuming + # retries. Note: ReadTimeout is handled here regardless of + # `tolerated_exception_types` — entries in that tuple only + # fire for non-timeout errors. + if is_no_new_line_timeout or type(err) in tolerated_exception_types: + pass + elif nb_tries >= max_retries: + raise + else: + nb_tries += 1 + sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2)) + error_to_retry = err + else: + # Retry-only mode: every error in follow mode burns a retry. + if nb_tries >= max_retries: + if is_no_new_line_timeout: + break # follow mode, silent stream, retries exhausted: give up + raise + nb_tries += 1 + sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2)) + error_to_retry = err + # Drop params after the first attempt: the start_event_idx dedup + # requires a stable replay prefix, which `tail` would break. + params = None + if on_iteration_end is not None and on_iteration_end(): + break + + def _fetch_space_logs_sse( + self, + *, + repo_id: str, + build: bool, + timeout: int, + follow: bool, + token: bool | str | None = None, + ) -> Iterable[dict[str, Any]]: + log_type = "build" if build else "run" + yield from self._stream_sse_events( + url=f"{self.endpoint}/api/spaces/{repo_id}/logs/{log_type}", + log_label=f"spaces /logs/{log_type} for repo_id={repo_id!r}", + timeout=timeout, + follow=follow, + token=token, + ) + + @validate_hf_hub_args + def fetch_space_logs( + self, + repo_id: str, + *, + build: bool = False, + follow: bool = False, + token: bool | str | None = None, + ) -> Iterable[str]: + """Fetch the run or build logs of a Space on the Hub. + + Useful for debugging a Space that is failing to build or crashing at runtime, + especially from a script or agentic workflow where reading logs in a browser + is not an option. + + Args: + repo_id (`str`): + ID of the Space. Example: `"bigcode/in-the-stack"`. + build (`bool`, *optional*, defaults to `False`): + If `True`, fetch the container build logs (useful when a Space is stuck + in `BUILD_ERROR`). If `False` (default), fetch the run logs, i.e. the + stdout/stderr of the running application. + follow (`bool`, *optional*, defaults to `False`): + If `True`, stream logs in real-time (blocking) until the server closes + the stream or `KeyboardInterrupt` is raised. If `False` (default), fetch + only the currently buffered logs and return immediately (non-blocking, + like `docker logs`). + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved token, which is + the recommended authentication method. Set to `False` to disable + authentication. See + https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + `Iterable[str]`: A generator yielding log lines as they become available. + + Example: + + ```python + >>> from huggingface_hub import fetch_space_logs + >>> # Non-blocking: print currently available run logs and exit. + >>> for line in fetch_space_logs("username/my-space"): + ... print(line, end="") + + >>> # Debug a build failure: + >>> for line in fetch_space_logs("username/my-space", build=True): + ... print(line, end="") + + >>> # Stream run logs until the server closes the stream. + >>> for line in fetch_space_logs("username/my-space", follow=True): + ... print(line, end="") + ``` + """ + # - Spaces /logs/{run|build} is SSE with `data: {"data": "...", "timestamp": "..."}` events. + # - Keep-alive messages are sent as empty `data:` events (skipped by the `data: {` filter). + # - In no-follow mode we use a short read timeout to drain the buffer and return. + timeout = 120 if follow else 5 + for event in self._fetch_space_logs_sse( + repo_id=repo_id, + build=build, + timeout=timeout, + follow=follow, + token=token, + ): + yield event["data"] + + @validate_hf_hub_args + def wait_for_space( + self, + repo_id: str, + *, + timeout: float | None = None, + poll_interval: float = 1.0, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Wait until a Space reaches a terminal stage (not building/starting). + + Polls [`get_space_runtime`] every `poll_interval` seconds until the Space's stage + is no longer intermediate (`BUILDING`, `RUNNING_BUILDING`, `APP_STARTING`, + `RUNNING_APP_STARTING`). Returns the final [`SpaceRuntime`] in all cases — check + `runtime.stage` to act on the outcome (e.g. `RUNNING` vs `BUILD_ERROR`). + + Args: + repo_id (`str`): + ID of the Space to wait for. Example: `"username/my-space"`. + timeout (`float`, *optional*): + Maximum time to wait in seconds. If `None`, waits indefinitely. + poll_interval (`float`, *optional*): + Seconds between status checks. Defaults to 1s. + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved token, which is the + recommended authentication method. Set to `False` to disable authentication. + See https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`SpaceRuntime`]: The final runtime information once the Space reaches a terminal stage. + + Raises: + `TimeoutError`: + If the Space has not reached a terminal stage after `timeout` seconds. + + Example: + + ```python + >>> from huggingface_hub import restart_space, wait_for_space + >>> restart_space("username/my-space") + >>> runtime = wait_for_space("username/my-space") + >>> runtime.stage + 'RUNNING' + ``` + """ + if timeout is not None and timeout < 0: + raise ValueError("`timeout` cannot be negative.") + if poll_interval <= 0: + raise ValueError("`poll_interval` must be positive.") + + deadline = None if timeout is None else time.monotonic() + timeout + while True: + runtime = self.get_space_runtime(repo_id, token=token) + if runtime.stage not in INTERMEDIATE_SPACE_STAGES: + return runtime + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and remaining <= 0: + raise TimeoutError(f"Space '{repo_id}' is still in stage '{runtime.stage}' after {timeout} seconds.") + time.sleep(poll_interval if remaining is None else min(poll_interval, remaining)) + + @_deprecate_arguments( + version="2.0", + deprecated_args={"space_storage"}, + custom_message="Use `space_volumes` to mount volumes on a Space.", + ) + @validate_hf_hub_args + def duplicate_repo( + self, + from_id: str, + to_id: str | None = None, + *, + repo_type: str | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: bool | str | None = None, + exist_ok: bool = False, + space_hardware: SpaceHardware | None = None, + space_storage: SpaceStorage | None = None, + space_sleep_time: int | None = None, + space_secrets: list[dict[str, str]] | None = None, + space_variables: list[dict[str, str]] | None = None, + space_volumes: list[Volume] | None = None, + ) -> RepoUrl: + """Duplicate a repo on the Hub (model, dataset, or Space). + + This performs a server-side copy that preserves full git history and LFS objects + without requiring a local download/upload round-trip. + + Args: + from_id (`str`): + ID of the repo to duplicate. Example: `"openai/gdpval"`. + to_id (`str`, *optional*): + ID of the new repo. Example: `"myorg/my-gdpval"`. If not provided, the new + repo will have the same name as the original repo, but in your account. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if duplicating a dataset or Space, + `None` or `"model"` if duplicating a model. Default is `None`. + private (`bool`, *optional*): + Whether the new repo should be private or not. Defaults to the same + privacy as the original repo. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the new repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. Defaults + to the same visibility as the original repo. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + space_hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware if repo_type is "space". Example: `"t4-medium"`. See + [`SpaceHardware`] for a complete list. + space_storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier if repo_type is "space". Example: + `"small"`. See [`SpaceStorage`] for a complete list. + space_sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. + Set to `-1` if you don't want your Space to sleep (default behavior for + upgraded hardware). For free hardware, you can't configure the sleep time + (value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space". + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + space_secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form + `{"key": ..., "value": ..., "description": ...}` where description is optional. + Only applicable if repo_type is "space". + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + space_variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in + the form `{"key": ..., "value": ..., "description": ...}` where description + is optional. Only applicable if repo_type is "space". + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + space_volumes (`list[Volume]`, *optional*): + A list of [`Volume`] objects to mount in the Space at duplication time. Each volume has a `type` + (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path` + (path inside the container), and optional `revision`, `read_only`, and `path` fields. + Only applicable if repo_type is "space". + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`HfHubHTTPError`]: + If the HuggingFace API returned an error + + Example: + ```python + >>> from huggingface_hub import duplicate_repo + + # Duplicate a model to your account + >>> duplicate_repo("google/gemma-7b") + RepoUrl('https://huggingface.co/nateraw/gemma-7b',...) + + # Duplicate a dataset with a custom name + >>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset") + RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...) + + # Duplicate a Space with custom hardware + >>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium") + RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError("Invalid repo type") + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + # Map repo_type to API path segment + api_prefix = { + None: "models", + constants.REPO_TYPE_MODEL: "models", + constants.REPO_TYPE_DATASET: "datasets", + constants.REPO_TYPE_SPACE: "spaces", + }[repo_type] + + # Resolve the target namespace + name. When 'to_id' is provided we take the name from it, + # otherwise we reuse the source name. Both may be a URL, an 'hf://' URI, or a bare id, so we + # try 'parse_hf_uri' first and fall back to a plain split ('/', or just + # '' for 'to_id'). A missing namespace defaults to the caller's account. + to_namespace: str | None = None + if to_id is not None: + try: + to_namespace, to_repo_name = parse_hf_uri(to_id).id.split("/") + except HfUriError: + namespace_and_name = to_id.rsplit("/", 1) + to_namespace = namespace_and_name[0] if len(namespace_and_name) == 2 else None + to_repo_name = namespace_and_name[-1] + else: + try: + to_repo_name = parse_hf_uri(from_id).id.split("/")[1] + except HfUriError: + to_repo_name = from_id.rsplit("/", 1)[-1] + if to_namespace is None: + to_namespace = self.whoami(token)["name"] + + payload: dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"} + + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + + # Space-specific options + space_args: list[tuple[str, str, Any]] = [ + # input arg, payload key, value + ("space_hardware", "hardware", space_hardware), + ("space_storage", "storageTier", space_storage), + ("space_sleep_time", "sleepTimeSeconds", space_sleep_time), + ("space_secrets", "secrets", space_secrets), + ("space_variables", "variables", space_variables), + ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None), + ] + + if repo_type == "space": + for _, key, value in space_args: + if value is not None: + payload[key] = value + if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + else: + if provided_space_args := [arg for arg, _, value in space_args if value is not None]: + warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.") + + r = get_session().post( + f"{self.endpoint}/api/{api_prefix}/{from_id}/duplicate", + headers=self._build_hf_headers(token=token), + json=payload, + ) + + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + pass + else: + raise + + return RepoUrl(r.json()["url"], endpoint=self.endpoint) + + @_deprecate_method(version="2.0", message="Use `duplicate_repo` instead.") + @validate_hf_hub_args + def duplicate_space( + self, + from_id: str, + to_id: str | None = None, + *, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: bool | str | None = None, + exist_ok: bool = False, + hardware: SpaceHardware | None = None, + storage: SpaceStorage | None = None, + sleep_time: int | None = None, + secrets: list[dict[str, str]] | None = None, + variables: list[dict[str, str]] | None = None, + ) -> RepoUrl: + """Duplicate a Space. + + Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state + as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space. + + Args: + from_id (`str`): + ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`. + to_id (`str`, *optional*): + ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same + name as the original Space, but in your account. + private (`bool`, *optional*): + Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the new Space. Can be `"public"`, `"private"`, or `"protected"`. Defaults to the same + visibility as the original Space. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list. + storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`HfHubHTTPError`]: + If the HuggingFace API returned an error + + Example: + ```python + >>> from huggingface_hub import duplicate_space + + # Duplicate a Space to your account + >>> duplicate_space("multimodalart/dreambooth-training") + RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...) + + # Can set custom destination id and visibility flag. + >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private") + RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...) + ``` + + > [!WARNING] + > `duplicate_space` is deprecated and will be removed in version 2.0. Use [`~HfApi.duplicate_repo`] instead. + """ + kwargs: dict[str, Any] = {} + if to_id is not None: + kwargs["to_id"] = to_id + return self.duplicate_repo( + from_id=from_id, + repo_type="space", + private=private, + visibility=visibility, + token=token, + exist_ok=exist_ok, + space_hardware=hardware, + space_storage=storage, + space_sleep_time=sleep_time, + space_secrets=secrets, + space_variables=variables, + **kwargs, + ) + + @_deprecate_method(version="2.0", message="Use `set_space_volumes` instead.") + @validate_hf_hub_args + def request_space_storage( + self, + repo_id: str, + storage: SpaceStorage, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Request persistent storage for a Space. + + > [!WARNING] + > `request_space_storage` is deprecated and will be removed in version 2.0. Use [`set_space_volumes`] instead. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`. + storage (`str` or [`SpaceStorage`]): + Storage tier. Either 'small', 'medium', or 'large'. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + """ + payload: dict[str, SpaceStorage] = {"tier": storage} + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @_deprecate_method(version="2.0", message="Use `delete_space_volumes` instead.") + @validate_hf_hub_args + def delete_space_storage( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Delete persistent storage for a Space. + + > [!WARNING] + > `delete_space_storage` is deprecated and will be removed in version 2.0. Use [`delete_space_volumes`] instead. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + Raises: + [`BadRequestError`] + If space has no persistent storage. + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def set_space_volumes( + self, + repo_id: str, + volumes: list[Volume], + *, + token: bool | str | None = None, + ) -> None: + """Set volumes for a Space. + + Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access + to a Hub resource (model, dataset, or storage bucket). + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"username/my-space"`. + volumes (`list[Volume]`): + List of [`Volume`] objects to mount. Each volume has a `type` (`"bucket"`, `"model"`, `"dataset"`, or + `"space"`), a `source` (repo or bucket ID), a `mount_path` (path inside the container), and optional + `revision`, `read_only`, and `path` fields. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`BadRequestError`]: + If the Space is a static Space (volumes are not supported on static Spaces). + + Example: + ```python + >>> from huggingface_hub import HfApi, Volume + >>> api = HfApi() + >>> api.set_space_volumes( + ... "username/my-space", + ... volumes=[ + ... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True), + ... Volume(type="bucket", source="username/my-bucket", mount_path="/data"), + ... ], + ... ) + ``` + """ + payload = {"volumes": [vol.to_dict() for vol in volumes]} + r = get_session().put( + f"{self.endpoint}/api/spaces/{repo_id}/volumes", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def delete_space_volumes( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> None: + """Remove all volumes from a Space. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"username/my-space"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`BadRequestError`]: + If the Space has no volumes attached. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.delete_space_volumes("username/my-space") + ``` + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/volumes", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + + ####################### + # Inference Endpoints # + ####################### + + def list_inference_endpoints( + self, namespace: str | None = None, *, token: bool | str | None = None + ) -> list[InferenceEndpoint]: + """Lists all inference endpoints for the given namespace. + + Args: + namespace (`str`, *optional*): + The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints + from all namespaces (i.e. personal namespace and all orgs the user belongs to). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_inference_endpoints() + [InferenceEndpoint(name='my-endpoint', ...), ...] + ``` + """ + # Special case: list all endpoints for all namespaces the user has access to + if namespace == "*": + user = self.whoami(token=token) + + # List personal endpoints first + endpoints: list[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token)) + + # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access) + for org in user.get("orgs", []): + try: + endpoints += list_inference_endpoints(namespace=org["name"], token=token) + except HfHubHTTPError as error: + if error.response.status_code == 401: # Either no billing or user don't have access) + logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error) + pass + + return endpoints + + # Normal case: list endpoints for a specific namespace + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return [ + InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token) + for endpoint in response.json()["items"] + ] + + def create_inference_endpoint( + self, + name: str, + *, + repository: str, + framework: str, + accelerator: str, + instance_size: str, + instance_type: str, + region: str, + vendor: str, + account_id: str | None = None, + min_replica: int = 1, + max_replica: int = 1, + scaling_metric: InferenceEndpointScalingMetric | None = None, + scaling_threshold: float | None = None, + scale_to_zero_timeout: int | None = None, + revision: str | None = None, + task: str | None = None, + custom_image: dict | None = None, + container_command: list[str] | None = None, + container_args: list[str] | None = None, + env: dict[str, str] | None = None, + secrets: dict[str, str] | None = None, + type: InferenceEndpointType | str = InferenceEndpointType.AUTHENTICATED, + domain: str | None = None, + path: str | None = None, + cache_http_responses: bool | None = None, + tags: list[str] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Create a new Inference Endpoint. + + Args: + name (`str`): + The unique name for the new Inference Endpoint. + repository (`str`): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`): + The machine learning framework used for the model (e.g. `"custom"`). + accelerator (`str`): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`): + The size or type of the instance to be used for hosting the model (e.g. `"x4"`). + instance_type (`str`): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). + region (`str`): + The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`). + vendor (`str`): + The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`). + account_id (`str`, *optional*): + The account ID used to link a VPC to a private Inference Endpoint (if applicable). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable + scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1. + scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*): + The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to + None (meaning: let the HF Endpoints service specify the metric). + scaling_threshold (`float`, *optional*): + The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. + Defaults to None (meaning: let the HF Endpoints service specify the threshold). + scale_to_zero_timeout (`int`, *optional*): + The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if + set to None and `min_replica` is not 0. Defaults to None. + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework or a custom container + (see examples). + container_command (`list[str]`, *optional*): + Override the container entrypoint command (maps to `model.command` in the API payload). Typically + used together with `custom_image`. + container_args (`list[str]`, *optional*): + Arguments appended to the container entrypoint (maps to `model.args` in the API payload). Typically + used together with `custom_image` to pass runtime flags to the container. + env (`dict[str, str]`, *optional*): + Non-secret environment variables to inject in the container environment. + secrets (`dict[str, str]`, *optional*): + Secret values to inject in the container environment. + type ([`InferenceEndpointType]`, *optional*): + The type of the Inference Endpoint, which can be `"authenticated"` (default), `"public"` or + `"private"`. `"protected"` is deprecated in favor of `"authenticated"` and will be removed in a + future release. + domain (`str`, *optional*): + The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`). + path (`str`, *optional*): + The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`). + cache_http_responses (`bool`, *optional*): + Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`. + tags (`list[str]`, *optional*): + A list of tags to associate with the Inference Endpoint. + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "my-endpoint-name", + ... repository="gpt2", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="cpu", + ... vendor="aws", + ... region="us-east-1", + ... type="authenticated", + ... instance_size="x2", + ... instance_type="intel-icl", + ... ) + >>> endpoint + InferenceEndpoint(name='my-endpoint-name', status="pending",...) + + # Run inference on the endpoint + >>> endpoint.client.text_generation(...) + "..." + ``` + + ```python + # Start an Inference Endpoint running Zephyr-7b-beta on TGI + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "aws-zephyr-7b-beta-0486", + ... repository="HuggingFaceH4/zephyr-7b-beta", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="gpu", + ... vendor="aws", + ... region="us-east-1", + ... type="authenticated", + ... instance_size="x1", + ... instance_type="nvidia-a10g", + ... env={ + ... "MAX_BATCH_PREFILL_TOKENS": "2048", + ... "MAX_INPUT_LENGTH": "1024", + ... "MAX_TOTAL_TOKENS": "1512", + ... "MODEL_ID": "/repository" + ... }, + ... custom_image={ + ... "healthRoute": "/health", + ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0", + ... }, + ... secrets={"MY_SECRET_KEY": "secret_value"}, + ... tags=["dev", "text-generation"], + ... ) + ``` + + ```python + # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "finbert-classifier", + ... repository="ProsusAI/finbert", + ... framework="pytorch", + ... task="text-classification", + ... min_replica=0, + ... scale_to_zero_timeout=15, + ... accelerator="cpu", + ... vendor="aws", + ... region="us-east-1", + ... type="authenticated", + ... instance_size="x2", + ... instance_type="intel-icl", + ... ) + >>> endpoint.wait(timeout=300) + # Run inference on the endpoint + >>> endpoint.client.text_generation(...) + TextClassificationOutputElement(label='positive', score=0.8983615040779114) + ``` + + """ + namespace = namespace or self._get_namespace(token=token) + + if type == InferenceEndpointType.PROTECTED: + warnings.warn( + "`type='protected'` is deprecated and will be removed in a future release. " + "Use `type='authenticated'` instead.", + FutureWarning, + ) + + if custom_image is not None: + image = ( + custom_image + if next(iter(custom_image)) in constants.INFERENCE_ENDPOINT_IMAGE_KEYS + else {"custom": custom_image} + ) + else: + image = {"huggingface": {}} + + payload: dict = { + "accountId": account_id, + "compute": { + "accelerator": accelerator, + "instanceSize": instance_size, + "instanceType": instance_type, + "scaling": { + "maxReplica": max_replica, + "minReplica": min_replica, + "scaleToZeroTimeout": scale_to_zero_timeout, + }, + }, + "model": { + "framework": framework, + "repository": repository, + "revision": revision, + "task": task, + "image": image, + }, + "name": name, + "provider": { + "region": region, + "vendor": vendor, + }, + "type": type, + } + if scaling_metric: + payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} # type: ignore + model_payload: dict[str, Any] = payload["model"] + if container_command is not None: + model_payload["command"] = container_command + if container_args is not None: + model_payload["args"] = container_args + if env: + payload["model"]["env"] = env + if secrets: + payload["model"]["secrets"] = secrets + if domain is not None or path is not None: + payload["route"] = {} + if domain is not None: + payload["route"]["domain"] = domain + if path is not None: + payload["route"]["path"] = path + if cache_http_responses is not None: + payload["cacheHttpResponses"] = cache_http_responses + if tags is not None: + payload["tags"] = tags + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + @experimental + @validate_hf_hub_args + def create_inference_endpoint_from_catalog( + self, + repo_id: str, + *, + name: str | None = None, + accelerator: Literal["cpu", "gpu", "neuron"] | str | None = None, + token: bool | str | None = None, + namespace: str | None = None, + ) -> InferenceEndpoint: + """Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog. + + The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference + and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list + of available models in the catalog. + + Args: + repo_id (`str`): + The ID of the model in the catalog to deploy as an Inference Endpoint. + name (`str`, *optional*): + The unique name for the new Inference Endpoint. If not provided, a random name will be generated. + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference. Possible values include `"cpu"`, `"gpu"`, and + `"neuron"`. If not provided, the server will use a default appropriate for the model. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace. + + Returns: + [`InferenceEndpoint`]: information about the new Inference Endpoint. + + > [!WARNING] + > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback + > if you have any suggestions or requests. + """ + if token is False: + raise ValueError( + "Cannot use `token=False` with `create_inference_endpoint_from_catalog` as it requires authentication." + ) + token = token or self.token or get_token() + payload: dict = { + "namespace": namespace or self._get_namespace(token=token), + "repoId": repo_id, + } + if name is not None: + payload["endpointName"] = name + if accelerator is not None: + payload["accelerator"] = accelerator + + response = get_session().post( + f"{constants.INFERENCE_CATALOG_ENDPOINT}/deploy", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + data = response.json()["endpoint"] + return InferenceEndpoint.from_raw(data, namespace=data["name"], token=token) + + @experimental + @validate_hf_hub_args + def list_inference_catalog(self, *, token: bool | str | None = None) -> list[str]: + """List models available in the Hugging Face Inference Catalog. + + The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference + and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list + of available models in the catalog. + + Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + + Returns: + List[`str`]: A list of model IDs available in the catalog. + > [!WARNING] + > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback + > if you have any suggestions or requests. + """ + response = get_session().get( + f"{constants.INFERENCE_CATALOG_ENDPOINT}/repo-list", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return response.json()["models"] + + def get_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Get information about an Inference Endpoint. + + Args: + name (`str`): + The name of the Inference Endpoint to retrieve information about. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the requested Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.get_inference_endpoint("my-text-to-image") + >>> endpoint + InferenceEndpoint(name='my-text-to-image', ...) + + # Get status + >>> endpoint.status + 'running' + >>> endpoint.url + 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' + + # Run inference + >>> endpoint.client.text_to_image(...) + ``` + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def update_inference_endpoint( + self, + name: str, + *, + # Compute update + accelerator: str | None = None, + instance_size: str | None = None, + instance_type: str | None = None, + min_replica: int | None = None, + max_replica: int | None = None, + scale_to_zero_timeout: int | None = None, + scaling_metric: InferenceEndpointScalingMetric | None = None, + scaling_threshold: float | None = None, + # Model update + repository: str | None = None, + framework: str | None = None, + revision: str | None = None, + task: str | None = None, + custom_image: dict | None = None, + env: dict[str, str] | None = None, + secrets: dict[str, str] | None = None, + # Route update + domain: str | None = None, + path: str | None = None, + # Other + cache_http_responses: bool | None = None, + tags: list[str] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Update an Inference Endpoint. + + This method allows the update of either the compute configuration, the deployed model, the route, or any combination. + All arguments are optional but at least one must be provided. + + For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`]. + + Args: + name (`str`): + The name of the Inference Endpoint to update. + + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`, *optional*): + The size or type of the instance to be used for hosting the model (e.g. `"x4"`). + instance_type (`str`, *optional*): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. + scale_to_zero_timeout (`int`, *optional*): + The duration in minutes before an inactive endpoint is scaled to zero. + scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*): + The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. + Defaults to None. + scaling_threshold (`float`, *optional*): + The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. + Defaults to None. + repository (`str`, *optional*): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`, *optional*): + The machine learning framework used for the model (e.g. `"custom"`). + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). + env (`dict[str, str]`, *optional*): + Non-secret environment variables to inject in the container environment + secrets (`dict[str, str]`, *optional*): + Secret values to inject in the container environment. + + domain (`str`, *optional*): + The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`). + path (`str`, *optional*): + The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`). + + cache_http_responses (`bool`, *optional*): + Whether to cache HTTP responses from the Inference Endpoint. + tags (`list[str]`, *optional*): + A list of tags to associate with the Inference Endpoint. + + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + # Populate only the fields that are not None + payload: dict = defaultdict(lambda: defaultdict(dict)) + if accelerator is not None: + payload["compute"]["accelerator"] = accelerator + if instance_size is not None: + payload["compute"]["instanceSize"] = instance_size + if instance_type is not None: + payload["compute"]["instanceType"] = instance_type + if max_replica is not None: + payload["compute"]["scaling"]["maxReplica"] = max_replica + if min_replica is not None: + payload["compute"]["scaling"]["minReplica"] = min_replica + if scale_to_zero_timeout is not None: + payload["compute"]["scaling"]["scaleToZeroTimeout"] = scale_to_zero_timeout + if scaling_metric: + payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} + if repository is not None: + payload["model"]["repository"] = repository + if framework is not None: + payload["model"]["framework"] = framework + if revision is not None: + payload["model"]["revision"] = revision + if task is not None: + payload["model"]["task"] = task + if custom_image is not None: + payload["model"]["image"] = {"custom": custom_image} + if env is not None: + payload["model"]["env"] = env + if secrets is not None: + payload["model"]["secrets"] = secrets + if domain is not None: + payload["route"]["domain"] = domain + if path is not None: + payload["route"]["path"] = path + if cache_http_responses is not None: + payload["cacheHttpResponses"] = cache_http_responses + if tags is not None: + payload["tags"] = tags + + response = get_session().put( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def delete_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> None: + """Delete an Inference Endpoint. + + This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable + to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`]. + + For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`]. + + Args: + name (`str`): + The name of the Inference Endpoint to delete. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + namespace = namespace or self._get_namespace(token=token) + response = get_session().delete( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def pause_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Pause an Inference Endpoint. + + A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`]. + This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which + would be automatically restarted when a request is made to it. + + For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`]. + + Args: + name (`str`): + The name of the Inference Endpoint to pause. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the paused Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def resume_inference_endpoint( + self, + name: str, + *, + namespace: str | None = None, + running_ok: bool = True, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Resume an Inference Endpoint. + + For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`]. + + Args: + name (`str`): + The name of the Inference Endpoint to resume. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + running_ok (`bool`, *optional*): + If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to + `True`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the resumed Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(response) + except HfHubHTTPError as error: + # If already running (and it's ok), then fetch current status and return + if running_ok and error.response.status_code == 400 and "already running" in error.response.text: + return self.get_inference_endpoint(name, namespace=namespace, token=token) + # Otherwise, raise the error + raise + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def scale_to_zero_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Scale Inference Endpoint to zero. + + An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a + cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which + would require a manual resume with [`resume_inference_endpoint`]. + + For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`]. + + Args: + name (`str`): + The name of the Inference Endpoint to scale to zero. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def _get_namespace(self, token: bool | str | None = None) -> str: + """Get the default namespace for the current user.""" + me = self.whoami(token=token) + if me["type"] == "user": + return me["name"] + else: + raise ValueError( + "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a" + " user." + ) + + ######################## + # Collection Endpoints # + ######################## + @validate_hf_hub_args + def list_collections( + self, + *, + owner: list[str] | str | None = None, + item: list[str] | str | None = None, + sort: CollectionSort_T | None = None, + limit: int | None = None, + token: bool | str | None = None, + ) -> Iterable[Collection]: + """List collections on the Huggingface Hub, given some filters. + + > [!WARNING] + > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items + > from a collection, you must use [`get_collection`]. + + Args: + owner (`list[str]` or `str`, *optional*): + Filter by owner's username. + item (`list[str]` or `str`, *optional*): + Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`. + sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*): + Sort collections by last modified, trending or upvotes. + limit (`int`, *optional*): + Maximum number of collections to be returned. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Collection]`: an iterable of [`Collection`] objects. + """ + # Construct the API endpoint + path = f"{self.endpoint}/api/collections" + headers = self._build_hf_headers(token=token) + params: dict = {} + if owner is not None: + params.update({"owner": owner}) + if item is not None: + params.update({"item": item}) + if sort is not None: + params.update({"sort": sort}) + if limit is not None: + params.update({"limit": limit}) + + # Paginate over the results until limit is reached + items = paginate(path, headers=headers, params=params) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + + # Parse as Collection and return + for position, collection_data in enumerate(items): + yield Collection(position=position, **collection_data) + + def get_collection(self, collection_slug: str, *, token: bool | str | None = None) -> Collection: + """Gets information about a Collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import get_collection + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + >>> collection.title + 'Recent models' + >>> len(collection.items) + 37 + >>> collection.items[0] + CollectionItem( + item_object_id='651446103cd773a050bf64c2', + item_id='TheBloke/U-Amethyst-20B-AWQ', + item_type='model', + position=88, + note=None + ) + ``` + """ + r = get_session().get( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def create_collection( + self, + title: str, + *, + namespace: str | None = None, + description: str | None = None, + private: bool = False, + resource_group_id: str | None = None, + exists_ok: bool = False, + token: bool | str | None = None, + ) -> Collection: + """Create a new Collection on the Hub. + + Args: + title (`str`): + Title of the collection to create. Example: `"Recent models"`. + namespace (`str`, *optional*): + Namespace of the collection to create (username or org). Will default to the owner name. + description (`str`, *optional*): + Description of the collection to create. The maximum size for a description is 150 characters. + private (`bool`, *optional*): + Whether the collection should be private or not. Defaults to `False` (i.e. public collection). + resource_group_id (`str`, *optional*): + Assign the collection to a resource group of the owning organization. Only valid for + organization-owned collections. The resource group ID is a 24-character hexadecimal string. + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if collection already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import create_collection + >>> collection = create_collection( + ... title="ICCV 2023", + ... description="Portfolio of models, papers and demos I presented at ICCV 2023", + ... ) + >>> collection.slug + "username/iccv-2023-64f9a55bb3115b4f513ec026" + ``` + """ + if namespace is None: + namespace = self.whoami(token)["name"] + + payload = { + "title": title, + "namespace": namespace, + "private": private, + } + if description is not None: + payload["description"] = description + if resource_group_id is not None: + payload["resourceGroupId"] = resource_group_id + + r = get_session().post( + f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exists_ok and err.response.status_code == 409: + # Collection already exists and `exists_ok=True` + slug = r.json()["slug"] + return self.get_collection(slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_metadata( + self, + collection_slug: str, + *, + title: str | None = None, + description: str | None = None, + position: int | None = None, + private: bool | None = None, + theme: str | None = None, + token: bool | str | None = None, + ) -> Collection: + """Update metadata of a collection on the Hub. + + All arguments are optional. Only provided metadata will be updated. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection to update. + description (`str`, *optional*): + Description of the collection to update. The maximum size for a description is 150 characters. + position (`int`, *optional*): + New position of the collection in the list of collections of the user. + private (`bool`, *optional*): + Whether the collection should be private or not. + theme (`str`, *optional*): + Theme of the collection on the Hub. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import update_collection_metadata + >>> collection = update_collection_metadata( + ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026", + ... title="ICCV Oct. 2023" + ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023", + ... private=False, + ... theme="pink", + ... ) + >>> collection.slug + "username/iccv-oct-2023-64f9a55bb3115b4f513ec026" + # ^collection slug got updated but not the trailing ID + ``` + """ + payload = { + "position": position, + "private": private, + "theme": theme, + "title": title, + "description": description, + } + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + return Collection(**{**r.json()["data"], "endpoint": self.endpoint}) + + def update_collection_resource_group( + self, + collection_slug: str, + resource_group_id: str | None, + *, + token: bool | str | None = None, + ) -> None: + """Assign a collection to a resource group, or remove it from any resource group. + + Only valid for organization-owned collections. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + resource_group_id (`str` or `None`): + The resource group to assign the collection to, as a 24-character hexadecimal string. If `None`, + the collection is removed from any resource group. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import update_collection_resource_group + >>> update_collection_resource_group( + ... collection_slug="my-org/iccv-2023-64f9a55bb3115b4f513ec026", + ... resource_group_id="66980ecfc1e12a49c8f0e42d", + ... ) + ``` + """ + r = get_session().post( + f"{self.endpoint}/api/collections/{collection_slug}/resource-group", + headers=self._build_hf_headers(token=token), + json={"resourceGroupId": resource_group_id}, + ) + hf_raise_for_status(r) + + def delete_collection( + self, collection_slug: str, *, missing_ok: bool = False, token: bool | str | None = None + ) -> None: + """Delete a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if the collection doesn't exist. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import delete_collection + >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True) + ``` + + > [!WARNING] + > This is a non-revertible action. A deleted collection cannot be restored. + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if missing_ok and err.response.status_code == 404: + # Collection doesn't exist and `missing_ok=True` + return + else: + raise + + def add_collection_item( + self, + collection_slug: str, + item_id: str, + item_type: CollectionItemType_T, + *, + note: str | None = None, + exists_ok: bool = False, + token: bool | str | None = None, + ) -> Collection: + """Add an item to a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_id (`str`): + Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets, + the paper id for papers, the slug of another collection (e.g. `"moonshotai/kimi-k2"`) + or a bucket id (e.g. `"namespace/bucket-name"`). + item_type (`str`): + Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"` + or `"bucket"`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if item already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Raises: + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the item you try to add to the collection does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False) + + Example: + + ```py + >>> from huggingface_hub import add_collection_item + >>> collection = add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="pierre-loic/climate-news-articles", + ... item_type="dataset" + ... ) + >>> collection.items[-1].item_id + "pierre-loic/climate-news-articles" + # ^item got added to the collection on last position + + # Add item with a note + >>> add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="datasets/climate_fever", + ... item_type="dataset" + ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet." + ... ) + (...) + ``` + """ + payload: dict[str, Any] = {"item": {"id": item_id, "type": item_type}} + if note is not None: + payload["note"] = note + r = get_session().post( + f"{self.endpoint}/api/collections/{collection_slug}/items", + headers=self._build_hf_headers(token=token), + json=payload, + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exists_ok and err.response.status_code == 409: + # Item already exists and `exists_ok=True` + return self.get_collection(collection_slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + note: str | None = None, + position: int | None = None, + token: bool | str | None = None, + ) -> None: + """Update an item in a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + position (`int`, *optional*): + New position of the item in the collection. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import get_collection, update_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Update item based on its ID (add note + update position) + >>> update_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... note="Newly updated model!" + ... position=0, + ... ) + ``` + """ + payload = {"position": position, "note": note} + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + + def delete_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + missing_ok: bool = False, + token: bool | str | None = None, + ) -> None: + """Delete an item from a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if the item doesn't exist. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import get_collection, delete_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Delete item based on its ID + >>> delete_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... ) + ``` + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if missing_ok and err.response.status_code == 404: + # Item already deleted and `missing_ok=True` + return + else: + raise + + ########################## + # Manage access requests # + ########################## + + @validate_hf_hub_args + def list_pending_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get pending access requests for a given gated repo. + + A pending request means the user has requested access to the repo but the request has not been processed yet. + If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected + using [`accept_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_pending_access_requests, accept_access_request + + # List pending requests + >>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='pending', + fields=None, + ), + ... + ] + + # Accept Clem's request + >>> accept_access_request("meta-llama/Llama-2-7b", "clem") + ``` + """ + yield from self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_accepted_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get accepted access requests for a given gated repo. + + An accepted request means the user has requested access to the repo and the request has been accepted. The user + can download any file of the repo. If the approval mode is automatic, this list should contains by default all + requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and + [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will + go to the rejected list. In both cases, the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_accepted_access_requests + + >>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='accepted', + fields=None, + ), + ... + ] + ``` + """ + yield from self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_rejected_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get rejected access requests for a given gated repo. + + A rejected request means the user has requested access to the repo and the request has been explicitly rejected + by a repo owner (either you or another user from your organization). The user cannot download any file of the + repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and + [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will + go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_rejected_access_requests + + >>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='rejected', + fields=None, + ), + ... + ] + ``` + """ + yield from self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token) + + def _list_access_requests( + self, + repo_id: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[AccessRequest]: + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + for request in paginate( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield AccessRequest( + username=request["user"]["user"], + fullname=request["user"]["fullname"], + email=request["user"].get("email"), + status=request["status"], + timestamp=parse_datetime(request["timestamp"]), + fields=request.get("fields"), # only if custom fields in form + ) + + @validate_hf_hub_args + def cancel_access_request( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Cancel an access request from a user for a given gated repo. + + A cancelled request will go back to the pending list and the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to cancel access request for. + user (`str`): + The username of the user which access request should be cancelled. + repo_type (`str`, *optional*): + The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the pending list. + """ + self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def accept_access_request( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Accept an access request from a user for a given gated repo. + + Once the request is accepted, the user will be able to download any file of the repo and access the community + tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be + cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to accept access request for. + user (`str`): + The username of the user which access request should be accepted. + repo_type (`str`, *optional*): + The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the accepted list. + """ + self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def reject_access_request( + self, + repo_id: str, + user: str, + *, + repo_type: str | None = None, + rejection_reason: str | None, + token: bool | str | None = None, + ) -> None: + """ + Reject an access request from a user for a given gated repo. + + A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected + requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`]. + A cancelled request will go back to the pending list while an accepted request will go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to reject access request for. + user (`str`): + The username of the user which access request should be rejected. + repo_type (`str`, *optional*): + The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + rejection_reason (`str`, *optional*): + Optional rejection reason that will be visible to the user (max 200 characters). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the rejected list. + """ + self._handle_access_request( + repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token + ) + + @validate_hf_hub_args + def _handle_access_request( + self, + repo_id: str, + user: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: str | None = None, + rejection_reason: str | None = None, + token: bool | str | None = None, + ) -> None: + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + payload = {"user": user, "status": status} + + if rejection_reason is not None: + if status != "rejected": + raise ValueError("`rejection_reason` can only be passed when rejecting an access request.") + payload["rejectionReason"] = rejection_reason + + response = get_session().post( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def grant_access( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Grant access to a user for a given gated repo. + + Granting access don't require for the user to send an access request by themselves. The user is automatically + added to the accepted list meaning they can download the files You can revoke the granted access at any time + using [`cancel_access_request`] or [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to grant access to. + user (`str`): + The username of the user to grant access. + repo_type (`str`, *optional*): + The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 400 if the user already has access to the repo. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + response = get_session().post( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/grant", + headers=self._build_hf_headers(token=token), + json={"user": user}, + ) + hf_raise_for_status(response) + return response.json() + + ################### + # Manage webhooks # + ################### + + @validate_hf_hub_args + def get_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Get a webhook by its id. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to get. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the webhook. + + Example: + ```python + >>> from huggingface_hub import get_webhook + >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc") + >>> print(webhook) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + secret="my-secret", + domains=["repo", "discussion"], + disabled=False, + ) + ``` + """ + response = get_session().get( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def list_webhooks(self, *, token: bool | str | None = None) -> list[WebhookInfo]: + """List all configured webhooks. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[WebhookInfo]`: + List of webhook info objects. + + Example: + ```python + >>> from huggingface_hub import list_webhooks + >>> webhooks = list_webhooks() + >>> len(webhooks) + 2 + >>> webhooks[0] + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + secret="my-secret", + domains=["repo", "discussion"], + disabled=False, + ) + ``` + """ + response = get_session().get( + f"{constants.ENDPOINT}/api/settings/webhooks", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhooks_data = response.json() + + return [ + WebhookInfo( + id=webhook["id"], + url=webhook.get("url"), + job=JobSpec(**webhook["job"]) if webhook.get("job") else None, + watched=[WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook["watched"]], + domains=webhook["domains"], + secret=webhook.get("secret"), + disabled=webhook["disabled"], + ) + for webhook in webhooks_data + ] + + @validate_hf_hub_args + def create_webhook( + self, + *, + url: str | None = None, + job_id: str | None = None, + watched: list[dict | WebhookWatchedItem], + domains: list[constants.WEBHOOK_DOMAIN_T] | None = None, + secret: str | None = None, + token: bool | str | None = None, + ) -> WebhookInfo: + """Create a new webhook. + + The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure. + This function should be called with one of `url` or `job_id`, but not both. + + Args: + url (`str`): + URL to send the payload to. + job_id (`str`): + ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD. + Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET. + watched (`list[WebhookWatchedItem]`): + List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces. + Watched items can also be provided as plain dictionaries. + domains (`list[Literal["repo", "discussion"]]`, optional): + List of domains to watch. It can be "repo", "discussion" or both. + secret (`str`, optional): + A secret to sign the payload with. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the newly created webhook. + + Example: + + Create a webhook that sends a payload to a URL + ```python + >>> from huggingface_hub import create_webhook + >>> payload = create_webhook( + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + ... domains=["repo", "discussion"], + ... secret="my-secret", + ... ) + >>> print(payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + job=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + + Run a Job and then create a webhook that triggers this Job + ```python + >>> from huggingface_hub import create_webhook, run_job + >>> job = run_job( + ... image="ubuntu", + ... command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"], + ... ) + >>> payload = create_webhook( + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... job_id=job.id, + ... domains=["repo", "discussion"], + ... secret="my-secret", + ... ) + >>> print(payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url=None, + job=JobSpec( + docker_image='ubuntu', + space_id=None, + command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'], + arguments=[], + environment={}, + secrets=[], + flavor='cpu-basic', + timeout=None, + tags=None, + arch=None + ), + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + """ + watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched] + + post_webhooks_json: dict = {"watched": watched_dicts} + if domains is not None: + post_webhooks_json["domains"] = domains + if secret is not None: + post_webhooks_json["secret"] = secret + if url is not None and job_id is not None: + raise ValueError("Set `url` or `job_id` but not both.") + elif url is not None: + post_webhooks_json["url"] = url + elif job_id is not None: + post_webhooks_json["jobSourceId"] = job_id + else: + raise ValueError("Missing argument for webhook: `url` or `job_id`.") + + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks", + json=post_webhooks_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def update_webhook( + self, + webhook_id: str, + *, + url: str | None = None, + watched: list[dict | WebhookWatchedItem] | None = None, + domains: list[constants.WEBHOOK_DOMAIN_T] | None = None, + secret: str | None = None, + token: bool | str | None = None, + ) -> WebhookInfo: + """Update an existing webhook. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to be updated. + url (`str`, optional): + The URL to which the payload will be sent. + watched (`list[WebhookWatchedItem]`, optional): + List of items to watch. It can be users, orgs, models, datasets, or spaces. + Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries. + domains (`list[Literal["repo", "discussion"]]`, optional): + The domains to watch. This can include "repo", "discussion", or both. + secret (`str`, optional): + A secret to sign the payload with, providing an additional layer of security. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the updated webhook. + + Example: + ```python + >>> from huggingface_hub import update_webhook + >>> updated_payload = update_webhook( + ... webhook_id="654bbbc16f2ec14d77f109cc", + ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... domains=["repo"], + ... secret="my-secret", + ... ) + >>> print(updated_payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo"], + secret="my-secret", + disabled=False, + ``` + """ + if watched is None: + watched = [] + watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched] + + update_json: dict = {"watched": watched_dicts} + if url is not None: + update_json["url"] = url + if domains is not None: + update_json["domains"] = domains + if secret is not None: + update_json["secret"] = secret + + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + json=update_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def enable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Enable a webhook (makes it "active"). + + Args: + webhook_id (`str`): + The unique identifier of the webhook to enable. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the enabled webhook. + + Example: + ```python + >>> from huggingface_hub import enable_webhook + >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc") + >>> enabled_webhook + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + """ + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/enable", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def disable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Disable a webhook (makes it "disabled"). + + Args: + webhook_id (`str`): + The unique identifier of the webhook to disable. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the disabled webhook. + + Example: + ```python + >>> from huggingface_hub import disable_webhook + >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc") + >>> disabled_webhook + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + jon=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=True, + ) + ``` + """ + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/disable", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def delete_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> None: + """Delete a webhook. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to delete. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `None` + + Example: + ```python + >>> from huggingface_hub import delete_webhook + >>> delete_webhook("654bbbc16f2ec14d77f109cc") + ``` + """ + response = get_session().delete( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + ############# + # Internals # + ############# + + def _build_hf_headers( + self, + token: bool | str | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + ) -> dict[str, str]: + """ + Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client + when `token` is not provided. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + return build_hf_headers( + token=token, + library_name=library_name or self.library_name, + library_version=library_version or self.library_version, + user_agent=user_agent or self.user_agent, + headers=self.headers, + ) + + def _prepare_folder_deletions( + self, + repo_id: str, + repo_type: str | None, + revision: str | None, + path_in_repo: str, + delete_patterns: list[str] | str | None, + token: bool | str | None = None, + ) -> list[CommitOperationDelete]: + """Generate the list of Delete operations for a commit to delete files from a repo. + + List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`] + with the matching items. + + Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be + kept even if it matches the `delete_patterns` constraints. + """ + if delete_patterns is None: + # If no delete patterns, no need to list and filter remote files + return [] + + # List remote files + filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + + # Compute relative path in repo + if path_in_repo and path_in_repo not in (".", "./"): + path_in_repo = path_in_repo.strip("/") + "/" # harmonize + relpath_to_abspath = { + file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo) + } + else: + relpath_to_abspath = {file: file for file in filenames} + + # Apply filter on relative paths and return + return [ + CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False) + for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns) + if relpath_to_abspath[relpath] != ".gitattributes" + ] + + def _prepare_upload_folder_additions( + self, + folder_path: str | Path, + path_in_repo: str, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> list[CommitOperationAdd]: + """Generate the list of Add operations for a commit to upload a folder. + + Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist) + constraints are discarded. + """ + + folder_path = Path(folder_path).expanduser().resolve() + if not folder_path.is_dir(): + raise ValueError(f"Provided path: '{folder_path}' is not a directory") + + # List files from folder + relpath_to_abspath = { + path.relative_to(folder_path).as_posix(): path + for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic + if path.is_file() + } + + # Filter files + # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering. + filtered_repo_objects = list( + filter_repo_objects( + relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns + ) + ) + + prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else "" + + # If updating a README.md file, make sure the metadata format is valid + # It's better to fail early than to fail after all the files have been hashed. + if "README.md" in filtered_repo_objects: + self._validate_yaml( + content=relpath_to_abspath["README.md"].read_text(encoding="utf8"), + repo_type=repo_type, + token=token, + ) + return [ + CommitOperationAdd( + path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk + path_in_repo=prefix + relpath, # "absolute" path in repo + ) + for relpath in filtered_repo_objects + ] + + def _validate_yaml(self, content: str, *, repo_type: str | None = None, token: bool | str | None = None): + """ + Validate YAML from `README.md`, used before file hashing and upload. + + Args: + content (`str`): + Content of `README.md` to validate. + repo_type (`str`, *optional*): + The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if YAML is invalid + """ + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + headers = self._build_hf_headers(token=token) + + response = get_session().post( + f"{self.endpoint}/api/validate-yaml", + json={"content": content, "repoType": repo_type}, + headers=headers, + ) + # Handle warnings (example: empty metadata) + response_content = response.json() + message = "\n".join([f"- {warning.get('message')}" for warning in response_content.get("warnings", [])]) + if message: + warnings.warn(f"Warnings while validating metadata in README.md:\n{message}") + + # Raise on errors + try: + hf_raise_for_status(response) + except BadRequestError as e: + errors = response_content.get("errors", []) + message = "\n".join([f"- {error.get('message')}" for error in errors]) + raise ValueError(f"Invalid metadata in README.md.\n{message}") from e + + def get_user_overview(self, username: str, token: bool | str | None = None) -> User: + """ + Get an overview of a user on the Hub. + + Args: + username (`str`): + Username of the user to get an overview of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `User`: A [`User`] object with the user's overview. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + """ + r = get_session().get( + f"{constants.ENDPOINT}/api/users/{username}/overview", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return User(**r.json()) + + @validate_hf_hub_args + def get_organization_overview(self, organization: str, token: bool | str | None = None) -> Organization: + """ + Get an overview of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get an overview of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended method + for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Organization`: An [`Organization`] object with the organization's overview. + + Raises: + [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError): + HTTP 404 If the organization does not exist on the Hub. + """ + r = get_session().get( + f"{constants.ENDPOINT}/api/organizations/{organization}/overview", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return Organization(**r.json()) + + @validate_hf_hub_args + def list_organization_followers(self, organization: str, token: bool | str | None = None) -> Iterable[User]: + """ + List followers of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get the followers of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the followers of the organization. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the organization does not exist on the Hub. + + """ + for follower in paginate( + path=f"{constants.ENDPOINT}/api/organizations/{organization}/followers", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**follower) + + def list_organization_members(self, organization: str, token: bool | str | None = None) -> Iterable[User]: + """ + List of members of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get the members of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the members of the organization. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the organization does not exist on the Hub. + + """ + for member in paginate( + path=f"{constants.ENDPOINT}/api/organizations/{organization}/members", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**member) + + def list_user_followers(self, username: str, token: bool | str | None = None) -> Iterable[User]: + """ + Get the list of followers of a user on the Hub. + + Args: + username (`str`): + Username of the user to get the followers of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the followers of the user. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + + """ + for follower in paginate( + path=f"{constants.ENDPOINT}/api/users/{username}/followers", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**follower) + + def list_user_following(self, username: str, token: bool | str | None = None) -> Iterable[User]: + """ + Get the list of users followed by a user on the Hub. + + Args: + username (`str`): + Username of the user to get the users followed by. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the users followed by the user. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + + """ + for followed_user in paginate( + path=f"{constants.ENDPOINT}/api/users/{username}/following", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**followed_user) + + def list_papers( + self, + *, + query: str | None = None, + limit: int | None = None, + token: bool | str | None = None, + ) -> Iterable[PaperInfo]: + """ + List daily papers on the Hugging Face Hub given a search query. + + Args: + query (`str`, *optional*): + A search query string to find papers. + If provided, returns papers that match the query. + limit (`int`, *optional*): + The maximum number of papers to return. + token (Union[bool, str, None], *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all papers with "attention" in their title + >>> api.list_papers(query="attention") + ``` + """ + path = f"{self.endpoint}/api/papers/search" + params: dict[str, Any] = {} + if query: + params["q"] = query + if limit is not None: + params["limit"] = limit + r = get_session().get( + path, + params=params, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + for paper in r.json(): + yield PaperInfo(**paper) + + def paper_info(self, id: str) -> PaperInfo: + """ + Get information for a paper on the Hub. + + Args: + id (`str`, **optional**): + ArXiv id of the paper. + + Returns: + `PaperInfo`: A `PaperInfo` object. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the paper does not exist on the Hub. + """ + path = f"{self.endpoint}/api/papers/{id}" + r = get_session().get(path) + hf_raise_for_status(r) + return PaperInfo(**r.json()) + + def read_paper(self, id: str) -> str: + """ + Get the markdown content of a paper page on the Hub. + + Args: + id (`str`): + ArXiv id of the paper. + + Returns: + `str`: The paper page content as markdown. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the paper does not exist on the Hub. + """ + path = f"{self.endpoint}/papers/{id}.md" + r = get_session().get(path) + hf_raise_for_status(r) + return r.text + + def list_daily_papers( + self, + *, + date: str | None = None, + token: bool | str | None = None, + week: str | None = None, + month: str | None = None, + submitter: str | None = None, + sort: DailyPapersSort_T | None = None, + p: int | None = None, + limit: int | None = None, + ) -> Iterable[PaperInfo]: + """ + List the daily papers published on a given date on the Hugging Face Hub. + + Args: + date (`str`, *optional*): + Date in ISO format (YYYY-MM-DD) for which to fetch daily papers. + Defaults to most recent ones. + token (Union[bool, str, None], *optional*): + A valid user access token (string). Defaults to the locally saved + token. To disable authentication, pass `False`. + week (`str`, *optional*): + Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`. + month (`str`, *optional*): + Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`. + submitter (`str`, *optional*): + Username of the submitter to filter daily papers. + sort (`Literal["publishedAt", "trending"]`, *optional*): + Sort order for the daily papers. Can be either by `publishedAt` or by `trending`. + Defaults to `"publishedAt"` + p (`int`, *optional*): + Page number for pagination. Defaults to 0. + limit (`int`, *optional*): + Limit of papers to fetch. Defaults to 50. + + Returns: + `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + >>> list(api.list_daily_papers(date="2025-10-29")) + ``` + """ + path = f"{self.endpoint}/api/daily_papers" + + params = { + k: v + for k, v in { + "p": p, + "limit": limit, + "sort": sort, + "date": date, + "week": week, + "month": month, + "submitter": submitter, + }.items() + if v is not None + } + + r = get_session().get(path, params=params, headers=self._build_hf_headers(token=token)) + hf_raise_for_status(r) + for paper in r.json(): + yield PaperInfo(**paper) + + def auth_check( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + write: bool = False, + ) -> None: + """ + Check if the provided user token has access to a specific repository on the Hugging Face Hub. + + This method verifies whether the user, authenticated via the provided token, has access to the specified + repository. If the repository is not found or if the user lacks the required permissions to access it, + the method raises an appropriate exception. + + Args: + repo_id (`str`): + The repository to check for access. Format should be `"user/repo_name"`. + Example: `"user/my-cool-model"`. + + repo_type (`str`, *optional*): + The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`. + If not specified, the default is `"model"`. + + token (`Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + write (`bool`, *optional*): + If `True`, checks whether the user has content write permission on the repository. + If `False` (default), only checks for read access. + + Raises: + [`~utils.RepositoryNotFoundError`]: + Raised if the repository does not exist, is private, or the user does not have access. This can + occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user + is not authenticated. + + [`~utils.GatedRepoError`]: + Raised if the repository exists but is gated and the user is not authorized to access it. + + Example: + Check if the user has access to a repository: + + ```python + >>> from huggingface_hub import auth_check + >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError + + try: + auth_check("user/my-cool-model") + except GatedRepoError: + # Handle gated repository error + print("You do not have permission to access this gated repository.") + except RepositoryNotFoundError: + # Handle repository not found error + print("The repository was not found or you do not have access.") + ``` + + In this example: + - If the user has access, the method completes successfully. + - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user + to handle them accordingly. + """ + headers = self._build_hf_headers(token=token) + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/auth-check" + if write: + path = f"{path}/write" + r = get_session().get(path, headers=headers) + hf_raise_for_status(r) + + def run_job( + self, + *, + image: str, + command: list[str], + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: JobHardware | str | None = None, + timeout: int | float | str | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + expose: list[int] | None = None, + ssh: bool = False, + resource_group_id: str | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Run compute Jobs on Hugging Face infrastructure. + + Args: + image (`str`): + The Docker image to use. + Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`. + Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`. + + command (`list[str]`): + The command to run. Example: `["echo", "hello"]`. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware. See [`JobHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + name (`str`, *optional*): + A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in + `labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix). + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + expose (`list[int]`, *optional*): + Container ports to expose through the jobs proxy. Each listed port is reachable + on the public jobs domain (e.g. `https://--8000.hf.jobs`). Access always + requires an HF token with read access to the job's namespace. + + ssh (`bool`, *optional*): + If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url` + (e.g. `ssh @ssh.hf.jobs`, or `hf jobs ssh ` from the CLI). Connecting requires + write access to the job's namespace and an SSH public key registered on the Hub + (https://huggingface.co/settings/keys). Defaults to False. + + resource_group_id (`str`, *optional*): + The ID of the resource group to create the Job in. Used to control access to resources within an + organization and for cost attribution/spending-limit features. If not provided, the Job is created + outside of any resource group. + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + Run your first Job: + + ```python + >>> from huggingface_hub import run_job + >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + ``` + + Run a GPU Job: + + ```python + >>> from huggingface_hub import run_job + >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel" + >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"] + >>> run_job(image=image, command=command, flavor="a10g-small") + ``` + + Run a Job with volumes: + + ```python + >>> from huggingface_hub import Volume, run_job + >>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data") + >>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output") + >>> image = "duckdb/duckdb" + >>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"] + >>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume]) + ``` + + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + if name is None and not (labels and "name" in labels): + name = _default_job_name_from_image(image, command) + job_spec = _create_job_spec( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + name=name, + labels=labels, + volumes=volumes, + expose=expose, + ssh=ssh, + resource_group_id=resource_group_id, + ) + response = get_session().post( + f"{self.endpoint}/api/jobs/{namespace}", + json=job_spec, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + job_info = response.json() + return JobInfo(**job_info, endpoint=self.endpoint) + + def _fetch_running_job_sse( + self, + *, + job_id: str, + route: str, + timeout: int, + skip_previous_events_on_retry: bool, + tolerated_status_codes: tuple[int, ...] = (), + tolerated_exception_types: tuple[type[Exception], ...] = (), + follow: bool = True, + namespace: str | None = None, + token: bool | str | None = None, + params: dict[str, Any] | None = None, + ) -> Iterable[dict[str, Any]]: + if namespace is None: + namespace = self.whoami(token=token)["name"] + + def has_job_finished() -> bool: + # We don't use http_backoff: this is the authoritative check that + # decides whether to keep streaming. + job_status_response = get_session().get( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(job_status_response) + job_status = job_status_response.json() + return "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING") + + yield from self._stream_sse_events( + url=f"{self.endpoint}/api/jobs/{namespace}/{job_id}/{route}", + log_label=f"jobs /{route} for {job_id=}", + timeout=timeout, + follow=follow, + token=token, + skip_previous_events_on_retry=skip_previous_events_on_retry, + tolerated_status_codes=tolerated_status_codes, + tolerated_exception_types=tolerated_exception_types, + on_iteration_end=has_job_finished, + params=params, + ) + + def fetch_job_logs( + self, + *, + job_id: str, + namespace: str | None = None, + follow: bool = False, + tail: int | None = None, + token: bool | str | None = None, + ) -> Iterable[str]: + """ + Fetch all the logs from a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + follow (`bool`, *optional*): + If `True`, stream logs in real-time until the job completes (blocking). + If `False` (default), fetch only the currently available logs and return immediately (non-blocking). + + tail (`int`, *optional*): + Maximum number of lines to return from the logs. When combined with `follow=True`, + starts from the last N lines and continues streaming new logs. When `follow=False`, + returns only the last N lines from currently available logs. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import fetch_job_logs, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + >>> for log in fetch_job_logs(job_id=job.id): + ... print(log) + Hello from HF compute! + + >>> # Non-blocking: fetch only currently available logs + >>> for log in fetch_job_logs(job_id=job.id, follow=False): + ... print(log) + + >>> # Stream logs starting from the last 100 lines + >>> for log in fetch_job_logs(job_id=job.id, follow=True, tail=100): + ... print(log) + ``` + """ + # - We need to retry because sometimes the /logs doesn't return logs when the job just started. + # (for example it can return only two lines: one for "Job started" and one empty line) + # - Timeouts can happen in case of build errors + # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming + # - Infinite empty log stream can happen in case of build error + # (the logs stream is infinite and empty except for the Job started message) + # - there is a ": keep-alive" every 30 seconds + + seconds_between_keep_alive = 30 + # When not following, use a short timeout: the server replays historical logs + # quickly, then pauses waiting for new events (~30s keep-alive). 5 seconds is + # enough to receive all buffered logs. + timeout = 4 * seconds_between_keep_alive if follow else 5 + params = {"tail": tail} if tail is not None else None + for event in self._fetch_running_job_sse( + job_id=job_id, + route="logs", + timeout=timeout, + skip_previous_events_on_retry=True, + follow=follow, + namespace=namespace, + token=token, + params=params, + ): + # timestamp = event["timestamp"] + if not event["data"].startswith("===== Job started"): + log = event["data"] + yield log + + def fetch_job_metrics( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> Iterable[dict[str, Any]]: + """ + Fetch all the live metrics from a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import fetch_job_metrics, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small") + >>> for metrics in fetch_job_metrics(job_id=job.id): + ... print(metrics) + { + "cpu_usage_pct": 0, + "cpu_millicores": 3500, + "memory_used_bytes": 1306624, + "memory_total_bytes": 15032385536, + "rx_bps": 0, + "tx_bps": 0, + "gpus": { + "882fa930": { + "utilization": 0, + "memory_used_bytes": 0, + "memory_total_bytes": 22836000000 + } + }, + "replica": "57vr7" + } + ``` + """ + # - there is one "metric" event every second, like this: + # event: metric + # data: {"cpu_usage_pct":0,"cpu_millicores":3500,"memory_used_bytes":1417216,"memory_total_bytes":15032385536,"rx_bps":0,"tx_bps":0,"gpus":{"d901cd7f":{"utilization":0,"memory_used_bytes":0,"memory_total_bytes":22836000000}},"replica":"j6qz9"} + # - the stream doesn't end when the job finishes, so we rely on timeouts (httpx.NetworkError with Timeout as cause) + # - httpx.ReadTimeout can happen if the job is marked as running but the hardware is not available yet, that we can ignore + # - it returns an internal error 500 if the job has already finished, we simply ignore it + # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming + # - there is a ": keep-alive" every 30 seconds + seconds_between_events = 1 + yield from self._fetch_running_job_sse( + job_id=job_id, + route="metrics", + timeout=10 * seconds_between_events, + skip_previous_events_on_retry=False, + tolerated_status_codes=(500,), + namespace=namespace, + token=token, + ) + + def list_jobs( + self, + *, + status: list[JobStage | str] | JobStage | str | None = None, + labels: dict[str, str] | None = None, + timeout: int | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> Iterable[JobInfo]: + """ + List compute Jobs on Hugging Face infrastructure. + + Args: + status (`JobStage`, `str` or `list`, *optional*): + Only return Jobs with the given status(es), e.g. `"RUNNING"` or `[JobStage.RUNNING, JobStage.SCHEDULING]`. + See [`JobStage`] for possible values. + + labels (`dict[str, str]`, *optional*): + Only return Jobs that have all the given `key=value` labels, e.g. `{"env": "prod", "team": "ml"}`. + + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + namespace (`str`, *optional*): + The namespace from where it lists the jobs. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + `Iterable[JobInfo]`: an iterable of [`JobInfo`] objects. + """ + if namespace is None: + namespace = whoami(token=token)["name"] + params: list[tuple[str, Any]] = [] + if status is not None: + statuses = [status] if isinstance(status, (str, JobStage)) else status + params.extend(("stage", (s.value if isinstance(s, JobStage) else str(s)).upper()) for s in statuses) + if labels is not None: + params.extend(("label", f"{key}={value}") for key, value in labels.items()) + + path = f"{self.endpoint}/api/jobs/{namespace}" + headers = self._build_hf_headers(token=token) + for job_info in paginate(path, params=params, headers=headers, timeout=timeout): + yield JobInfo(**job_info, endpoint=self.endpoint) + + def list_jobs_hardware(self, token: bool | str | None = None) -> list[JobHardwareInfo]: + """ + List available hardware options for Jobs on Hugging Face infrastructure. + + Returns: + `list[JobHardwareInfo]`: A list of available hardware configurations. + + Example: + + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> hardware_list = api.list_jobs_hardware() + >>> hardware_list[0] + JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ephemeral_storage='20 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute') + >>> hardware_list[0].name + 'cpu-basic' + + # Filter GPU options + >>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None] + >>> gpu_hardware[0].accelerator.model + 'T4' + ``` + """ + response = get_session().get(f"{self.endpoint}/api/jobs/hardware", headers=self._build_hf_headers(token=token)) + hf_raise_for_status(response) + return [JobHardwareInfo(**hardware) for hardware in response.json()] + + def inspect_job( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Inspect a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import inspect_job, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + >>> inspect_job(job.id) + JobInfo( + id='68780d00bbe36d38803f645f', + created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc), + docker_image='python:3.12', + space_id=None, + command=['python', '-c', "print('Hello from HF compute!')"], + arguments=[], + environment={}, + secrets={}, + flavor='cpu-basic', + status=JobStatus(stage='RUNNING', message=None) + ) + ``` + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return JobInfo(**response.json(), endpoint=self.endpoint) + + @overload + def wait_for_job( + self, + job_id: str, + *, + timeout: float | None = None, + poll_interval: float = 1.0, + stages: list[JobStage] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: ... + + @overload + def wait_for_job( + self, + job_id: list[str], + *, + timeout: float | None = None, + poll_interval: float = 1.0, + stages: list[JobStage] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> list[JobInfo]: ... + + def wait_for_job( + self, + job_id: str | list[str], + *, + timeout: float | None = None, + poll_interval: float = 1.0, + stages: list[JobStage] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo | list[JobInfo]: + """ + Wait until one or more compute Jobs on Hugging Face infrastructure reach a given stage. + + Each Job status is polled (with [`inspect_job`]) every `poll_interval` seconds until its stage is one + of `stages` (terminal stages by default: `"COMPLETED"`, `"CANCELED"`, `"ERROR"` or `"DELETED"`). The + final [`JobInfo`] is returned in all cases: a failed or canceled Job does **not** raise an exception — + check `job.status.stage` to act on the outcome. + + Terminal stages always stop the wait, even when not listed in `stages`. This avoids waiting forever for + a stage the Job will never reach (e.g. waiting for `"RUNNING"` on a Job that fails during scheduling). + + Args: + job_id (`str` or `list[str]`): + ID of the Job, or a list of Job IDs to wait for. If a list is passed, a list of [`JobInfo`] + is returned (in the same order). + + timeout (`float`, *optional*): + The maximum time to wait for the Job(s) to finish, in seconds. If `None`, will wait + indefinitely. + + poll_interval (`float`, *optional*): + The time to wait between each status check, in seconds. Defaults to 1s. + + stages (`list[JobStage]`, *optional*): + The stages to wait for. Defaults to the terminal stages (`"COMPLETED"`, `"CANCELED"`, + `"ERROR"`, `"DELETED"`). Pass e.g. `[JobStage.RUNNING]` to wait for the Job to start running. + Terminal stages always stop the wait regardless of this value. + + namespace (`str`, *optional*): + The namespace where the Job(s) are running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`JobInfo`] or `list[JobInfo]`: the final Job info(s). + + Raises: + `TimeoutError`: + If at least one Job has not reached one of the target stages after `timeout` seconds. + + Example: + + ```python + >>> from huggingface_hub import run_job, wait_for_job + >>> job = run_job(image="python:3.12", command=["python", "-c", "print('Hello from HF compute!')"]) + >>> wait_for_job(job_id=job.id).status.stage + 'COMPLETED' + ``` + """ + if timeout is not None and timeout < 0: + raise ValueError("`timeout` cannot be negative.") + if poll_interval <= 0: + raise ValueError("`poll_interval` must be positive.") + + # Terminal stages always stop the wait, so a Job that never reaches the target stage doesn't hang. + target_stages = set(stages) | set(TERMINAL_JOB_STAGES) if stages else set(TERMINAL_JOB_STAGES) + + if namespace is None: + namespace = self.whoami(token=token)["name"] + deadline = None if timeout is None else time.monotonic() + timeout + + def _wait_single(single_job_id: str) -> JobInfo: + while True: + job = self.inspect_job(job_id=single_job_id, namespace=namespace, token=token) + if job.status.stage in target_stages: + return job + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and remaining <= 0: + raise TimeoutError( + f"Job '{single_job_id}' is still in stage '{job.status.stage}' after {timeout} seconds." + ) + time.sleep(poll_interval if remaining is None else min(poll_interval, remaining)) + + if isinstance(job_id, str): + return _wait_single(job_id) + return [_wait_single(single_job_id) for single_job_id in job_id] + + def cancel_job( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Cancel a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().post( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}/cancel", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def update_job_labels( + self, + *, + job_id: str, + labels: dict[str, str], + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Update labels of an existing Job. + + Replaces all existing user-provided labels with the new labels. + + Args: + job_id (`str`): + ID of the Job. + + labels (`dict[str, str]`): + New labels to set on the job. Replaces all existing labels. + Both keys and values must be max 100 characters and contain only + alphanumeric characters, dots, dashes, and underscores. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`JobInfo`]: The updated Job info. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().put( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}/labels", + headers=self._build_hf_headers(token=token), + json={"labels": labels}, + ) + hf_raise_for_status(response) + return JobInfo(**response.json(), endpoint=self.endpoint) + + @experimental + def run_uv_job( + self, + script: str, + *, + script_args: list[str] | None = None, + dependencies: list[str] | None = None, + python: str | None = None, + image: str | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: JobHardware | str | None = None, + timeout: int | float | str | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + expose: list[int] | None = None, + ssh: bool = False, + resource_group_id: str | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Run a UV script Job on Hugging Face infrastructure. + + Args: + script (`str`): + Path or URL of the UV script, or a command. + + script_args (`list[str]`, *optional*) + Arguments to pass to the script or command. + + dependencies (`list[str]`, *optional*) + Dependencies to use to run the UV script. + + python (`str`, *optional*) + Use a specific Python version. Default is 3.12. + + image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"): + Use a custom Docker image with `uv` installed. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware. See [`JobHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + name (`str`, *optional*): + A name for the Job. Stored as the `name` label. Cannot be passed together with a `name` key in + `labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix). + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + expose (`list[int]`, *optional*): + Container ports to expose through the jobs proxy. Each listed port is reachable + on the public jobs domain (e.g. `https://--8000.hf.jobs`). Access always + requires an HF token with read access to the job's namespace. + + ssh (`bool`, *optional*): + If True, the job's container is reachable over SSH at the URL given by `job.status.ssh_url` + (e.g. `ssh @ssh.hf.jobs`, or `hf jobs ssh ` from the CLI). Connecting requires + write access to the job's namespace and an SSH public key registered on the Hub + (https://huggingface.co/settings/keys). Defaults to False. + + resource_group_id (`str`, *optional*): + The ID of the resource group to create the Job in. Used to control access to resources within an + organization and for cost attribution/spending-limit features. If not provided, the Job is created + outside of any resource group. + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + Run a script from a URL: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small") + ``` + + Run a local script: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small") + ``` + + Run a command: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "lighteval" + >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"] + >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small") + ``` + + Mount volumes, e.g. to save model checkpoints during training: + + ```python + >>> from huggingface_hub import Volume, run_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...] + >>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs") + >>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket]) + ``` + """ + image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm" + env = env or {} + secrets = secrets or {} + + if name is None and not (labels and "name" in labels): + name = _default_job_name_from_script(script, script_args or []) + + # Build command + command, env, secrets, extra_volumes = self._create_uv_command_env_and_secrets( + script=script, + script_args=script_args, + dependencies=dependencies, + python=python, + env=env, + secrets=secrets, + namespace=namespace, + token=token, + volumes=volumes, + ) + if extra_volumes: + volumes = (volumes or []) + extra_volumes + # Create RunCommand args + return self.run_job( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + name=name, + labels=labels, + volumes=volumes, + expose=expose, + ssh=ssh, + resource_group_id=resource_group_id, + namespace=namespace, + token=token, + ) + + def create_scheduled_job( + self, + *, + image: str, + command: list[str], + schedule: str, + suspend: bool | None = None, + concurrency: bool | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: JobHardware | str | None = None, + timeout: int | float | str | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + expose: list[int] | None = None, + resource_group_id: str | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Create scheduled compute Jobs on Hugging Face infrastructure. + + Args: + image (`str`): + The Docker image to use. + Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`. + Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`. + + command (`list[str]`): + The command to run. Example: `["echo", "hello"]`. + + schedule (`str`): + One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a + CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). + + suspend (`bool`, *optional*): + If True, the scheduled Job is suspended (paused). Defaults to False. + + concurrency (`bool`, *optional*): + If True, multiple instances of this Job can run concurrently. Defaults to False. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware. See [`JobHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + name (`str`, *optional*): + A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name` + key in `labels`. Names do not have to be unique. Defaults to a name derived from image and command (with a short hash suffix). + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + expose (`list[int]`, *optional*): + Container ports to expose through the jobs proxy. Each listed port is reachable + on the public jobs domain (e.g. `https://--8000.hf.jobs`). Access always + requires an HF token with read access to the job's namespace. + + resource_group_id (`str`, *optional*): + The ID of the resource group to create the scheduled Job in. Used to control access to resources + within an organization and for cost attribution/spending-limit features. If not provided, the + scheduled Job is created outside of any resource group. + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + Create your first scheduled Job: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly") + ``` + + Use a CRON schedule expression: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *") + ``` + + Create a scheduled GPU Job: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel" + >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"] + >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly") + ``` + + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + if name is None and not (labels and "name" in labels): + name = _default_job_name_from_image(image, command) + + # prepare payload to send to HF Jobs API + job_spec = _create_job_spec( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + name=name, + labels=labels, + volumes=volumes, + expose=expose, + resource_group_id=resource_group_id, + ) + input_json: dict[str, Any] = { + "jobSpec": job_spec, + "schedule": schedule, + } + if concurrency is not None: + input_json["concurrency"] = concurrency + if suspend is not None: + input_json["suspend"] = suspend + response = get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}", + json=input_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + scheduled_job_info = response.json() + return ScheduledJobInfo(**scheduled_job_info) + + def list_scheduled_jobs( + self, + *, + timeout: int | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> list[ScheduledJobInfo]: + """ + List scheduled compute Jobs on Hugging Face infrastructure. + + Args: + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + namespace (`str`, *optional*): + The namespace from where it lists the jobs. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/scheduled-jobs/{namespace}", + headers=self._build_hf_headers(token=token), + timeout=timeout, + ) + hf_raise_for_status(response) + return [ScheduledJobInfo(**scheduled_job_info) for scheduled_job_info in response.json()] + + def inspect_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Inspect a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import inspect_job, create_scheduled_job + >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly") + >>> inspect_scheduled_job(scheduled_job.id) + ``` + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return ScheduledJobInfo(**response.json()) + + def delete_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Delete a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().delete( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def suspend_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Suspend (pause) a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/suspend", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def resume_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Resume (unpause) a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/resume", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def trigger_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Trigger a scheduled Job to run immediately. + + This triggers one immediate run of the scheduled job's spec. It does **not** modify the schedule + and does **not** affect the next scheduled run. If an instance is already running and the scheduled + job does not allow concurrent runs, the request is rejected (HTTP 409). + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`JobInfo`]: Info about the triggered run. + + Raises: + [`~utils.HfHubHTTPError`]: + HTTP 409 if another instance is already running and `concurrency` is disabled on the scheduled job. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/run", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return JobInfo(**response.json(), endpoint=self.endpoint) + + def update_scheduled_job_labels( + self, + *, + scheduled_job_id: str, + labels: dict[str, str], + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Update labels of an existing scheduled Job. + + Replaces all existing user-provided labels with the new labels. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + labels (`dict[str, str]`): + New labels to set on the scheduled job. Replaces all existing labels. + Both keys and values must be max 100 characters and contain only + alphanumeric characters, dots, dashes, and underscores. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`ScheduledJobInfo`]: The updated scheduled Job info. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().put( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/labels", + headers=self._build_hf_headers(token=token), + json={"labels": labels}, + ) + hf_raise_for_status(response) + return ScheduledJobInfo(**response.json()) + + @experimental + def create_scheduled_uv_job( + self, + script: str, + *, + script_args: list[str] | None = None, + schedule: str, + suspend: bool | None = None, + concurrency: bool | None = None, + dependencies: list[str] | None = None, + python: str | None = None, + image: str | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: JobHardware | str | None = None, + timeout: int | float | str | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + expose: list[int] | None = None, + resource_group_id: str | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Run a UV script Job on Hugging Face infrastructure. + + Args: + script (`str`): + Path or URL of the UV script, or a command. + + script_args (`list[str]`, *optional*) + Arguments to pass to the script, or a command. + + schedule (`str`): + One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a + CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). + + suspend (`bool`, *optional*): + If True, the scheduled Job is suspended (paused). Defaults to False. + + concurrency (`bool`, *optional*): + If True, multiple instances of this Job can run concurrently. Defaults to False. + + dependencies (`list[str]`, *optional*) + Dependencies to use to run the UV script. + + python (`str`, *optional*) + Use a specific Python version. Default is 3.12. + + image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"): + Use a custom Docker image with `uv` installed. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware. See [`JobHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + name (`str`, *optional*): + A name for the scheduled Job. Stored as the `name` label. Cannot be passed together with a `name` + key in `labels`. Names do not have to be unique. Defaults to a name derived from script and its arguments (with a short hash suffix). + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + expose (`list[int]`, *optional*): + Container ports to expose through the jobs proxy. Each listed port is reachable + on the public jobs domain (e.g. `https://--8000.hf.jobs`). Access always + requires an HF token with read access to the job's namespace. + + resource_group_id (`str`, *optional*): + The ID of the resource group to create the scheduled Job in. Used to control access to resources + within an organization and for cost attribution/spending-limit features. If not provided, the + scheduled Job is created outside of any resource group. + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + Schedule a script from a URL: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly") + ``` + + Schedule a local script: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly") + ``` + + Schedule a command: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "lighteval" + >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly") + ``` + """ + image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm" + if name is None and not (labels and "name" in labels): + name = _default_job_name_from_script(script, script_args or []) + + # Build command + command, env, secrets, extra_volumes = self._create_uv_command_env_and_secrets( + script=script, + script_args=script_args, + dependencies=dependencies, + python=python, + env=env, + secrets=secrets, + namespace=namespace, + token=token, + volumes=volumes, + ) + if extra_volumes: + volumes = (volumes or []) + extra_volumes + # Create RunCommand args + return self.create_scheduled_job( + image=image, + command=command, + schedule=schedule, + suspend=suspend, + concurrency=concurrency, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + name=name, + labels=labels, + volumes=volumes, + expose=expose, + resource_group_id=resource_group_id, + namespace=namespace, + token=token, + ) + + def _create_uv_command_env_and_secrets( + self, + *, + script: str, + script_args: list[str] | None, + dependencies: list[str] | None, + python: str | None, + env: dict[str, Any] | None, + secrets: dict[str, Any] | None, + namespace: str | None, + token: bool | str | None, + volumes: list[Volume] | None = None, + ) -> tuple[list[str], dict[str, Any], dict[str, Any], list[Volume]]: + env = env or {} + secrets = secrets or {} + + # Build command + uv_args = [] + if dependencies: + for dependency in dependencies: + uv_args += ["--with", dependency] + if python: + uv_args += ["--python", python] + script_args = script_args or [] + + if namespace is None: + namespace = self.whoami(token=token)["name"] + + # Find the local files to pass to the job + local_files_to_include = {candidate for candidate in [script] + script_args if Path(candidate).is_file()} + # Fail early for missing scripts or config files + missing_local_files = { + candidate + for candidate in [script] + script_args + if not Path(candidate).is_file() + and Path(candidate).suffix in [".py", ".sh", ".yaml", ".yml", ".toml"] + and not candidate.startswith("https://") + and not candidate.startswith("http://") + } + if missing_local_files: + raise FileNotFoundError(", ".join(missing_local_files)) + + if len(local_files_to_include) == 0: + # Direct URL execution or command - no upload needed + command = ["uv", "run"] + uv_args + [script] + script_args + return command, env, secrets, [] + + # Find appropriate remote file names + remote_to_local_file_names: dict[str, str] = {} + for local_file_to_include in local_files_to_include: + local_file_path = Path(local_file_to_include) + # Sanitize spaces for predictable remote paths + remote_file_path = Path(local_file_path.name.replace(" ", "_")) + if remote_file_path.name in remote_to_local_file_names: + for i in itertools.count(): + remote_file_name = remote_file_path.with_stem(remote_file_path.stem + f"({i})").name + if remote_file_name not in remote_to_local_file_names: + remote_to_local_file_names[remote_file_name] = local_file_to_include + break + else: + remote_to_local_file_names[remote_file_path.name] = local_file_to_include + local_to_remote_file_names = { + local_file_to_include: remote_file_name + for remote_file_name, local_file_to_include in remote_to_local_file_names.items() + } + + # Local files are shipped to the job via a bucket mounted at /data. + existing_mount_paths = {v.mount_path for v in (volumes or [])} + if constants.HF_JOBS_ARTIFACTS_MOUNT_PATH in existing_mount_paths: + raise ValueError( + f"Mount path {constants.HF_JOBS_ARTIFACTS_MOUNT_PATH!r} is reserved for Jobs artifacts when running local scripts. Mount your volume at a different path." + ) + + extra_volumes = self._upload_scripts_to_bucket( + namespace=namespace, + remote_to_local_file_names=remote_to_local_file_names, + token=token, + ) + # Rewrite script and script_args to reference the mounted path. The bucket + # volume is scoped to the per-job subfolder (via `Volume.path`), so the job + # container sees the uploaded files directly at the mount root. + mount_path = constants.HF_JOBS_ARTIFACTS_MOUNT_PATH + if script in local_to_remote_file_names: + script = f"{mount_path}/{local_to_remote_file_names[script]}" + script_args = [ + f"{mount_path}/{local_to_remote_file_names[arg]}" if arg in local_to_remote_file_names else arg + for arg in script_args + ] + command = ["uv", "run"] + uv_args + [script] + script_args + return command, env, secrets, extra_volumes + + def _upload_scripts_to_bucket( + self, + *, + namespace: str, + remote_to_local_file_names: dict[str, str], + token: bool | str | None, + ) -> list[Volume]: + """Upload script files to a per-job subfolder in the artifacts bucket. + + Creates a bucket `/jobs-artifacts` (if it doesn't exist) and uploads + each script to `{timestamp}-{random}/{remote_name}` inside it. Returns a + [`Volume`] scoped to that bucket subfolder. Volume is in read-write mode so the Job can save data back to this bucket. + """ + bucket_id = f"{namespace}/{constants.HF_JOBS_ARTIFACTS_BUCKET_NAME}" + subfolder_id = f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S')}-{token_hex(3)}" + + bucket_url = self.create_bucket(bucket_id=bucket_id, exist_ok=True, token=token, private=True) + + add_ops: list[tuple[str | Path | bytes, str]] = [ + (Path(local_path), f"{subfolder_id}/{remote_name}") + for remote_name, local_path in remote_to_local_file_names.items() + ] + self.batch_bucket_files(bucket_id=bucket_id, add=add_ops, token=token) + print(f"Your script and Job artifacts will be saved in this bucket: {bucket_url.url}") + + volume = Volume( + type="bucket", + source=bucket_id, + mount_path=constants.HF_JOBS_ARTIFACTS_MOUNT_PATH, + path=subfolder_id, + read_only=False, + ) + return [volume] + + def sync_job_volume( + self, + source: str | Path, + mount_path: str, + *, + remote_name: str | None = None, + read_only: bool = True, + namespace: str | None = None, + token: bool | str | None = None, + ) -> Volume: + """Sync a local directory to a bucket and return a [`Volume`] ready to mount in a Job. + + Files are uploaded to a subfolder of the `{namespace}/jobs-artifacts` bucket (auto-created as + private; a warning is emitted if it already exists and is public) using the same sync logic + as [`sync_bucket`]: re-syncing the same directory only + uploads new or modified files. By default the subfolder name is derived from the directory + path and the machine's hostname, so repeated calls from the same directory reuse the same + remote folder. Pass `remote_name` to use a fixed name instead. + + Note that the data is *copied* to the bucket, not mounted live: changes made locally after + the sync are not visible to the Job (re-run `sync_job_volume` to update), and the volume is + mounted read-only by default. To retrieve data written by a Job to a read-write volume, sync + the bucket folder back with [`sync_bucket`]. If the source directory is empty (e.g. an output + directory), a placeholder `.keep` file is uploaded so the volume can still be mounted. + + Args: + source (`str` or `Path`): + Path to a local directory to sync. + mount_path (`str`): + Mount path inside the Job container, e.g. `"/inputs"`. Must start with `/`. + remote_name (`str`, *optional*): + Name of the bucket subfolder to sync to. Defaults to a `{dirname}-{hash}` name derived + from the source path and the machine's hostname. + read_only (`bool`, *optional*, defaults to `True`): + Mount the volume read-only in the Job. Pass `False` to let the Job write back to the + bucket folder (e.g. to retrieve outputs with [`sync_bucket`] afterwards). + namespace (`str`, *optional*): + The namespace owning the `jobs-artifacts` bucket. Defaults to the current user's + namespace. Use the same namespace as the Job that will mount the volume. + token (`Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + [`Volume`]: A bucket volume scoped to the synced subfolder, to pass in the `volumes` list + of [`run_job`], [`run_uv_job`], [`create_scheduled_job`] or [`create_scheduled_uv_job`]. + + Example: + ```python + >>> from huggingface_hub import run_uv_job, sync_job_volume + + # Upload ./training-data once, then run multiple jobs against it + >>> volume = sync_job_volume("./training-data", "/data") + >>> run_uv_job("train.py", script_args=["--learning-rate", "0.01"], volumes=[volume]) + >>> run_uv_job("train.py", script_args=["--learning-rate", "0.05"], volumes=[volume]) + + # Read-write volume to retrieve outputs after the job completes + >>> volume = sync_job_volume("./outputs", "/outputs", read_only=False) + >>> job = run_uv_job("process.py", volumes=[volume]) + ``` + """ + if not mount_path.startswith("/"): + raise ValueError( + f"Mount path must be an absolute path inside the container (e.g. '/data'), got {mount_path!r}." + ) + source_path = Path(source).expanduser() + if not source_path.is_dir(): + raise ValueError(f"Source must be an existing local directory: '{source}'.") + + if namespace is None: + namespace = self.whoami(token=token)["name"] + bucket_id = f"{namespace}/{constants.HF_JOBS_ARTIFACTS_BUCKET_NAME}" + folder = remote_name or _derive_job_volume_name(source_path) + + # The jobs-artifacts bucket holds user scripts and data, so it must be private. A new bucket + # is created private here; if it already exists we cannot change its visibility, so warn when + # it is public instead of silently uploading the data to a publicly accessible bucket. + self.create_bucket(bucket_id=bucket_id, exist_ok=True, private=True, token=token) + if not self.bucket_info(bucket_id=bucket_id, token=token).private: + warnings.warn( + f"Bucket '{bucket_id}' already exists and is public: data synced for the Job will be " + f"publicly accessible. Make it private from {self.endpoint}/buckets/{bucket_id}.", + UserWarning, + ) + self.sync_bucket(str(source_path), f"hf://buckets/{bucket_id}/{folder}", token=token) + if not any(path.is_file() for path in source_path.rglob("*")): + # A folder cannot be empty in a bucket, and mounting a non-existent folder fails the Job. + # Upload a placeholder file so an empty directory (e.g. an output dir) can still be mounted. + self.batch_bucket_files(bucket_id, add=[(b"", f"{folder}/.keep")], token=token) + + return Volume(type="bucket", source=bucket_id, mount_path=mount_path, path=folder, read_only=read_only) + + @validate_hf_hub_args + def create_bucket( + self, + bucket_id: str, + *, + private: bool | None = None, + resource_group_id: str | None = None, + region: REPO_REGIONS | None = None, + exist_ok: bool = False, + token: bool | str | None = None, + ) -> BucketUrl: + """Create a bucket on the Hub. + + Args: + bucket_id (`str`): + A namespace (user or an organization) and a bucket name separated by a `/`. + If no namespace is provided, the bucket will be created in the current user's namespace. + private (`bool`, *optional*): + Whether to make the bucket private. If `None` (default), the bucket will be public unless the + organization's default is private. + resource_group_id (`str`, *optional*): + Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub + organizations and allow to define which members of the organization can access the resource. The ID + of a resource group can be found in the URL of the resource's page on the Hub + (e.g. `"66670e5163145ca562cb1988"`). To learn more about resource groups, see + https://huggingface.co/docs/hub/en/security-resource-groups. + region (`Literal["us", "eu"]`, *optional*): + Cloud region in which to create the bucket. Can be one of `"us"` or `"eu"`. If not specified, the bucket will be + created in the default region. Requires Team plan or above. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if the bucket already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketUrl`]: URL to the newly created bucket containing + attributes like `endpoint`, `namespace`, and `bucket_id`. + + Example: + ```python + >>> from huggingface_hub import create_bucket + + >>> url = create_bucket(bucket_id="my-bucket") + >>> url.bucket_id + 'user/my-bucket' + >>> url.url + 'https://huggingface.co/buckets/user/my-bucket' + >>> url.uri.to_uri() + 'hf://buckets/user/my-bucket' + + >>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True) + BucketUrl(...) + + >>> create_bucket(bucket_id="my-bucket", region="us") + BucketUrl(...) + ``` + """ + payload: dict[str, Any] = {} + if private is not None: + payload["private"] = private + if resource_group_id is not None: + payload["resourceGroupId"] = resource_group_id + if region is not None: + payload["region"] = region + + if "/" not in bucket_id: + namespace, name = "me", bucket_id # "me" namespace refers to the current user + else: + parsed = _parse_bucket_uri(bucket_id) + if parsed.path_in_repo: + raise ValueError(f"Invalid bucket ID: {bucket_id}") + namespace, name = parsed.id.split("/") + + response = get_session().post( + f"{self.endpoint}/api/buckets/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + try: + hf_raise_for_status(response) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + # Bucket already exists and `exist_ok=True` + pass + elif exist_ok and err.response.status_code in (401, 403): + # 401 -> if JWT token without create bucket scope + # 403 -> if no write permission on the namespace + # In both cases, bucket might already exist + try: + self.bucket_info(bucket_id=bucket_id, token=token) + return BucketUrl(f"{self.endpoint}/buckets/{bucket_id}", endpoint=self.endpoint) + except HfHubHTTPError: + raise err + else: + raise + return BucketUrl(response.json()["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def bucket_info( + self, + bucket_id: str, + *, + token: bool | str | None = None, + ) -> BucketInfo: + """Get information about a specific bucket on the Hub. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketInfo`]: The bucket information. + + Raises: + [`~errors.BucketNotFoundError`]: If the bucket cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + Example: + ```python + >>> from huggingface_hub import bucket_info + >>> info = bucket_info(bucket_id="Wauplin/first-bucket") + >>> info.id + 'Wauplin/first-bucket' + >>> info.private + False + >>> info.created_at + datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc) + >>> info.size + 551879671 + >>> info.total_files + 12 + ``` + """ + response = get_session().get( + f"{self.endpoint}/api/buckets/{bucket_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return BucketInfo(**response.json()) + + @validate_hf_hub_args + def list_buckets( + self, + namespace: str | None = None, + *, + search: str | None = None, + token: bool | str | None = None, + ) -> Iterable[BucketInfo]: + """List buckets on the Hub under a certain namespace. + + Args: + namespace (`str`, *optional*): + List buckets under this namespace (user or organization). Defaults to listing user's buckets. + search (`str`, *optional*): + A search string to filter bucket names. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[BucketInfo]`: An iterable of [`BucketInfo`] objects. + + Example: + ```python + >>> from huggingface_hub import list_buckets + >>> for bucket in list_buckets(): # lists buckets in the user's namespace + ... print(bucket) + + >>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization + ... print(bucket) + + >>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name + ... print(bucket) + ``` + """ + if namespace is None: + namespace = "me" + params: dict[str, Any] = {} + if search is not None: + params["search"] = search + for item in paginate( + f"{self.endpoint}/api/buckets/{namespace}", params=params, headers=self._build_hf_headers(token=token) + ): + yield BucketInfo(**item) + + @validate_hf_hub_args + def delete_bucket( + self, + bucket_id: str, + *, + missing_ok: bool = False, + token: bool | str | None = None, + ) -> None: + """Delete a bucket from the Hub. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + missing_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if the bucket does not exist. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~errors.BucketNotFoundError`]: If the bucket cannot be found and `missing_ok` is set to `False` (default). + + Example: + ```python + >>> from huggingface_hub import delete_bucket + >>> delete_bucket(bucket_id="Wauplin/first-bucket") + >>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True) + ``` + """ + response = get_session().delete( + f"{self.endpoint}/api/buckets/{bucket_id}", + headers=self._build_hf_headers(token=token), + ) + + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if e.response.status_code != 404 or not missing_ok: + raise + + @validate_hf_hub_args + def move_bucket( + self, + from_id: str, + to_id: str, + *, + token: bool | str | None = None, + ) -> None: + """Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2" + + Note there are certain limitations. For more information about moving + repositories, please see + https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo. + + Args: + from_id (`str`): + A namespace (user or an organization) and a bucket name separated + by a `/`. Original bucket identifier (e.g. `"username/my-bucket"`). + to_id (`str`): + A namespace (user or an organization) and a bucket name separated + by a `/`. Final bucket identifier (e.g. `"username/new-bucket-name"` + or `"organization/my-bucket"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~errors.BucketNotFoundError`]: + If the source bucket cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + Example: + ```python + >>> from huggingface_hub import move_bucket + + >>> # Rename a bucket within the same namespace + >>> move_bucket(from_id="username/old-name", to_id="username/new-name") + + >>> # Transfer a bucket to an organization + >>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket") + ``` + """ + if len(from_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)") + + if len(to_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)") + + json_payload = {"fromRepo": from_id, "toRepo": to_id, "type": "bucket"} + + path = f"{self.endpoint}/api/repos/move" + headers = self._build_hf_headers(token=token) + response = get_session().post(path, headers=headers, json=json_payload) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_bucket_tree( + self, + bucket_id: str, + prefix: str | None = None, + *, + recursive: bool | None = None, + token: str | bool | None = None, + ) -> Iterable[BucketFile | BucketFolder]: + """List files in a bucket. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + prefix (`str`, *optional*): + Filter results to files whose path starts with this prefix. + recursive (`bool`, *optional*): + If `True`, list files recursively. If `False` (default), list files and directories only at root. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Union[BucketFile, BucketFolder]]`: An iterable of [`BucketFile`] and [`BucketFolder`] objects + containing file and directory information (path, etc.). + + Example: + ```python + >>> from huggingface_hub import list_bucket_tree + >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"): + ... print(file_info.path) + + >>> # Filter by prefix + >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"): + ... print(file_info.path) + ``` + """ + encoded_prefix = "/" + quote(prefix, safe="") if prefix else "" + params = {} + if recursive is not None: + params["recursive"] = recursive + for item in paginate( + path=f"{self.endpoint}/api/buckets/{bucket_id}/tree{encoded_prefix}", + headers=self._build_hf_headers(token=token), + params=params, + ): + if item["type"] == "file": + yield BucketFile(**item) + elif item["type"] == "directory": + yield BucketFolder(**item) + + @validate_hf_hub_args + def get_bucket_paths_info( + self, + bucket_id: str, + paths: Iterable[str], + *, + token: str | bool | None = None, + ) -> Iterable[BucketFile]: + """ + Get information about a bucket's paths. + + Calls are made in batches of 1000 paths. Results are yielded as they are received. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + paths (`Iterable[str]`): + The paths to get information about. If a path does not exist, it is ignored without raising an exception. + Only file paths are supported. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[BucketFile]`: + The information about the paths, as an iterable of [`BucketFile`] objects. + + Example: + ```py + >>> from huggingface_hub import get_bucket_paths_info + >>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"]) + >>> for info in paths_info: + ... print(info) + BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc)) + BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc)) + ``` + """ + headers = self._build_hf_headers(token=token) + + for batch in chunk_iterable(paths, chunk_size=_BUCKET_PATHS_INFO_BATCH_SIZE): + response = http_backoff( + "POST", + f"{self.endpoint}/api/buckets/{bucket_id}/paths-info", + json={"paths": list(batch)}, + headers=headers, + ) + hf_raise_for_status(response) + for path_info in response.json(): + yield BucketFile(**path_info) + + @validate_hf_hub_args + def copy_files(self, source: str, destination: str, *, token: str | bool | None = None) -> None: + """Copy files between locations on the Hub. + + Copy files from a bucket or repository (model, dataset, space) to a bucket or another repository. + Both individual files and entire folders are supported. + + When copying folders, a trailing `/` on the source path uses rsync-style semantics: copy the *contents* + of the folder into the destination, without nesting the source folder itself. Without a trailing `/`, + the source folder is nested inside the destination (like `cp -r`). + + When copying from a repository to a bucket, `.gitattributes` files are automatically excluded since they + are git-specific metadata and not relevant in a bucket context. + + Repo-to-repo copies use [`CommitOperationCopy`] under the hood and create a commit on the destination + repository. Bucket-to-repo copies are not supported. + + > [!WARNING] + > Server-side copies only work within the same [storage region](https://huggingface.co/docs/hub/storage-regions). + + Args: + source (`str`): + Source location as an `hf://` URI. Can be a bucket path (e.g. `"hf://buckets/my-bucket/path/to/file"`) + or a repo path (e.g. `"hf://username/my-model/weights.bin"`, `"hf://datasets/username/my-dataset/data/"`). + destination (`str`): + Destination location as an `hf://` URI pointing to a bucket (e.g. `"hf://buckets/my-bucket/target/path"`) + or a repository (e.g. `"hf://username/my-model/target/path"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): + If source/destination URIs are invalid or if copying from a bucket to a repo. + + Example: + ```python + >>> from huggingface_hub import copy_files + + # Copy a single file between buckets + >>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin") + + # Copy a folder into another bucket (nests: backup/models/...) + >>> copy_files("hf://buckets/my-bucket/models", "hf://buckets/other-bucket/backup/") + + # Copy folder contents (trailing /): files go directly into backup/ + >>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/") + + # Copy a file from a model repo to a bucket + >>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/") + + # Copy an entire dataset to a bucket + >>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/") + + # Copy files between repositories + >>> copy_files("hf://username/source-model/", "hf://username/dest-model/") + + # Copy a file from one repo to another + >>> copy_files("hf://username/source-model/config.json", "hf://username/dest-model/config.json") + ``` + """ + source_uri = parse_hf_uri(source) + destination_uri = parse_hf_uri(destination) + + # Rsync-style trailing slash on source: "copy contents of" instead of "copy directory into". + # Check before parsing strips the slash. + merge_contents = source.endswith("/") + + if destination_uri.is_repo: + if source_uri.is_bucket: + raise ValueError("Bucket-to-repo copy is not supported.") + self._copy_to_repo(source_uri, destination_uri, merge_contents, source, destination, token=token) + else: + self._copy_to_bucket(source_uri, destination_uri, merge_contents, source, destination, token=token) + + def _copy_to_bucket( + self, + source: HfUri, + destination: HfUri, + merge_contents: bool, + source_str: str, + destination_str: str, + *, + token: str | bool | None = None, + ) -> None: + destination_bucket_id = destination.id + destination_path = destination.path_in_repo + destination_is_directory = False + destination_exists_as_directory = False + + if destination_path == "": + destination_is_directory = True + destination_exists_as_directory = True + else: + dest_path_info = list(self.get_bucket_paths_info(destination_bucket_id, [destination_path], token=token)) + if dest_path_info: + destination_is_directory = False + else: + destination_exists_as_directory = any( + self.list_bucket_tree(destination_bucket_id, prefix=destination_path, recursive=False, token=token) + ) + destination_is_directory = destination_exists_as_directory or destination_str.endswith("/") + + all_adds: list[tuple[str, str]] = [] + all_copies: list[_BucketCopyFile] = [] + pending_downloads: list[tuple[str, str]] = [] + + def _resolve_target_path(src_file_path: str, src_root_path: str | None, is_single_file: bool) -> str: + return _resolve_copy_target_path( + src_file_path, + src_root_path, + is_single_file, + destination_path, + destination_is_directory, + destination_exists_as_directory, + merge_contents, + ) + + def _build_copy_op( + target_path: str, xet_hash: str, size: int, source_repo_type: str, source_repo_id: str + ) -> _BucketCopyFile: + """Server-side copy by xet hash — no data transfer needed.""" + return _BucketCopyFile( + destination=target_path, + xet_hash=xet_hash, + source_repo_type=source_repo_type, + source_repo_id=source_repo_id, + size=size, + ) + + def _add_repo_file(file: RepoFile, target_path: str) -> None: + if file.xet_hash is not None: + all_copies.append(_build_copy_op(target_path, file.xet_hash, file.size, source.type, source.id)) + else: + pending_downloads.append((file.path, target_path)) + + if source.is_bucket: + source_path = source.path_in_repo + source_path_info = list(self.get_bucket_paths_info(source.id, [source_path], token=token)) + + if source_path_info: + source_file = source_path_info[0] + target_path = _resolve_target_path(source_file.path, None, is_single_file=True) + all_copies.append( + _build_copy_op(target_path, source_file.xet_hash, source_file.size, "bucket", source.id) + ) + else: + for item in self.list_bucket_tree(source.id, prefix=source_path or None, recursive=True, token=token): + if not isinstance(item, BucketFile): + continue + if source_path and not (item.path == source_path or item.path.startswith(source_path + "/")): + continue + target_path = _resolve_target_path(item.path, source_path or None, is_single_file=False) + all_copies.append(_build_copy_op(target_path, item.xet_hash, item.size, "bucket", source.id)) + else: + for file, target_path in self._iter_repo_files_for_copy( + source, + destination_path, + destination_is_directory, + destination_exists_as_directory, + merge_contents, + token=token, + ): + # Skip .gitattributes files (git-specific metadata, not relevant in a bucket) + if file.path.rsplit("/", 1)[-1] == ".gitattributes": + continue + _add_repo_file(file, target_path) + + if not all_copies and not all_adds and not pending_downloads: + if source.is_bucket: + raise EntryNotFoundError(f"No files found at '{source_str}' in bucket '{source.id}'.") + else: + raise EntryNotFoundError(f"No files found at '{source_str}' in {source.type} '{source.id}'.") + + if pending_downloads: + + def _download_and_collect(item: tuple[str, str]) -> None: + file_path, target_path = item + local_path = self.hf_hub_download( + repo_id=source.id, + repo_type=source.type, + filename=file_path, + revision=source.revision, + token=token, + tqdm_class=silent_tqdm, # type: ignore + ) + all_adds.append((local_path, target_path)) + + hf_thread_map(_download_and_collect, pending_downloads, desc="Downloading text files for copy") + + # Send copies first (no upload needed), then adds (may need upload) + if all_copies: + for copy_chunk in chunk_iterable(all_copies, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(destination_bucket_id, copy=list(copy_chunk), token=token) + if all_adds: + for add_chunk in chunk_iterable(all_adds, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(destination_bucket_id, add=list(add_chunk), token=token) + + def _iter_repo_files_for_copy( + self, + source: HfUri, + destination_path: str, + destination_is_directory: bool, + destination_exists_as_directory: bool, + merge_contents: bool, + *, + token: str | bool | None = None, + ) -> Iterable[tuple[RepoFile, str]]: + """Yield (file, target_path) pairs from a repo source, with target paths resolved.""" + source_path = source.path_in_repo + source_repo_path_info: list[RepoFile | RepoFolder] = [] + if source_path != "": + source_repo_path_info = self.get_paths_info( + repo_id=source.id, + paths=[source_path], + repo_type=source.type, + revision=source.revision, + token=token, + ) + + def _resolve(src_file_path: str, src_root_path: str | None, is_single_file: bool) -> str: + return _resolve_copy_target_path( + src_file_path, + src_root_path, + is_single_file, + destination_path, + destination_is_directory, + destination_exists_as_directory, + merge_contents, + ) + + if len(source_repo_path_info) == 1 and isinstance(source_repo_path_info[0], RepoFile): + file = source_repo_path_info[0] + yield file, _resolve(file.path, None, is_single_file=True) + else: + for repo_item in self.list_repo_tree( + repo_id=source.id, + path_in_repo=source_path, + recursive=True, + repo_type=source.type, + revision=source.revision, + token=token, + ): + if not isinstance(repo_item, RepoFile): + continue + yield repo_item, _resolve(repo_item.path, source_path or None, is_single_file=False) + + def _copy_to_repo( + self, + source: HfUri, + destination: HfUri, + merge_contents: bool, + source_str: str, + destination_str: str, + *, + token: str | bool | None = None, + ) -> None: + destination_path = destination.path_in_repo + destination_is_directory = False + destination_exists_as_directory = False + + if destination_path == "": + destination_is_directory = True + destination_exists_as_directory = True + else: + dest_path_info = self.get_paths_info( + repo_id=destination.id, + paths=[destination_path], + repo_type=destination.type, + revision=destination.revision, + token=token, + ) + if len(dest_path_info) == 1 and isinstance(dest_path_info[0], RepoFile): + destination_is_directory = False + elif len(dest_path_info) == 1 and isinstance(dest_path_info[0], RepoFolder): + destination_is_directory = True + destination_exists_as_directory = True + else: + try: + destination_exists_as_directory = any( + self.list_repo_tree( + repo_id=destination.id, + path_in_repo=destination_path, + repo_type=destination.type, + revision=destination.revision, + token=token, + ) + ) + except RemoteEntryNotFoundError: + destination_exists_as_directory = False + destination_is_directory = destination_exists_as_directory or destination_str.endswith("/") + + is_same_repo = source.id == destination.id and source.type == destination.type + + commit_ops: list[CommitOperationCopy] = [ + CommitOperationCopy( + src_path_in_repo=file.path, + path_in_repo=target, + src_revision=source.revision, + src_repo_id=None if is_same_repo else source.id, + src_repo_type=None if is_same_repo else source.type, + ) + for file, target in self._iter_repo_files_for_copy( + source, + destination_path, + destination_is_directory, + destination_exists_as_directory, + merge_contents, + token=token, + ) + ] + + if not commit_ops: + raise EntryNotFoundError(f"No files found at '{source_str}' in {source.type} '{source.id}'.") + + self.create_commit( + repo_id=destination.id, + repo_type=destination.type, + revision=destination.revision, + operations=commit_ops, + commit_message=f"Copy files from {source.type}s/{source.id}", + token=token, + ) + + @validate_hf_hub_args + def batch_bucket_files( + self, + bucket_id: str, + *, + add: list[tuple[str | Path | bytes, str]] | None = None, + copy: list[tuple[str, str, str, str]] | None = None, + delete: list[str] | None = None, + token: str | bool | None = None, + ): + """Add, copy, and/or delete files in a bucket. + + This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded, + copied, or deleted while others haven't. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + add (`list` of `tuple`, *optional*): + Files to upload. Each element is a `(source, destination)` tuple where `source` is a path to a local + file (`str` or `Path`) or raw `bytes` content, and `destination` is the path in the bucket. + copy (`list` of `tuple`, *optional*): + Files to copy by xet hash. Each element is a `(source_repo_type, source_repo_id, xet_hash, + destination)` tuple where: + - `source_repo_type` is the type of the source repository: `"model"`, `"dataset"`, `"space"`, or + `"bucket"`. + - `source_repo_id` is the ID of the source repository or bucket (e.g. `"username/my-model"`). + - `xet_hash` is the xet hash of the file to copy. + - `destination` is the destination path in the bucket. + This is a server-side operation — no data is downloaded or re-uploaded. + delete (`list` of `str`, *optional*): + Paths of files to delete from the bucket. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```python + >>> from huggingface_hub import batch_bucket_files + + # Upload files + >>> batch_bucket_files( + ... "username/my-bucket", + ... add=[ + ... ("./model.safetensors", "models/model.safetensors"), + ... (b'{{"key": "value"}}', "config.json"), + ... ], + ... ) + + # Copy xet files from another bucket or repo (server-side, no data transfer) + >>> batch_bucket_files( + ... "username/my-bucket", + ... copy=[ + ... ("bucket", "username/source-bucket", "", "models/model.safetensors"), + ... ("model", "username/my-model", "", "models/config.safetensors"), + ... ], + ... ) + + # Delete files + >>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"]) + + # Upload and delete in one batch + >>> batch_bucket_files( + ... "username/my-bucket", + ... add=[("./new.txt", "new.txt")], + ... delete=["old.txt"], + ... ) + ``` + """ + add = add or [] + copy = copy or [] + delete = delete or [] + + # Small batch: do everything in one call + if len(add) + len(copy) + len(delete) <= _BUCKET_BATCH_ADD_CHUNK_SIZE: + self._batch_bucket_files(bucket_id, add=add, copy=copy, delete=delete, token=token) # type: ignore + return + + # Large batch: chunk copies first (no upload), then adds, then deletes + from .utils._xet_progress_reporting import XetUploadProgressReporter + + if add and not are_progress_bars_disabled(): + progress = XetUploadProgressReporter(total_files=len(add)) + else: + progress = None + + try: + for copy_chunk in chunk_iterable(copy, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, copy=list(copy_chunk), token=token) + + for add_chunk in chunk_iterable(add, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, add=list(add_chunk), token=token, _progress=progress) + + for delete_chunk in chunk_iterable(delete, chunk_size=_BUCKET_BATCH_DELETE_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, delete=list(delete_chunk), token=token) + finally: + if progress is not None: + progress.close() + + return + + def _batch_bucket_files( + self, + bucket_id: str, + *, + add: list[tuple[str | Path | bytes, str] | _BucketAddFile] | None = None, + copy: list[tuple[str, str, str, str] | _BucketCopyFile] | None = None, + delete: list[str | _BucketDeleteFile] | None = None, + token: str | bool | None = None, + _progress: XetUploadProgressReporter | None = None, + ): + """Internal method: process a single batch of bucket file operations (upload to XET + call /batch).""" + # Convert public API inputs to internal operation objects + operations: list[_BucketAddFile | _BucketCopyFile | _BucketDeleteFile] = [] + if add: + for add_item in add: + if isinstance(add_item, _BucketAddFile): + operations.append(add_item) + else: + source, destination = add_item + operations.append(_BucketAddFile(source=source, destination=destination)) + if copy: + for copy_item in copy: + if isinstance(copy_item, _BucketCopyFile): + operations.append(copy_item) + else: + source_repo_type, source_repo_id, xet_hash, destination = copy_item + operations.append( + _BucketCopyFile( + destination=destination, + xet_hash=xet_hash, + source_repo_type=source_repo_type, + source_repo_id=source_repo_id, + ) + ) + if delete: + for delete_item in delete: + if isinstance(delete_item, _BucketDeleteFile): + operations.append(delete_item) + else: + operations.append(_BucketDeleteFile(path=delete_item)) + + if not operations: + return + + from hf_xet import SKIP_SHA256 + + from .utils._xet import ( + XetTokenType, + abort_xet_session, + get_xet_session, + xet_connection_info_refresh_url, + xet_headers_without_auth, + ) + from .utils._xet_progress_reporting import XetUploadProgressReporter + + headers = self._build_hf_headers(token=token) + + add_operations = [op for op in operations if isinstance(op, _BucketAddFile)] + add_operations_to_upload = [op for op in add_operations if op.xet_hash is None] + add_bytes_operations = [op for op in add_operations if isinstance(op.source, bytes)] + add_path_operations = [op for op in add_operations if not isinstance(op.source, bytes)] + + if len(add_operations_to_upload) > 0: + refresh_url = xet_connection_info_refresh_url( + token_type=XetTokenType.WRITE, + repo_id=bucket_id, + repo_type="bucket", + endpoint=self.endpoint, + ) + xet_headers = xet_headers_without_auth(headers) + + owns_progress = _progress is None + if _progress is not None: + progress = _progress + progress.reset_for_next_commit() + progress_callback = progress.update_progress + elif not are_progress_bars_disabled(): + progress = XetUploadProgressReporter() + progress_callback = progress.update_progress + else: + progress, progress_callback = None, None + + session = get_xet_session() + + try: + with session.new_upload_commit( + token_refresh_url=refresh_url, + token_refresh_headers=headers, + custom_headers=xet_headers, + progress_callback=progress_callback, + ) as commit: + handles = [] + for op in add_path_operations: + if op.xet_hash is None: + handles.append((commit.start_upload_file(str(op.source), sha256=SKIP_SHA256), op)) + for op in add_bytes_operations: + if op.xet_hash is None: + handles.append((commit.start_upload_bytes(op.source, sha256=SKIP_SHA256), op)) + for handle, op in handles: + result = handle.result() + op.xet_hash = result.xet_info.hash + op.size = result.xet_info.file_size + except KeyboardInterrupt: + abort_xet_session() + raise + finally: + if owns_progress and progress is not None: + progress.close() + + def _payload_as_ndjson() -> Iterable[bytes]: + for op in operations: + if isinstance(op, _BucketAddFile): + payload = { + "type": "addFile", + "path": op.destination, + "xetHash": op.xet_hash, + "mtime": op.mtime, + } + if op.content_type is not None: + payload["contentType"] = op.content_type + elif isinstance(op, _BucketCopyFile): + payload = { + "type": "copyFile", + "path": op.destination, + "xetHash": op.xet_hash, + "sourceRepoType": op.source_repo_type, + "sourceRepoId": op.source_repo_id, + } + else: + payload = { + "type": "deleteFile", + "path": op.path, + } + yield json.dumps(payload).encode() + yield b"\n" + + headers = { + "Content-Type": "application/x-ndjson", + **headers, + } + data = b"".join(_payload_as_ndjson()) + + response = http_backoff( + "POST", f"{self.endpoint}/api/buckets/{bucket_id}/batch", headers=headers, content=data + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def get_bucket_file_metadata( + self, + bucket_id: str, + remote_path: str, + *, + token: str | bool | None = None, + ) -> BucketFileMetadata: + """Fetch metadata of a file in a bucket. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + remote_path (`str`): + The path of the file in the bucket. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketFileMetadata`]: The file metadata containing size and xet information. + + Example: + ```python + >>> from huggingface_hub import get_bucket_file_metadata + >>> metadata = get_bucket_file_metadata( + ... bucket_id="username/my-bucket", + ... remote_path="models/model.safetensors", + ... ) + >>> metadata.size + 42000 + ``` + """ + response = _httpx_follow_relative_redirects_with_backoff( + "HEAD", + f"{self.endpoint}/buckets/{bucket_id}/resolve/{quote(remote_path, safe='')}", + headers=self._build_hf_headers(token=token), + retry_on_errors=True, + ) + + xet_file_data = parse_xet_file_data_from_response(response) + if xet_file_data is None: + raise ValueError(f"Could not parse xet file data for '{remote_path}' in bucket '{bucket_id}'.") + + size = response.headers.get("Content-Length") + if size is None: + raise ValueError(f"Could not get size for '{remote_path}' in bucket '{bucket_id}'.") + + return BucketFileMetadata(size=int(size), xet_file_data=xet_file_data) + + @validate_hf_hub_args + def download_bucket_files( + self, + bucket_id: str, + files: list[tuple[str | BucketFile, str | Path]], + *, + raise_on_missing_files: bool = False, + token: str | bool | None = None, + ) -> None: + """Download files from a bucket. + + Files input is a list of `(remote file, local file)` tuples where `remote file` is either the path of the file + in the bucket or a [`BucketFile`] object, and `local file` is the destination path on the local filesystem. + When passing a [`BucketFile`] object (obtained from [`list_bucket_tree`]), the method will skip the metadata + fetching step and directly download the files. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + files (`list[tuple[Union[str, BucketFile], Union[str, Path]]]`): + Files to download as a list of tuple (source, destination). See description above for format details. + raise_on_missing_files (`bool`, *optional*): + If `True`, raise an [`EntryNotFoundError`] when a requested file does not exist in the bucket. If + `False` (default), missing files are skipped with a warning. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```python + >>> from huggingface_hub import download_bucket_files + + >>> download_bucket_files( + ... bucket_id="username/my-bucket", + ... files=[ + ... ("models/model.safetensors", "./local/model.safetensors"), + ... ("config.json", "./local/config.json"), + ... ], + ... ) + ``` + + ```python + >>> from huggingface_hub import download_bucket_files + + >>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")] + >>> download_bucket_files( + ... bucket_id="username/my-bucket", + ... files=[(file, f"./local/{file.path}") for file in parquet_files], + ... ) + ``` + """ + from hf_xet import XetFileInfo # type: ignore[no-redef] + + from .utils._xet import abort_xet_session, get_xet_session, xet_headers_without_auth + + headers = self._build_hf_headers(token=token) + + if len(files) == 0: + return + + # Resolve all string paths to BucketFile objects in a single batch request + str_paths = [path for path, _ in files if not isinstance(path, BucketFile)] + bucket_files_by_path: dict[str, BucketFile] = {} + if str_paths: + bucket_files_by_path = { + info.path: info for info in self.get_bucket_paths_info(bucket_id, str_paths, token=token) + } + + # Check for missing files + missing_paths = [path for path in str_paths if path not in bucket_files_by_path] + if missing_paths: + if raise_on_missing_files: + raise EntryNotFoundError( + f"{len(missing_paths)} file(s) not found in bucket '{bucket_id}': {', '.join(missing_paths)}" + ) + for path in missing_paths: + warnings.warn(f"File '{path}' not found in bucket '{bucket_id}'. Skipping.") + + non_zero_download_items: list[tuple[XetFileInfo, str]] = [] + first_valid_bucket_file: BucketFile | None = None + for remote_file, local_path in files: + if not isinstance(remote_file, BucketFile): + if remote_file not in bucket_files_by_path: + continue # skip missing files (already warned above) + remote_file = bucket_files_by_path[remote_file] + if first_valid_bucket_file is None: + first_valid_bucket_file = remote_file + dest_path = Path(local_path).absolute() + if remote_file.size == 0: + # Create empty file without downloading + if dest_path.exists(): + if dest_path.is_dir(): + raise IsADirectoryError(f"Expected file but found directory at '{dest_path}'") + if dest_path.stat().st_size != 0: + dest_path.write_bytes(b"") + else: + dest_path.parent.mkdir(parents=True, exist_ok=True) + dest_path.touch() + else: + non_zero_download_items.append((XetFileInfo(remote_file.xet_hash, remote_file.size), str(dest_path))) + + if len(non_zero_download_items) == 0 or first_valid_bucket_file is None: + return + + # Fetch refresh route (same for all files in this bucket) + remote_path = first_valid_bucket_file.path + metadata = self.get_bucket_file_metadata(bucket_id, remote_path, token=token) + + xet_headers = xet_headers_without_auth(headers) + + # Download files + from .utils._xet_progress_reporting import XetDownloadProgressReporter + + session = get_xet_session() + + with XetDownloadProgressReporter( + reconstruction_desc="Downloading bucket files", + transfer_desc="Downloading bytes", + total=sum(xet_info.file_size for xet_info, _ in non_zero_download_items), + log_level=logger.getEffectiveLevel(), + name="huggingface_hub.download_bucket_files", + ) as progress: + try: + with session.new_file_download_group( + token_refresh_url=metadata.xet_file_data.refresh_route, + token_refresh_headers=headers, + custom_headers=xet_headers, + progress_callback=progress.update_progress, + ) as group: + for xet_info, dest in non_zero_download_items: + group.start_download_file(xet_info, dest) + except KeyboardInterrupt: + abort_xet_session() + raise + + @validate_hf_hub_args + def sync_bucket( + self, + source: str | None = None, + dest: str | None = None, + *, + delete: bool = False, + ignore_times: bool = False, + ignore_sizes: bool = False, + existing: bool = False, + ignore_existing: bool = False, + include: list[str] | None = None, + exclude: list[str] | None = None, + filter_from: str | None = None, + plan: str | None = None, + apply: str | None = None, + dry_run: bool = False, + verbose: bool = False, + quiet: bool = False, + token: bool | str | None = None, + ) -> SyncPlan: + """Sync files between a local directory and a bucket. + + This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path + (``hf://buckets/...``) and the other must be a local directory path. + + Args: + source (`str`, *optional*): + Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + dest (`str`, *optional*): + Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + delete (`bool`, *optional*, defaults to `False`): + Delete destination files not present in source. + ignore_times (`bool`, *optional*, defaults to `False`): + Skip files only based on size, ignoring modification times. + ignore_sizes (`bool`, *optional*, defaults to `False`): + Skip files only based on modification times, ignoring sizes. + existing (`bool`, *optional*, defaults to `False`): + Skip creating new files on receiver (only update existing files). + ignore_existing (`bool`, *optional*, defaults to `False`): + Skip updating files that exist on receiver (only create new files). + include (`list[str]`, *optional*): + Include files matching patterns (fnmatch-style). + exclude (`list[str]`, *optional*): + Exclude files matching patterns (fnmatch-style). + filter_from (`str`, *optional*): + Path to a filter file with include/exclude rules. + plan (`str`, *optional*): + Save sync plan to this JSONL file instead of executing. + apply (`str`, *optional*): + Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed. + dry_run (`bool`, *optional*, defaults to `False`): + Print sync plan to stdout as JSONL without executing. + verbose (`bool`, *optional*, defaults to `False`): + Show detailed per-file operations. + quiet (`bool`, *optional*, defaults to `False`): + Suppress all output and progress bars. + token (Union[bool, str, None], optional): + A valid user access token. If not provided, the locally saved token will be used. + + Returns: + [`SyncPlan`]: The computed (or loaded) sync plan. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Upload local directory to bucket + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket") + + # Download bucket to local directory + >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data") + + # Sync with delete and filtering + >>> api.sync_bucket( + ... "./data", + ... "hf://buckets/username/my-bucket", + ... delete=True, + ... include=["*.safetensors"], + ... ) + + # Dry run: preview what would be synced + >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True) + >>> plan.summary() + {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096} + + # Save plan for review, then apply + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl") + >>> api.sync_bucket(apply="sync-plan.jsonl") + ``` + """ + return sync_bucket_internal( + source=source, + dest=dest, + api=self, + delete=delete, + ignore_times=ignore_times, + ignore_sizes=ignore_sizes, + existing=existing, + ignore_existing=ignore_existing, + include=include, + exclude=exclude, + filter_from=filter_from, + plan=plan, + apply=apply, + dry_run=dry_run, + verbose=verbose, + quiet=quiet, + token=token, + ) + + +def _parse_revision_from_pr_url(pr_url: str) -> str: + """Safely parse revision number from a PR url. + + Example: + ```py + >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2") + "refs/pr/2" + ``` + """ + re_match = re.match(_REGEX_DISCUSSION_URL, pr_url) + if re_match is None: + raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'") + return f"refs/pr/{re_match[1]}" + + +def parse_local_safetensors_file_metadata(path: str | Path) -> SafetensorsFileMetadata: + """ + Parse metadata from a local safetensors file. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + path (`str` or `Path`): + Path to the safetensors file. + + Returns: + [`SafetensorsFileMetadata`]: information related to the safetensors file. + + Raises: + [`SafetensorsParsingError`]: + If the safetensors file header couldn't be parsed correctly. + `FileNotFoundError`: + If the file does not exist. + + Example: + ```py + >>> metadata = parse_local_safetensors_file_metadata("path/to/model.safetensors") + >>> metadata + SafetensorsFileMetadata( + metadata={'format': 'pt'}, + tensors={'layer.weight': TensorInfo(dtype='F32', shape=[512, 512], ...}, ...} + ) + >>> metadata.parameter_count + {'F32': 262144} + ``` + """ + path = Path(path) + filename = path.name + context_msg = f"path '{path}'" + + with open(path, "rb") as f: + # 1. Read first 8 bytes and parse/validate metadata size using shared helper + size_bytes = f.read(8) + metadata_size = _get_safetensors_metadata_size(size_bytes, filename, context_msg) + + # 2. Read metadata bytes + metadata_as_bytes = f.read(metadata_size) + if len(metadata_as_bytes) < metadata_size: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is truncated. Expected " + f"{metadata_size} bytes of metadata but got {len(metadata_as_bytes)}." + ) + + # 3. Parse using shared helper + return _parse_safetensors_header(metadata_as_bytes, filename, context_msg) + + +def get_local_safetensors_metadata(path: str | Path) -> SafetensorsRepoMetadata: + """ + Parse metadata for a local safetensors file or folder. + + Supports: + - Single safetensors file (e.g., `model.safetensors`) + - Directory with non-sharded model (contains `model.safetensors`) + - Directory with sharded model (contains `model.safetensors.index.json`) + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + path (`str` or `Path`): + Path to a safetensors file or directory containing safetensors files. + + Returns: + [`SafetensorsRepoMetadata`]: information related to the safetensors repo. + + Raises: + [`NotASafetensorsRepoError`]: + If the path is not a valid safetensors file or folder (i.e., doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file). + [`SafetensorsParsingError`]: + If a safetensors file header couldn't be parsed correctly. + `FileNotFoundError`: + If the path does not exist. + + Example: + ```py + # Parse single safetensors file + >>> metadata = get_local_safetensors_metadata("path/to/model.safetensors") + >>> metadata + SafetensorsRepoMetadata(metadata=None, sharded=False, weight_map={...}, files_metadata={...}) + + # Parse directory with sharded model + >>> metadata = get_local_safetensors_metadata("path/to/model_folder") + >>> metadata + SafetensorsRepoMetadata(metadata={'total_size': ...}, sharded=True, weight_map={...}, files_metadata={...}) + >>> len(metadata.files_metadata) + 3 # Number of safetensors shards + ``` + """ + path = Path(path) + + # Case 1: Direct path to a safetensors file + if path.is_file(): + file_metadata = parse_local_safetensors_file_metadata(path) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={tensor_name: path.name for tensor_name in file_metadata.tensors.keys()}, + files_metadata={path.name: file_metadata}, + ) + + # Case 2: Directory + if not path.is_dir(): + raise FileNotFoundError(f"Path '{path}' does not exist.") + + single_file_path = path / constants.SAFETENSORS_SINGLE_FILE + index_file_path = path / constants.SAFETENSORS_INDEX_FILE + + # Case 2a: Non-sharded model (single model.safetensors file) + if single_file_path.exists(): + file_metadata = parse_local_safetensors_file_metadata(single_file_path) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={ + tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys() + }, + files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata}, + ) + + # Case 2b: Sharded model (model.safetensors.index.json) + if index_file_path.exists(): + with open(index_file_path) as f: + index = json.load(f) + + weight_map = index.get("weight_map", {}) + + # Parse metadata from each shard + files_metadata = {} + for shard_filename in set(weight_map.values()): + shard_path = path / shard_filename + files_metadata[shard_filename] = parse_local_safetensors_file_metadata(shard_path) + + return SafetensorsRepoMetadata( + metadata=index.get("metadata", None), + sharded=True, + weight_map=weight_map, + files_metadata=files_metadata, + ) + + # Not a valid safetensors folder + raise NotASafetensorsRepoError( + f"'{path}' is not a valid safetensors folder. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or " + f"'{constants.SAFETENSORS_SINGLE_FILE}' files." + ) + + +api = HfApi() + +whoami = api.whoami +auth_check = api.auth_check + +list_models = api.list_models +model_info = api.model_info + +list_datasets = api.list_datasets +list_dataset_parquet_files = api.list_dataset_parquet_files +dataset_info = api.dataset_info +get_dataset_leaderboard = api.get_dataset_leaderboard + +list_spaces = api.list_spaces +list_space_templates = api.list_space_templates +search_spaces = api.search_spaces +space_info = api.space_info + +kernel_info = api.kernel_info + +list_papers = api.list_papers +paper_info = api.paper_info +read_paper = api.read_paper +list_daily_papers = api.list_daily_papers + +repo_exists = api.repo_exists +revision_exists = api.revision_exists +file_exists = api.file_exists +repo_info = api.repo_info +resolve_revision = api.resolve_revision +list_repo_files = api.list_repo_files +list_repo_refs = api.list_repo_refs +list_repo_commits = api.list_repo_commits +list_repo_tree = api.list_repo_tree +get_paths_info = api.get_paths_info +verify_repo_checksums = api.verify_repo_checksums + +get_model_tags = api.get_model_tags +get_dataset_tags = api.get_dataset_tags + +create_commit = api.create_commit +create_repo = api.create_repo +delete_repo = api.delete_repo +update_repo_settings = api.update_repo_settings +move_repo = api.move_repo +upload_file = api.upload_file +upload_folder = api.upload_folder +delete_file = api.delete_file +delete_folder = api.delete_folder +delete_files = api.delete_files +upload_large_folder = api.upload_large_folder +preupload_lfs_files = api.preupload_lfs_files +create_branch = api.create_branch +delete_branch = api.delete_branch +create_tag = api.create_tag +delete_tag = api.delete_tag +get_full_repo_name = api.get_full_repo_name + +# Danger-zone API +super_squash_history = api.super_squash_history +list_lfs_files = api.list_lfs_files +permanently_delete_lfs_files = api.permanently_delete_lfs_files + +# Safetensors helpers +get_safetensors_metadata = api.get_safetensors_metadata +parse_safetensors_file_metadata = api.parse_safetensors_file_metadata + +# Background jobs +run_as_future = api.run_as_future + +# Activity API +list_liked_repos = api.list_liked_repos +list_repo_likers = api.list_repo_likers +list_user_repos = api.list_user_repos +unlike = api.unlike + +# Community API +get_discussion_details = api.get_discussion_details +get_repo_discussions = api.get_repo_discussions +create_discussion = api.create_discussion +create_pull_request = api.create_pull_request +change_discussion_status = api.change_discussion_status +comment_discussion = api.comment_discussion +edit_discussion_comment = api.edit_discussion_comment +rename_discussion = api.rename_discussion +merge_pull_request = api.merge_pull_request + +# Space API +get_space_secrets = api.get_space_secrets +add_space_secret = api.add_space_secret +delete_space_secret = api.delete_space_secret +get_space_variables = api.get_space_variables +add_space_variable = api.add_space_variable +delete_space_variable = api.delete_space_variable +get_space_runtime = api.get_space_runtime +list_spaces_hardware = api.list_spaces_hardware +request_space_hardware = api.request_space_hardware +set_space_sleep_time = api.set_space_sleep_time +pause_space = api.pause_space +restart_space = api.restart_space +duplicate_repo = api.duplicate_repo +duplicate_space = api.duplicate_space +request_space_storage = api.request_space_storage +delete_space_storage = api.delete_space_storage +set_space_volumes = api.set_space_volumes +delete_space_volumes = api.delete_space_volumes +enable_space_dev_mode = api.enable_space_dev_mode +disable_space_dev_mode = api.disable_space_dev_mode +fetch_space_logs = api.fetch_space_logs +wait_for_space = api.wait_for_space + +# Inference Endpoint API +list_inference_endpoints = api.list_inference_endpoints +create_inference_endpoint = api.create_inference_endpoint +get_inference_endpoint = api.get_inference_endpoint +update_inference_endpoint = api.update_inference_endpoint +delete_inference_endpoint = api.delete_inference_endpoint +pause_inference_endpoint = api.pause_inference_endpoint +resume_inference_endpoint = api.resume_inference_endpoint +scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint +create_inference_endpoint_from_catalog = api.create_inference_endpoint_from_catalog +list_inference_catalog = api.list_inference_catalog + +# Collections API +get_collection = api.get_collection +list_collections = api.list_collections +create_collection = api.create_collection +update_collection_metadata = api.update_collection_metadata +update_collection_resource_group = api.update_collection_resource_group +delete_collection = api.delete_collection +add_collection_item = api.add_collection_item +update_collection_item = api.update_collection_item +delete_collection_item = api.delete_collection_item +delete_collection_item = api.delete_collection_item + +# Access requests API +list_pending_access_requests = api.list_pending_access_requests +list_accepted_access_requests = api.list_accepted_access_requests +list_rejected_access_requests = api.list_rejected_access_requests +cancel_access_request = api.cancel_access_request +accept_access_request = api.accept_access_request +reject_access_request = api.reject_access_request +grant_access = api.grant_access + +# Webhooks API +create_webhook = api.create_webhook +disable_webhook = api.disable_webhook +delete_webhook = api.delete_webhook +enable_webhook = api.enable_webhook +get_webhook = api.get_webhook +list_webhooks = api.list_webhooks +update_webhook = api.update_webhook + + +# User API +get_user_overview = api.get_user_overview +get_organization_overview = api.get_organization_overview +list_organization_followers = api.list_organization_followers +list_organization_members = api.list_organization_members +list_user_followers = api.list_user_followers +list_user_following = api.list_user_following + +# Jobs API +run_job = api.run_job +fetch_job_logs = api.fetch_job_logs +fetch_job_metrics = api.fetch_job_metrics +list_jobs = api.list_jobs +list_jobs_hardware = api.list_jobs_hardware +inspect_job = api.inspect_job +wait_for_job = api.wait_for_job +cancel_job = api.cancel_job +update_job_labels = api.update_job_labels +run_uv_job = api.run_uv_job +create_scheduled_job = api.create_scheduled_job +list_scheduled_jobs = api.list_scheduled_jobs +inspect_scheduled_job = api.inspect_scheduled_job +delete_scheduled_job = api.delete_scheduled_job +suspend_scheduled_job = api.suspend_scheduled_job +resume_scheduled_job = api.resume_scheduled_job +trigger_scheduled_job = api.trigger_scheduled_job +update_scheduled_job_labels = api.update_scheduled_job_labels +create_scheduled_uv_job = api.create_scheduled_uv_job +sync_job_volume = api.sync_job_volume + +# Buckets API +create_bucket = api.create_bucket +bucket_info = api.bucket_info +list_buckets = api.list_buckets +delete_bucket = api.delete_bucket +move_bucket = api.move_bucket +list_bucket_tree = api.list_bucket_tree +get_bucket_paths_info = api.get_bucket_paths_info +copy_files = api.copy_files +batch_bucket_files = api.batch_bucket_files +get_bucket_file_metadata = api.get_bucket_file_metadata +download_bucket_files = api.download_bucket_files +sync_bucket = api.sync_bucket diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hub_mixin.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hub_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..937cfe1851538aa8389222885015212c80514871 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/hub_mixin.py @@ -0,0 +1,834 @@ +import inspect +import json +import os +from collections.abc import Callable +from dataclasses import Field, asdict, dataclass, is_dataclass +from pathlib import Path +from typing import Any, ClassVar, Protocol, TypeVar + +import packaging.version + +from . import constants +from .errors import EntryNotFoundError, HfHubHTTPError +from .file_download import hf_hub_download +from .hf_api import HfApi +from .repocard import ModelCard, ModelCardData +from .utils import ( + SoftTemporaryDirectory, + is_jsonable, + is_safetensors_available, + is_simple_optional_type, + is_torch_available, + logging, + unwrap_simple_optional_type, + validate_hf_hub_args, +) + + +if is_torch_available(): + import torch # type: ignore + +if is_safetensors_available(): + import safetensors + from safetensors.torch import load_model as load_model_as_safetensor + from safetensors.torch import save_model as save_model_as_safetensor + + +logger = logging.get_logger(__name__) + + +# Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349 +class DataclassInstance(Protocol): + __dataclass_fields__: ClassVar[dict[str, Field]] + + +# Generic variable that is either ModelHubMixin or a subclass thereof +T = TypeVar("T", bound="ModelHubMixin") +# Generic variable to represent an args type +ARGS_T = TypeVar("ARGS_T") +ENCODER_T = Callable[[ARGS_T], Any] +DECODER_T = Callable[[Any], ARGS_T] +CODER_T = tuple[ENCODER_T, DECODER_T] + + +DEFAULT_MODEL_CARD = """ +--- +# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/model-cards +{{ card_data }} +--- + +This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration: +- Code: {{ repo_url | default("[More Information Needed]", true) }} +- Paper: {{ paper_url | default("[More Information Needed]", true) }} +- Docs: {{ docs_url | default("[More Information Needed]", true) }} +""" + + +@dataclass +class MixinInfo: + model_card_template: str + model_card_data: ModelCardData + docs_url: str | None = None + paper_url: str | None = None + repo_url: str | None = None + + +class ModelHubMixin: + """ + A generic mixin to integrate ANY machine learning framework with the Hub. + + To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models + have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example + of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions. + + When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to + `__init__` but to the class definition itself. This is useful to define metadata about the library integrating + [`ModelHubMixin`]. + + For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations). + + Args: + repo_url (`str`, *optional*): + URL of the library repository. Used to generate model card. + paper_url (`str`, *optional*): + URL of the library paper. Used to generate model card. + docs_url (`str`, *optional*): + URL of the library documentation. Used to generate model card. + model_card_template (`str`, *optional*): + Template of the model card. Used to generate model card. Defaults to a generic template. + language (`str` or `list[str]`, *optional*): + Language supported by the library. Used to generate model card. + library_name (`str`, *optional*): + Name of the library integrating ModelHubMixin. Used to generate model card. + license (`str`, *optional*): + License of the library integrating ModelHubMixin. Used to generate model card. + E.g: "apache-2.0" + license_name (`str`, *optional*): + Name of the library integrating ModelHubMixin. Used to generate model card. + Only used if `license` is set to `other`. + E.g: "coqui-public-model-license". + license_link (`str`, *optional*): + URL to the license of the library integrating ModelHubMixin. Used to generate model card. + Only used if `license` is set to `other` and `license_name` is set. + E.g: "https://coqui.ai/cpml". + pipeline_tag (`str`, *optional*): + Tag of the pipeline. Used to generate model card. E.g. "text-classification". + tags (`list[str]`, *optional*): + Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"] + coders (`dict[Type, tuple[Callable, Callable]]`, *optional*): + Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not + jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc. + + Example: + + ```python + >>> from huggingface_hub import ModelHubMixin + + # Inherit from ModelHubMixin + >>> class MyCustomModel( + ... ModelHubMixin, + ... library_name="my-library", + ... tags=["computer-vision"], + ... repo_url="https://github.com/huggingface/my-cool-library", + ... paper_url="https://arxiv.org/abs/2304.12244", + ... docs_url="https://huggingface.co/docs/my-cool-library", + ... # ^ optional metadata to generate model card + ... ): + ... def __init__(self, size: int = 512, device: str = "cpu"): + ... # define how to initialize your model + ... super().__init__() + ... ... + ... + ... def _save_pretrained(self, save_directory: Path) -> None: + ... # define how to serialize your model + ... ... + ... + ... @classmethod + ... def from_pretrained( + ... cls: type[T], + ... pretrained_model_name_or_path: Union[str, Path], + ... *, + ... force_download: bool = False, + ... token: Optional[Union[str, bool]] = None, + ... cache_dir: Optional[Union[str, Path]] = None, + ... local_files_only: bool = False, + ... revision: Optional[str] = None, + ... **model_kwargs, + ... ) -> T: + ... # define how to deserialize your model + ... ... + + >>> model = MyCustomModel(size=256, device="gpu") + + # Save model weights to local directory + >>> model.save_pretrained("my-awesome-model") + + # Push model weights to the Hub + >>> model.push_to_hub("my-awesome-model") + + # Download and initialize weights from the Hub + >>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model") + >>> reloaded_model.size + 256 + + # Model card has been correctly populated + >>> from huggingface_hub import ModelCard + >>> card = ModelCard.load("username/my-awesome-model") + >>> card.data.tags + ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"] + >>> card.data.library_name + "my-library" + ``` + """ + + _hub_mixin_config: dict | DataclassInstance | None = None + # ^ optional config attribute automatically set in `from_pretrained` + _hub_mixin_info: MixinInfo + # ^ information about the library integrating ModelHubMixin (used to generate model card) + _hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not + _hub_mixin_init_parameters: dict[str, inspect.Parameter] # __init__ parameters + _hub_mixin_jsonable_default_values: dict[str, Any] # default values for __init__ parameters + _hub_mixin_jsonable_custom_types: tuple[type, ...] # custom types that can be encoded/decoded + _hub_mixin_coders: dict[type, CODER_T] # encoders/decoders for custom types + # ^ internal values to handle config + + def __init_subclass__( + cls, + *, + # Generic info for model card + repo_url: str | None = None, + paper_url: str | None = None, + docs_url: str | None = None, + # Model card template + model_card_template: str = DEFAULT_MODEL_CARD, + # Model card metadata + language: list[str] | None = None, + library_name: str | None = None, + license: str | None = None, + license_name: str | None = None, + license_link: str | None = None, + pipeline_tag: str | None = None, + tags: list[str] | None = None, + # How to encode/decode arguments with custom type into a JSON config? + coders: None + | ( + dict[type, CODER_T] + # Key is a type. + # Value is a tuple (encoder, decoder). + # Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))} + ) = None, + ) -> None: + """Inspect __init__ signature only once when subclassing + handle modelcard.""" + super().__init_subclass__() + + # Will be reused when creating modelcard + tags = tags or [] + tags.append("model_hub_mixin") + + # Initialize MixinInfo if not existent + info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData()) + + # If parent class has a MixinInfo, inherit from it as a copy + if hasattr(cls, "_hub_mixin_info"): + # Inherit model card template from parent class if not explicitly set + if model_card_template == DEFAULT_MODEL_CARD: + info.model_card_template = cls._hub_mixin_info.model_card_template + + # Inherit from parent model card data + info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict()) + + # Inherit other info + info.docs_url = cls._hub_mixin_info.docs_url + info.paper_url = cls._hub_mixin_info.paper_url + info.repo_url = cls._hub_mixin_info.repo_url + cls._hub_mixin_info = info + + # Update MixinInfo with metadata + if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD: + info.model_card_template = model_card_template + if repo_url is not None: + info.repo_url = repo_url + if paper_url is not None: + info.paper_url = paper_url + if docs_url is not None: + info.docs_url = docs_url + if language is not None: + info.model_card_data.language = language + if library_name is not None: + info.model_card_data.library_name = library_name + if license is not None: + info.model_card_data.license = license + if license_name is not None: + info.model_card_data.license_name = license_name + if license_link is not None: + info.model_card_data.license_link = license_link + if pipeline_tag is not None: + info.model_card_data.pipeline_tag = pipeline_tag + if tags is not None: + normalized_tags = list(tags) + if info.model_card_data.tags is not None: + info.model_card_data.tags.extend(normalized_tags) + else: + info.model_card_data.tags = normalized_tags + + if info.model_card_data.tags is not None: + info.model_card_data.tags = sorted(set(info.model_card_data.tags)) + + # Handle encoders/decoders for args + cls._hub_mixin_coders = coders or {} + cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys()) + + # Inspect __init__ signature to handle config + cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters) + cls._hub_mixin_jsonable_default_values = { + param.name: cls._encode_arg(param.default) + for param in cls._hub_mixin_init_parameters.values() + if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default) + } + cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters + + def __new__(cls: type[T], *args, **kwargs) -> T: + """Create a new instance of the class and handle config. + + 3 cases: + - If `self._hub_mixin_config` is already set, do nothing. + - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`. + - Otherwise, build `self._hub_mixin_config` from default values and passed values. + """ + instance = super().__new__(cls) + + # If `config` is already set, return early + if instance._hub_mixin_config is not None: + return instance + + # Infer passed values + passed_values = { + **{ + key: value + for key, value in zip( + # [1:] to skip `self` parameter + list(cls._hub_mixin_init_parameters)[1:], + args, + ) + }, + **kwargs, + } + + # If config passed as dataclass => set it and return early + if is_dataclass(passed_values.get("config")): + instance._hub_mixin_config = passed_values["config"] + return instance + + # Otherwise, build config from default + passed values + init_config = { + # default values + **cls._hub_mixin_jsonable_default_values, + # passed values + **{ + key: cls._encode_arg(value) # Encode custom types as jsonable value + for key, value in passed_values.items() + if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder + }, + } + passed_config = init_config.pop("config", {}) + + # Populate `init_config` with provided config + if isinstance(passed_config, dict): + init_config.update(passed_config) + + # Set `config` attribute and return + if init_config != {}: + instance._hub_mixin_config = init_config + return instance + + @classmethod + def _is_jsonable(cls, value: Any) -> bool: + """Check if a value is JSON serializable.""" + if is_dataclass(value): + return True + if isinstance(value, cls._hub_mixin_jsonable_custom_types): + return True + return is_jsonable(value) + + @classmethod + def _encode_arg(cls, arg: Any) -> Any: + """Encode an argument into a JSON serializable format.""" + if is_dataclass(arg): + return asdict(arg) # type: ignore[arg-type] + for type_, (encoder, _) in cls._hub_mixin_coders.items(): + if isinstance(arg, type_): + if arg is None: + return None + return encoder(arg) + return arg + + @classmethod + def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> ARGS_T | None: + """Decode a JSON serializable value into an argument.""" + if is_simple_optional_type(expected_type): + if value is None: + return None + expected_type = unwrap_simple_optional_type(expected_type) # type: ignore + # Dataclass => handle it + if is_dataclass(expected_type): + return _load_dataclass(expected_type, value) # type: ignore + # Otherwise => check custom decoders + for type_, (_, decoder) in cls._hub_mixin_coders.items(): + if inspect.isclass(expected_type) and issubclass(expected_type, type_): + return decoder(value) + # Otherwise => don't decode + return value + + def save_pretrained( + self, + save_directory: str | Path, + *, + config: dict | DataclassInstance | None = None, + repo_id: str | None = None, + push_to_hub: bool = False, + model_card_kwargs: dict[str, Any] | None = None, + **push_to_hub_kwargs, + ) -> str | None: + """ + Save weights in local directory. + + Args: + save_directory (`str` or `Path`): + Path to directory in which the model weights and configuration will be saved. + config (`dict` or `DataclassInstance`, *optional*): + Model configuration specified as a key/value dictionary or a dataclass instance. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether or not to push your model to the Huggingface Hub after saving it. + repo_id (`str`, *optional*): + ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if + not provided. + model_card_kwargs (`dict[str, Any]`, *optional*): + Additional arguments passed to the model card template to customize the model card. + push_to_hub_kwargs: + Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method. + Returns: + `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise. + """ + save_directory = Path(save_directory) + save_directory.mkdir(parents=True, exist_ok=True) + + # Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json + # as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite + # an existing config.json if it was not saved by `_save_pretrained`. + config_path = save_directory / constants.CONFIG_NAME + config_path.unlink(missing_ok=True) + + # save model weights/files (framework-specific) + self._save_pretrained(save_directory) + + # save config (if provided and if not serialized yet in `_save_pretrained`) + if config is None: + config = self._hub_mixin_config + if config is not None: + if is_dataclass(config): + config = asdict(config) # type: ignore[arg-type] + if not config_path.exists(): + config_str = json.dumps(config, sort_keys=True, indent=2) + config_path.write_text(config_str) + + # save model card + model_card_path = save_directory / "README.md" + model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {} + if not model_card_path.exists(): # do not overwrite if already exists + self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md") + + # push to the Hub if required + if push_to_hub: + kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input + if config is not None: # kwarg for `push_to_hub` + kwargs["config"] = config + if repo_id is None: + repo_id = save_directory.name # Defaults to `save_directory` name + return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs) + return None + + def _save_pretrained(self, save_directory: Path) -> None: + """ + Overwrite this method in subclass to define how to save your model. + Check out our [integration guide](../guides/integrations) for instructions. + + Args: + save_directory (`str` or `Path`): + Path to directory in which the model weights and configuration will be saved. + """ + raise NotImplementedError + + @classmethod + @validate_hf_hub_args + def from_pretrained( + cls: type[T], + pretrained_model_name_or_path: str | Path, + *, + force_download: bool = False, + token: str | bool | None = None, + cache_dir: str | Path | None = None, + local_files_only: bool = False, + revision: str | None = None, + **model_kwargs, + ) -> T: + """ + Download a model from the Huggingface Hub and instantiate it. + + Args: + pretrained_model_name_or_path (`str`, `Path`): + - Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`. + - Or a path to a `directory` containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`. + revision (`str`, *optional*): + Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. + Defaults to the latest commit on `main` branch. + force_download (`bool`, *optional*, defaults to `False`): + Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding + the existing cache. + token (`str` or `bool`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the local cached file if it exists. + model_kwargs (`dict`, *optional*): + Additional kwargs to pass to the model during initialization. + """ + model_id = str(pretrained_model_name_or_path) + config_file: str | None = None + if os.path.isdir(model_id): + if constants.CONFIG_NAME in os.listdir(model_id): + config_file = os.path.join(model_id, constants.CONFIG_NAME) + else: + logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}") + else: + try: + config_file = hf_hub_download( + repo_id=model_id, + filename=constants.CONFIG_NAME, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + except HfHubHTTPError as e: + logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}") + + # Read config + config = None + if config_file is not None: + with open(config_file, encoding="utf-8") as f: + config = json.load(f) + + # Decode custom types in config + for key, value in config.items(): + if key in cls._hub_mixin_init_parameters: + expected_type = cls._hub_mixin_init_parameters[key].annotation + if expected_type is not inspect.Parameter.empty: + config[key] = cls._decode_arg(expected_type, value) + + # Populate model_kwargs from config + for param in cls._hub_mixin_init_parameters.values(): + if param.name not in model_kwargs and param.name in config: + model_kwargs[param.name] = config[param.name] + + # Check if `config` argument was passed at init + if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs: + # Decode `config` argument if it was passed + config_annotation = cls._hub_mixin_init_parameters["config"].annotation + config = cls._decode_arg(config_annotation, config) + + # Forward config to model initialization + model_kwargs["config"] = config + + # Inject config if `**kwargs` are expected + if is_dataclass(cls): + for key in cls.__dataclass_fields__: + if key not in model_kwargs and key in config: + model_kwargs[key] = config[key] + elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()): + for key, value in config.items(): # type: ignore[union-attr] + if key not in model_kwargs: + model_kwargs[key] = value + + # Finally, also inject if `_from_pretrained` expects it + if cls._hub_mixin_inject_config and "config" not in model_kwargs: + model_kwargs["config"] = config + + instance = cls._from_pretrained( + model_id=str(model_id), + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + local_files_only=local_files_only, + token=token, + **model_kwargs, + ) + + # Implicitly set the config as instance attribute if not already set by the class + # This way `config` will be available when calling `save_pretrained` or `push_to_hub`. + if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})): + instance._hub_mixin_config = config + + return instance + + @classmethod + def _from_pretrained( + cls: type[T], + *, + model_id: str, + revision: str | None, + cache_dir: str | Path | None, + force_download: bool, + local_files_only: bool, + token: str | bool | None, + **model_kwargs, + ) -> T: + """Overwrite this method in subclass to define how to load your model from pretrained. + + Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most + args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this + method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location` + parameter to set on which device the model should be loaded. + + Check out our [integration guide](../guides/integrations) for more instructions. + + Args: + model_id (`str`): + ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). + revision (`str`, *optional*): + Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the + latest commit on `main` branch. + force_download (`bool`, *optional*, defaults to `False`): + Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding + the existing cache. + token (`str` or `bool`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the local cached file if it exists. + model_kwargs: + Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. + """ + raise NotImplementedError + + @validate_hf_hub_args + def push_to_hub( + self, + repo_id: str, + *, + config: dict | DataclassInstance | None = None, + commit_message: str = "Push model using huggingface_hub.", + private: bool | None = None, + token: str | None = None, + branch: str | None = None, + create_pr: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + model_card_kwargs: dict[str, Any] | None = None, + ) -> str: + """ + Upload model checkpoint to the Hub. + + Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use + `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more + details. + + Args: + repo_id (`str`): + ID of the repository to push to (example: `"username/my-model"`). + config (`dict` or `DataclassInstance`, *optional*): + Model configuration specified as a key/value dictionary or a dataclass instance. + commit_message (`str`, *optional*): + Message to commit while pushing. + private (`bool`, *optional*): + Whether the repository created should be private. + If `None` (default), the repo will be public unless the organization's default is private. + token (`str`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + branch (`str`, *optional*): + The git branch on which to push the model. This defaults to `"main"`. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are pushed. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not pushed. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo. + model_card_kwargs (`dict[str, Any]`, *optional*): + Additional arguments passed to the model card template to customize the model card. + + Returns: + The url of the commit of your model in the given repository. + """ + api = HfApi(token=token) + repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id + + # Push the files to the repo in a single commit + with SoftTemporaryDirectory() as tmp: + saved_path = Path(tmp) / repo_id + self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs) + return api.upload_folder( + repo_id=repo_id, + repo_type="model", + folder_path=saved_path, + commit_message=commit_message, + revision=branch, + create_pr=create_pr, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + delete_patterns=delete_patterns, + ) + + def generate_model_card(self, *args, **kwargs) -> ModelCard: + card = ModelCard.from_template( + card_data=self._hub_mixin_info.model_card_data, + template_str=self._hub_mixin_info.model_card_template, + repo_url=self._hub_mixin_info.repo_url, + paper_url=self._hub_mixin_info.paper_url, + docs_url=self._hub_mixin_info.docs_url, + **kwargs, + ) + return card + + +class PyTorchModelHubMixin(ModelHubMixin): + """ + Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model + is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model, + you should first set it back in training mode with `model.train()`. + + See [`ModelHubMixin`] for more details on how to use the mixin. + + Example: + + ```python + >>> import torch + >>> import torch.nn as nn + >>> from huggingface_hub import PyTorchModelHubMixin + + >>> class MyModel( + ... nn.Module, + ... PyTorchModelHubMixin, + ... library_name="keras-nlp", + ... repo_url="https://github.com/keras-team/keras-nlp", + ... paper_url="https://arxiv.org/abs/2304.12244", + ... docs_url="https://keras.io/keras_nlp/", + ... # ^ optional metadata to generate model card + ... ): + ... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4): + ... super().__init__() + ... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size)) + ... self.linear = nn.Linear(output_size, vocab_size) + + ... def forward(self, x): + ... return self.linear(x + self.param) + >>> model = MyModel(hidden_size=256) + + # Save model weights to local directory + >>> model.save_pretrained("my-awesome-model") + + # Push model weights to the Hub + >>> model.push_to_hub("my-awesome-model") + + # Download and initialize weights from the Hub + >>> model = MyModel.from_pretrained("username/my-awesome-model") + >>> model.hidden_size + 256 + ``` + """ + + def __init_subclass__(cls, *args, tags: list[str] | None = None, **kwargs) -> None: + tags = tags or [] + tags.append("pytorch_model_hub_mixin") + kwargs["tags"] = tags + return super().__init_subclass__(*args, **kwargs) + + def _save_pretrained(self, save_directory: Path) -> None: + """Save weights from a Pytorch model to a local directory.""" + model_to_save = self.module if hasattr(self, "module") else self # type: ignore + save_model_as_safetensor(model_to_save, str(save_directory / constants.SAFETENSORS_SINGLE_FILE)) # type: ignore [arg-type] + + @classmethod + def _from_pretrained( + cls, + *, + model_id: str, + revision: str | None, + cache_dir: str | Path | None, + force_download: bool, + local_files_only: bool, + token: str | bool | None, + map_location: str = "cpu", + strict: bool = False, + **model_kwargs, + ): + """Load Pytorch pretrained weights and return the loaded model.""" + model = cls(**model_kwargs) + if os.path.isdir(model_id): + print("Loading weights from local directory") + model_file = os.path.join(model_id, constants.SAFETENSORS_SINGLE_FILE) + return cls._load_as_safetensor(model, model_file, map_location, strict) + else: + try: + model_file = hf_hub_download( + repo_id=model_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + return cls._load_as_safetensor(model, model_file, map_location, strict) + except EntryNotFoundError: + model_file = hf_hub_download( + repo_id=model_id, + filename=constants.PYTORCH_WEIGHTS_NAME, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + return cls._load_as_pickle(model, model_file, map_location, strict) + + @classmethod + def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T: + state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True) + model.load_state_dict(state_dict, strict=strict) # type: ignore + model.eval() # type: ignore + return model + + @classmethod + def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T: + if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined] + load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type] + if map_location != "cpu": + logger.warning( + "Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors." + " This means that the model is loaded on 'cpu' first and then copied to the device." + " This leads to a slower loading time." + " Please update safetensors to version 0.4.3 or above for improved performance." + ) + model.to(map_location) # type: ignore [attr-defined] + else: + safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type] + model.eval() # type: ignore + return model + + +def _load_dataclass(datacls: type[DataclassInstance], data: dict) -> DataclassInstance: + """Load a dataclass instance from a dictionary. + + Fields not expected by the dataclass are ignored. + """ + return datacls(**{k: v for k, v in data.items() if k in datacls.__dataclass_fields__}) diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/lfs.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/lfs.py new file mode 100644 index 0000000000000000000000000000000000000000..9958a1c332f0ab938cb9769a6384e178fb5e7a96 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/lfs.py @@ -0,0 +1,442 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Git LFS related type definitions and utilities""" + +import io +import re +from collections.abc import Iterable +from math import ceil +from os.path import getsize +from typing import TYPE_CHECKING, BinaryIO, TypedDict +from urllib.parse import unquote + +from huggingface_hub import constants + +from .utils import ( + build_hf_headers, + fix_hf_endpoint_in_url, + hf_raise_for_status, + http_backoff, + logging, + validate_hf_hub_args, +) +from .utils._lfs import SliceFileObj +from .utils.sha import sha256, sha_fileobj + + +if TYPE_CHECKING: + from ._commit_api import CommitOperationAdd + +logger = logging.get_logger(__name__) + +OID_REGEX = re.compile(r"^[0-9a-f]{40}$") + +LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload" + +LFS_HEADERS = { + "Accept": "application/vnd.git-lfs+json", + "Content-Type": "application/vnd.git-lfs+json", +} + + +class UploadInfo: + """ + Data structure holding required information to determine whether a blob + should be uploaded to the hub using the LFS protocol or the regular protocol. + + The SHA256 of the blob is computed lazily: creating an `UploadInfo` from a local path only reads + the first 512 bytes of the file. The full file is read (and hashed) only if `sha256` is accessed + before it has been set. When a file is uploaded through the Xet protocol, the SHA256 is computed + during upload (single read pass) and set afterwards. + + Args: + size (`int`): + Size in bytes of the blob + sample (`bytes`): + First 512 bytes of the blob + sha256 (`bytes`, *optional*): + SHA256 hash of the blob, if already known. Otherwise computed lazily from `source_path`. + source_path (`str`, *optional*): + Path to the local file the blob comes from. Required to lazily compute `sha256` if not provided. + """ + + def __init__( + self, + size: int, + sample: bytes, + sha256: bytes | None = None, + source_path: str | None = None, + ): + if sha256 is None and source_path is None: + raise ValueError("Either `sha256` or `source_path` must be provided.") + self.size = size + self.sample = sample + self._sha256 = sha256 + self._source_path = source_path + + @property + def sha256(self) -> bytes: + """SHA256 of the blob. If not set yet, reads the whole file from `source_path` to compute it.""" + if self._sha256 is None: + assert self._source_path is not None # guaranteed by __init__ + with open(self._source_path, "rb") as file: + self._sha256 = sha_fileobj(file) + return self._sha256 + + @sha256.setter + def sha256(self, value: bytes) -> None: + self._sha256 = value + + @property + def is_hashed(self) -> bool: + """Whether the SHA256 is already known (accessing `sha256` will not trigger a file read).""" + return self._sha256 is not None + + def __repr__(self) -> str: + sha = self._sha256.hex() if self._sha256 is not None else "" + return f"UploadInfo(size={self.size}, sha256={sha})" + + @classmethod + def from_path(cls, path: str): + size = getsize(path) + with open(path, "rb") as file: + sample = file.peek(512)[:512] + return cls(size=size, sample=sample, source_path=path) + + @classmethod + def from_bytes(cls, data: bytes): + sha = sha256(data).digest() + return cls(size=len(data), sample=data[:512], sha256=sha) + + @classmethod + def from_fileobj(cls, fileobj: BinaryIO): + sample = fileobj.read(512) + fileobj.seek(0, io.SEEK_SET) + sha = sha_fileobj(fileobj) + size = fileobj.tell() + fileobj.seek(0, io.SEEK_SET) + return cls(size=size, sha256=sha, sample=sample) + + +@validate_hf_hub_args +def post_lfs_batch_info( + upload_infos: Iterable[UploadInfo], + token: str | None, + repo_type: str, + repo_id: str, + revision: str | None = None, + endpoint: str | None = None, + headers: dict[str, str] | None = None, + transfers: list[str] | None = None, +) -> tuple[list[dict], list[dict], str | None]: + """ + Requests the LFS batch endpoint to retrieve upload instructions + + Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md + + Args: + upload_infos (`Iterable` of `UploadInfo`): + `UploadInfo` for the files that are being uploaded, typically obtained + from `CommitOperationAdd.upload_info` + token (`str` or `None`): + An authentication token (see https://huggingface.co/settings/token). + Pass `None` to fall back to the local cached token (or no token if unauthenticated). + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The git revision to upload to. + endpoint (`str`, *optional*): + The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`. + headers (`dict`, *optional*): + Additional headers to include in the request + transfers (`list`, *optional*): + List of transfer methods to use. Defaults to ["basic", "multipart"]. + + Returns: + `LfsBatchInfo`: 3-tuple: + - First element is the list of upload instructions from the server + - Second element is a list of errors, if any + - Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet") + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If an argument is invalid or the server response is malformed. + [`HfHubHTTPError`] + If the server returned an error. + """ + endpoint = endpoint if endpoint is not None else constants.ENDPOINT + url_prefix = "" + if repo_type in constants.REPO_TYPES_URL_PREFIXES: + url_prefix = constants.REPO_TYPES_URL_PREFIXES[repo_type] + batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch" + payload: dict = { + "operation": "upload", + "transfers": transfers if transfers is not None else ["basic", "multipart"], + "objects": [ + { + "oid": upload.sha256.hex(), + "size": upload.size, + } + for upload in upload_infos + ], + "hash_algo": "sha256", + } + if revision is not None: + payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted' + + headers = { + **LFS_HEADERS, + **build_hf_headers(token=token), + **(headers or {}), + } + resp = http_backoff("POST", batch_url, headers=headers, json=payload) + hf_raise_for_status(resp) + batch_info = resp.json() + + objects = batch_info.get("objects", None) + if not isinstance(objects, list): + raise ValueError("Malformed response from server") + + chosen_transfer = batch_info.get("transfer") + chosen_transfer = chosen_transfer if isinstance(chosen_transfer, str) else None + + return ( + [_validate_batch_actions(obj) for obj in objects if "error" not in obj], + [_validate_batch_error(obj) for obj in objects if "error" in obj], + chosen_transfer, + ) + + +class PayloadPartT(TypedDict): + partNumber: int + etag: str + + +class CompletionPayloadT(TypedDict): + """Payload that will be sent to the Hub when uploading multi-part.""" + + oid: str + parts: list[PayloadPartT] + + +def lfs_upload( + operation: "CommitOperationAdd", + lfs_batch_action: dict, + token: str | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, +) -> None: + """ + Handles uploading a given object to the Hub with the LFS protocol. + + Can be a No-op if the content of the file is already present on the hub large file storage. + + Args: + operation (`CommitOperationAdd`): + The add operation triggering this upload. + lfs_batch_action (`dict`): + Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for + more details. + token (`str`, *optional*): + An authentication token (see https://huggingface.co/settings/token). Used to call the + optional LFS verify step at the end of the upload. If `None`, falls back to the local + cached token. + headers (`dict`, *optional*): + Headers to include in the request, including authentication and user agent headers. + endpoint (`str`, *optional*): + The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `lfs_batch_action` is improperly formatted + [`HfHubHTTPError`] + If the upload resulted in an error + """ + # 0. If LFS file is already present, skip upload + _validate_batch_actions(lfs_batch_action) + actions = lfs_batch_action.get("actions") + if actions is None: + # The file was already uploaded + logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload") + return + + # 1. Validate server response (check required keys in dict) + upload_action = lfs_batch_action["actions"]["upload"] + _validate_lfs_action(upload_action) + verify_action = lfs_batch_action["actions"].get("verify") + if verify_action is not None: + _validate_lfs_action(verify_action) + + # 2. Upload file (either single part or multi-part) + header = upload_action.get("header", {}) + chunk_size = header.get("chunk_size") + upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint) + if chunk_size is not None: + try: + chunk_size = int(chunk_size) + except (ValueError, TypeError): + raise ValueError( + f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'." + ) + _upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url) + else: + _upload_single_part(operation=operation, upload_url=upload_url) + + # 3. Verify upload went well + if verify_action is not None: + _validate_lfs_action(verify_action) + verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint) + verify_resp = http_backoff( + "POST", + verify_url, + headers=build_hf_headers(token=token, headers=headers), + json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size}, + ) + hf_raise_for_status(verify_resp) + logger.debug(f"{operation.path_in_repo}: Upload successful") + + +def _validate_lfs_action(lfs_action: dict): + """validates response from the LFS batch endpoint""" + if not ( + isinstance(lfs_action.get("href"), str) + and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict)) + ): + raise ValueError("lfs_action is improperly formatted") + return lfs_action + + +def _validate_batch_actions(lfs_batch_actions: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)): + raise ValueError("lfs_batch_actions is improperly formatted") + + upload_action = lfs_batch_actions.get("actions", {}).get("upload") + verify_action = lfs_batch_actions.get("actions", {}).get("verify") + if upload_action is not None: + _validate_lfs_action(upload_action) + if verify_action is not None: + _validate_lfs_action(verify_action) + return lfs_batch_actions + + +def _validate_batch_error(lfs_batch_error: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)): + raise ValueError("lfs_batch_error is improperly formatted") + error_info = lfs_batch_error.get("error") + if not ( + isinstance(error_info, dict) + and isinstance(error_info.get("message"), str) + and isinstance(error_info.get("code"), int) + ): + raise ValueError("lfs_batch_error is improperly formatted") + return lfs_batch_error + + +def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None: + """ + Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol) + + Args: + upload_url (`str`): + The URL to PUT the file to. + fileobj: + The file-like object holding the data to upload. + + Raises: + [`HfHubHTTPError`] + If the upload resulted in an error. + """ + with operation.as_file(with_tqdm=True) as fileobj: + # S3 might raise a transient 500 error -> let's retry if that happens + response = http_backoff("PUT", upload_url, data=fileobj) + hf_raise_for_status(response) + + +def _upload_multi_part(operation: "CommitOperationAdd", header: dict, chunk_size: int, upload_url: str) -> None: + """ + Uploads file using HF multipart LFS transfer protocol. + """ + # 1. Get upload URLs for each part + sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size) + + # 2. Upload parts (pure Python) + response_headers = _upload_parts_iteratively( + operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size + ) + + # 3. Send completion request + # NOTE: `upload_url` is the Hub completion endpoint (not the S3 upload URLs). + completion_res = http_backoff( + "POST", + upload_url, + json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()), + headers=LFS_HEADERS, + ) + hf_raise_for_status(completion_res) + + +def _get_sorted_parts_urls(header: dict, upload_info: UploadInfo, chunk_size: int) -> list[str]: + sorted_part_upload_urls = [ + upload_url + for _, upload_url in sorted( + [ + (int(part_num, 10), upload_url) + for part_num, upload_url in header.items() + if part_num.isdigit() and len(part_num) > 0 + ], + key=lambda t: t[0], + ) + ] + num_parts = len(sorted_part_upload_urls) + if num_parts != ceil(upload_info.size / chunk_size): + raise ValueError("Invalid server response to upload large LFS file") + return sorted_part_upload_urls + + +def _get_completion_payload(response_headers: list[dict], oid: str) -> CompletionPayloadT: + parts: list[PayloadPartT] = [] + for part_number, header in enumerate(response_headers): + etag = header.get("etag") + if etag is None or etag == "": + raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}") + parts.append( + { + "partNumber": part_number + 1, + "etag": etag, + } + ) + return {"oid": oid, "parts": parts} + + +def _upload_parts_iteratively( + operation: "CommitOperationAdd", sorted_parts_urls: list[str], chunk_size: int +) -> list[dict]: + headers = [] + with operation.as_file(with_tqdm=True) as fileobj: + for part_idx, part_upload_url in enumerate(sorted_parts_urls): + with SliceFileObj( + fileobj, + seek_from=chunk_size * part_idx, + read_limit=chunk_size, + ) as fileobj_slice: + # S3 might raise a transient 500 error -> let's retry if that happens + part_upload_res = http_backoff("PUT", part_upload_url, data=fileobj_slice) + hf_raise_for_status(part_upload_res) + headers.append(part_upload_res.headers) + return headers # type: ignore diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/py.typed b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb03da924520ab87ad202b6032b2e4d85bae195 --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard.py @@ -0,0 +1,835 @@ +import os +import re +from pathlib import Path +from typing import Any, Literal + +import yaml + +from huggingface_hub.file_download import hf_hub_download +from huggingface_hub.hf_api import upload_file +from huggingface_hub.repocard_data import ( + CardData, + DatasetCardData, + EvalResult, + ModelCardData, + SpaceCardData, + eval_results_to_model_index, + model_index_to_eval_results, +) +from huggingface_hub.utils import HfHubHTTPError, get_session, hf_raise_for_status, is_jinja_available, yaml_dump + +from . import constants +from .errors import EntryNotFoundError +from .utils import SoftTemporaryDirectory, logging, validate_hf_hub_args + + +logger = logging.get_logger(__name__) + + +TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md" +TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md" + +# exact same regex as in the Hub server. Please keep in sync. +# See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18 +REGEX_YAML_BLOCK = re.compile(r"^(\s*---(?:\r\n|\r|\n))([\S\s]*?)((?:\r\n|\r|\n)---[ \t]*(\r\n|\n|$))") + + +class RepoCard: + card_data_class = CardData + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + def __init__(self, content: str, ignore_metadata_errors: bool = False): + """Initialize a RepoCard from string content. The content should be a + Markdown file with a YAML block at the beginning and a Markdown body. + + Args: + content (`str`): The content of the Markdown file. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> text = ''' + ... --- + ... language: en + ... license: mit + ... --- + ... + ... # My repo + ... ''' + >>> card = RepoCard(text) + >>> card.data.to_dict() + {'language': 'en', 'license': 'mit'} + >>> card.text + '\\n# My repo\\n' + + ``` + > [!TIP] + > Raises the following error: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > when the content of the repo card metadata is not a dictionary. + """ + + # Set the content of the RepoCard, as well as underlying .data and .text attributes. + # See the `content` property setter for more details. + self.ignore_metadata_errors = ignore_metadata_errors + self.content = content + + @property + def content(self): + """The content of the RepoCard, including the YAML block and the Markdown body.""" + line_break = _detect_line_ending(self._content) or "\n" + return f"---{line_break}{self.data.to_yaml(line_break=line_break, original_order=self._original_order)}{line_break}---{line_break}{self.text}" + + @content.setter + def content(self, content: str): + """Set the content of the RepoCard.""" + self._content = content + + match = REGEX_YAML_BLOCK.search(content) + if match: + # Metadata found in the YAML block + yaml_block = match.group(2) + self.text = content[match.end() :] + data_dict = yaml.safe_load(yaml_block) + + if data_dict is None: + data_dict = {} + + # The YAML block's data should be a dictionary + if not isinstance(data_dict, dict): + raise ValueError("repo card metadata block should be a dict") + else: + # Model card without metadata... create empty metadata + logger.warning("Repo card metadata block was not found. Setting CardData to empty.") + data_dict = {} + self.text = content + + self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors) + self._original_order = list(data_dict.keys()) + + def __str__(self): + return self.content + + def save(self, filepath: Path | str): + r"""Save a RepoCard to a file. + + Args: + filepath (`Union[Path, str]`): Filepath to the markdown file to save. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") + >>> card.save("/tmp/test.md") + + ``` + """ + filepath = Path(filepath) + filepath.parent.mkdir(parents=True, exist_ok=True) + # Preserve newlines as in the existing file. + with open(filepath, mode="w", newline="", encoding="utf-8") as f: + f.write(str(self)) + + @classmethod + def load( + cls, + repo_id_or_path: str | Path, + repo_type: str | None = None, + token: str | None = None, + ignore_metadata_errors: bool = False, + ): + """Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath. + + Args: + repo_id_or_path (`Union[str, Path]`): + The repo ID associated with a Hugging Face Hub repo or a local filepath. + repo_type (`str`, *optional*): + The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options + are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child + class, the default value will be the child class's `repo_type`. + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's + README.md file or filepath. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard.load("nateraw/food") + >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"] + + ``` + """ + + if Path(repo_id_or_path).is_file(): + card_path = Path(repo_id_or_path) + elif isinstance(repo_id_or_path, str): + card_path = Path( + hf_hub_download( + repo_id_or_path, + constants.REPOCARD_NAME, + repo_type=repo_type or cls.repo_type, + token=token, + ) + ) + else: + raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).") + + # Preserve newlines in the existing file. + with card_path.open(mode="r", newline="", encoding="utf-8") as f: + return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors) + + def validate(self, repo_type: str | None = None): + """Validates card against Hugging Face Hub's card validation logic. + Using this function requires access to the internet, so it is only called + internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`]. + + Args: + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". + If this function is called from a child class, the default will be the child class's `repo_type`. + + > [!TIP] + > Raises the following errors: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if the card fails validation checks. + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the request to the Hub API fails for any other reason. + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + body = { + "repoType": repo_type, + "content": str(self), + } + headers = {"Accept": "text/plain"} + + try: + response = get_session().post("https://huggingface.co/api/validate-yaml", json=body, headers=headers) + hf_raise_for_status(response) + except HfHubHTTPError as exc: + if response.status_code == 400: + raise ValueError(response.text) + else: + raise exc + + def push_to_hub( + self, + repo_id: str, + token: str | None = None, + repo_type: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ): + """Push a RepoCard to a Hugging Face Hub repo. + + Args: + repo_id (`str`): + The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to + the stored token. + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this + function is called by a child class, it will default to the child class's `repo_type`. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. + commit_description (`str`, *optional*) + The description of the generated commit. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + create_pr (`bool`, *optional*): + Whether or not to create a Pull Request with this commit. Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed too concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + # Validate card before pushing to hub + self.validate(repo_type=repo_type) + + with SoftTemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) / constants.REPOCARD_NAME + tmp_path.write_text(str(self), encoding="utf-8") + url = upload_file( + path_or_fileobj=str(tmp_path), + path_in_repo=constants.REPOCARD_NAME, + repo_id=repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) + return url + + @classmethod + def from_template( + cls, + card_data: CardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a RepoCard from a template. By default, it uses the default template. + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.CardData`): + A huggingface_hub.CardData instance containing the metadata you want to include in the YAML + header of the repo card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + template_str (`str`, *optional*): + A raw Jinja template string with optional variables. Used when neither `template_path` + nor the default template is appropriate. Ignored if `template_path` is also provided. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the + template. + """ + if is_jinja_available(): + import jinja2 + else: + raise ImportError( + "Using RepoCard.from_template requires Jinja2 to be installed. Please" + " install it with `pip install Jinja2`." + ) + + kwargs = card_data.to_dict().copy() + kwargs.update(template_kwargs) # Template_kwargs have priority + + if template_path is not None: + template_str = Path(template_path).read_text() + if template_str is None: + template_str = Path(cls.default_template_path).read_text() + template = jinja2.Template(template_str) + content = template.render(card_data=card_data.to_yaml(), **kwargs) + return cls(content) + + +class ModelCard(RepoCard): + card_data_class = ModelCardData # type: ignore[assignment] + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: ModelCardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a ModelCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.ModelCardData`): + A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML + header of the model card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + template_str (`str`, *optional*): + A raw Jinja template string with optional variables. Used when neither `template_path` + nor the default template is appropriate. Ignored if `template_path` is also provided. + + Returns: + [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult + + >>> # Using the Default Template + >>> card_data = ModelCardData( + ... language='en', + ... license='mit', + ... library_name='timm', + ... tags=['image-classification', 'resnet'], + ... datasets=['beans'], + ... metrics=['accuracy'], + ... ) + >>> card = ModelCard.from_template( + ... card_data, + ... model_description='This model does x + y...' + ... ) + + >>> # Including Evaluation Results + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'], + ... eval_results=[ + ... EvalResult( + ... task_type='image-classification', + ... dataset_type='beans', + ... dataset_name='Beans', + ... metric_type='accuracy', + ... metric_value=0.9, + ... ), + ... ], + ... model_name='my-cool-model', + ... ) + >>> card = ModelCard.from_template(card_data) + + >>> # Using a Custom Template + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'] + ... ) + >>> card = ModelCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/modelcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class DatasetCard(RepoCard): + card_data_class = DatasetCardData # type: ignore[assignment] + default_template_path = TEMPLATE_DATASETCARD_PATH + repo_type = "dataset" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: DatasetCardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.DatasetCardData`): + A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML + header of the dataset card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + template_str (`str`, *optional*): + A raw Jinja template string with optional variables. Used when neither `template_path` + nor the default template is appropriate. Ignored if `template_path` is also provided. + + Returns: + [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import DatasetCard, DatasetCardData + + >>> # Using the Default Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... annotations_creators='crowdsourced', + ... task_categories=['text-classification'], + ... task_ids=['sentiment-classification', 'text-scoring'], + ... multilinguality='monolingual', + ... pretty_name='My Text Classification Dataset', + ... ) + >>> card = DatasetCard.from_template( + ... card_data, + ... pretty_name=card_data.pretty_name, + ... ) + + >>> # Using a Custom Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... ) + >>> card = DatasetCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/datasetcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class SpaceCard(RepoCard): + card_data_class = SpaceCardData # type: ignore[assignment] + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "space" + + +def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722 + """Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines. + + Uses same implementation as in Hub server, keep it in sync. + + Returns: + str: The detected line ending of the string. + """ + cr = content.count("\r") + lf = content.count("\n") + crlf = content.count("\r\n") + if cr + lf == 0: + return None + if crlf == cr and crlf == lf: + return "\r\n" + if cr > lf: + return "\r" + else: + return "\n" + + +def metadata_load(local_path: str | Path) -> dict | None: + content = Path(local_path).read_text() + match = REGEX_YAML_BLOCK.search(content) + if match: + yaml_block = match.group(2) + data = yaml.safe_load(yaml_block) + if data is None or isinstance(data, dict): + return data + raise ValueError("repo card metadata block should be a dict") + else: + return None + + +def metadata_save(local_path: str | Path, data: dict) -> None: + """ + Save the metadata dict in the upper YAML part Trying to preserve newlines as + in the existing file. Docs about open() with newline="" parameter: + https://docs.python.org/3/library/functions.html?highlight=open#open Does + not work with "^M" linebreaks, which are replaced by \n + """ + line_break = "\n" + content = "" + # try to detect existing newline character + if os.path.exists(local_path): + with open(local_path, newline="", encoding="utf8") as readme: + content = readme.read() + if isinstance(readme.newlines, tuple): + line_break = readme.newlines[0] + elif isinstance(readme.newlines, str): + line_break = readme.newlines + + # creates a new file if it not + with open(local_path, "w", newline="", encoding="utf8") as readme: + data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break) + # sort_keys: keep dict order + match = REGEX_YAML_BLOCK.search(content) + if match: + output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :] + else: + output = f"---{line_break}{data_yaml}---{line_break}{content}" + + readme.write(output) + readme.close() + + +def metadata_eval_result( + *, + model_pretty_name: str, + task_pretty_name: str, + task_id: str, + metrics_pretty_name: str, + metrics_id: str, + metrics_value: Any, + dataset_pretty_name: str, + dataset_id: str, + metrics_config: str | None = None, + metrics_verified: bool = False, + dataset_config: str | None = None, + dataset_split: str | None = None, + dataset_revision: str | None = None, + metrics_verification_token: str | None = None, +) -> dict: + """ + Creates a metadata dict with the result from a model evaluated on a dataset. + + Args: + model_pretty_name (`str`): + The name of the model in natural language. + task_pretty_name (`str`): + The name of a task in natural language. + task_id (`str`): + Example: automatic-speech-recognition. A task id. + metrics_pretty_name (`str`): + A name for the metric in natural language. Example: Test WER. + metrics_id (`str`): + Example: wer. A metric id from https://hf.co/metrics. + metrics_value (`Any`): + The value from the metric. Example: 20.0 or "20.0 ± 1.2". + dataset_pretty_name (`str`): + The name of the dataset in natural language. + dataset_id (`str`): + Example: common_voice. A dataset id from https://hf.co/datasets. + metrics_config (`str`, *optional*): + The name of the metric configuration used in `load_metric()`. + Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + metrics_verified (`bool`, *optional*, defaults to `False`): + Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + dataset_config (`str`, *optional*): + Example: fr. The name of the dataset configuration used in `load_dataset()`. + dataset_split (`str`, *optional*): + Example: test. The name of the dataset split used in `load_dataset()`. + dataset_revision (`str`, *optional*): + Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision + used in `load_dataset()`. + metrics_verification_token (`bool`, *optional*): + A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + + Returns: + `dict`: a metadata dict with the result from a model evaluated on a dataset. + + Example: + ```python + >>> from huggingface_hub import metadata_eval_result + >>> results = metadata_eval_result( + ... model_pretty_name="RoBERTa fine-tuned on ReactionGIF", + ... task_pretty_name="Text Classification", + ... task_id="text-classification", + ... metrics_pretty_name="Accuracy", + ... metrics_id="accuracy", + ... metrics_value=0.2662102282047272, + ... dataset_pretty_name="ReactionJPEG", + ... dataset_id="julien-c/reactionjpeg", + ... dataset_config="default", + ... dataset_split="test", + ... ) + >>> results == { + ... 'model-index': [ + ... { + ... 'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [ + ... { + ... 'task': { + ... 'type': 'text-classification', + ... 'name': 'Text Classification' + ... }, + ... 'dataset': { + ... 'name': 'ReactionJPEG', + ... 'type': 'julien-c/reactionjpeg', + ... 'config': 'default', + ... 'split': 'test' + ... }, + ... 'metrics': [ + ... { + ... 'type': 'accuracy', + ... 'value': 0.2662102282047272, + ... 'name': 'Accuracy', + ... 'verified': False + ... } + ... ] + ... } + ... ] + ... } + ... ] + ... } + True + + ``` + """ + + return { + "model-index": eval_results_to_model_index( + model_name=model_pretty_name, + eval_results=[ + EvalResult( + task_name=task_pretty_name, + task_type=task_id, + metric_name=metrics_pretty_name, + metric_type=metrics_id, + metric_value=metrics_value, + dataset_name=dataset_pretty_name, + dataset_type=dataset_id, + metric_config=metrics_config, + verified=metrics_verified, + verify_token=metrics_verification_token, + dataset_config=dataset_config, + dataset_split=dataset_split, + dataset_revision=dataset_revision, + ) + ], + ) + } + + +@validate_hf_hub_args +def metadata_update( + repo_id: str, + metadata: dict, + *, + repo_type: str | None = None, + overwrite: bool = False, + token: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + revision: str | None = None, + create_pr: bool = False, + parent_commit: str | None = None, +) -> str: + """ + Updates the metadata in the README.md of a repository on the Hugging Face Hub. + If the README.md file doesn't exist yet, a new one is created with metadata and + the default ModelCard or DatasetCard template. For `space` repo, an error is thrown + as a Space cannot exist without a `README.md` file. + + Args: + repo_id (`str`): + The name of the repository. + metadata (`dict`): + A dictionary containing the metadata to be updated. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if updating to a dataset or space, + `None` or `"model"` if updating to a model. Default is `None`. + overwrite (`bool`, *optional*, defaults to `False`): + If set to `True` an existing field can be overwritten, otherwise + attempting to overwrite an existing field will cause an error. + token (`str`, *optional*): + The Hugging Face authentication token. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Update metadata with huggingface_hub"` + commit_description (`str` *optional*) + The description of the generated commit + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the + `"main"` branch. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `revision` with that commit. + Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed too concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + + Example: + ```python + >>> from huggingface_hub import metadata_update + >>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [{'dataset': {'name': 'ReactionGIF', + ... 'type': 'julien-c/reactiongif'}, + ... 'metrics': [{'name': 'Recall', + ... 'type': 'recall', + ... 'value': 0.7762102282047272}], + ... 'task': {'name': 'Text Classification', + ... 'type': 'text-classification'}}]}]} + >>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata) + + ``` + """ + commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub" + + # Card class given repo_type + card_class: type[RepoCard] + if repo_type is None or repo_type == "model": + card_class = ModelCard + elif repo_type == "dataset": + card_class = DatasetCard + elif repo_type == "space": + card_class = RepoCard + else: + raise ValueError(f"Unknown repo_type: {repo_type}") + + # Either load repo_card from the Hub or create an empty one. + # NOTE: Will not create the repo if it doesn't exist. + try: + card = card_class.load(repo_id, token=token, repo_type=repo_type) + except EntryNotFoundError: + if repo_type == "space": + raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.") + + # Initialize a ModelCard or DatasetCard from default template and no data. + # Cast to the concrete expected card type to satisfy type checkers. + card = card_class.from_template(CardData()) # type: ignore + + for key, value in metadata.items(): + if key == "model-index": + # if the new metadata doesn't include a name, either use existing one or repo name + if "name" not in value[0]: + value[0]["name"] = getattr(card, "model_name", repo_id) + model_name, new_results = model_index_to_eval_results(value) + if card.data.eval_results is None: + card.data.eval_results = new_results + card.data.model_name = model_name + else: + existing_results = card.data.eval_results + + # Iterate over new results + # Iterate over existing results + # If both results describe the same metric but value is different: + # If overwrite=True: overwrite the metric value + # Else: raise ValueError + # Else: append new result to existing ones. + for new_result in new_results: + result_found = False + for existing_result in existing_results: + if new_result.is_equal_except_value(existing_result): + if new_result != existing_result and not overwrite: + raise ValueError( + "You passed a new value for the existing metric" + f" 'name: {new_result.metric_name}, type: " + f"{new_result.metric_type}'. Set `overwrite=True`" + " to overwrite existing metrics." + ) + result_found = True + existing_result.metric_value = new_result.metric_value + if existing_result.verified is True: + existing_result.verify_token = new_result.verify_token + if not result_found: + card.data.eval_results.append(new_result) + else: + # Any metadata that is not a result metric + if card.data.get(key) is not None and not overwrite and card.data.get(key) != value: + raise ValueError( + f"You passed a new value for the existing meta data field '{key}'." + " Set `overwrite=True` to overwrite existing metadata." + ) + else: + card.data[key] = value + + return card.push_to_hub( + repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) diff --git a/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard_data.py b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard_data.py new file mode 100644 index 0000000000000000000000000000000000000000..69539f809b7f38b54be76fe689153b3c3ec4ff7a --- /dev/null +++ b/.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/repocard_data.py @@ -0,0 +1,776 @@ +import copy +from collections import defaultdict +from dataclasses import dataclass +from typing import Any + +from huggingface_hub.utils import logging, yaml_dump + + +logger = logging.get_logger(__name__) + + +@dataclass +class EvalResult: + """ + Flattened representation of individual evaluation results found in model-index of Model Cards. + + For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1. + + Args: + task_type (`str`): + The task identifier. Example: "image-classification". + dataset_type (`str`): + The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets. + dataset_name (`str`): + A pretty name for the dataset. Example: "Common Voice (French)". + metric_type (`str`): + The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics. + metric_value (`Any`): + The metric value. Example: 0.9 or "20.0 ± 1.2". + task_name (`str`, *optional*): + A pretty name for the task. Example: "Speech Recognition". + dataset_config (`str`, *optional*): + The name of the dataset configuration used in `load_dataset()`. + Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info: + https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name + dataset_split (`str`, *optional*): + The split used in `load_dataset()`. Example: "test". + dataset_revision (`str`, *optional*): + The revision (AKA Git Sha) of the dataset used in `load_dataset()`. + Example: 5503434ddd753f426f4b38109466949a1217c2bb + dataset_args (`dict[str, Any]`, *optional*): + The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}` + metric_name (`str`, *optional*): + A pretty name for the metric. Example: "Test WER". + metric_config (`str`, *optional*): + The name of the metric configuration used in `load_metric()`. + Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations + metric_args (`dict[str, Any]`, *optional*): + The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4 + verified (`bool`, *optional*): + Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + verify_token (`str`, *optional*): + A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + source_name (`str`, *optional*): + The name of the source of the evaluation result. Example: "Open LLM Leaderboard". + source_url (`str`, *optional*): + The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard". + """ + + # Required + + # The task identifier + # Example: automatic-speech-recognition + task_type: str + + # The dataset identifier + # Example: common_voice. Use dataset id from https://hf.co/datasets + dataset_type: str + + # A pretty name for the dataset. + # Example: Common Voice (French) + dataset_name: str + + # The metric identifier + # Example: wer. Use metric id from https://hf.co/metrics + metric_type: str + + # Value of the metric. + # Example: 20.0 or "20.0 ± 1.2" + metric_value: Any + + # Optional + + # A pretty name for the task. + # Example: Speech Recognition + task_name: str | None = None + + # The name of the dataset configuration used in `load_dataset()`. + # Example: fr in `load_dataset("common_voice", "fr")`. + # See the `datasets` docs for more info: + # https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name + dataset_config: str | None = None + + # The split used in `load_dataset()`. + # Example: test + dataset_split: str | None = None + + # The revision (AKA Git Sha) of the dataset used in `load_dataset()`. + # Example: 5503434ddd753f426f4b38109466949a1217c2bb + dataset_revision: str | None = None + + # The arguments passed during `Metric.compute()`. + # Example for `bleu`: max_order: 4 + dataset_args: dict[str, Any] | None = None + + # A pretty name for the metric. + # Example: Test WER + metric_name: str | None = None + + # The name of the metric configuration used in `load_metric()`. + # Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + # See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations + metric_config: str | None = None + + # The arguments passed during `Metric.compute()`. + # Example for `bleu`: max_order: 4 + metric_args: dict[str, Any] | None = None + + # Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + verified: bool | None = None + + # A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + verify_token: str | None = None + + # The name of the source of the evaluation result. + # Example: Open LLM Leaderboard + source_name: str | None = None + + # The URL of the source of the evaluation result. + # Example: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard + source_url: str | None = None + + @property + def unique_identifier(self) -> tuple: + """Returns a tuple that uniquely identifies this evaluation.""" + return ( + self.task_type, + self.dataset_type, + self.dataset_config, + self.dataset_split, + self.dataset_revision, + ) + + def is_equal_except_value(self, other: "EvalResult") -> bool: + """ + Return True if `self` and `other` describe exactly the same metric but with a + different value. + """ + for key, _ in self.__dict__.items(): + if key == "metric_value": + continue + # For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`, + # so we exclude it here in the comparison. + if key != "verify_token" and getattr(self, key) != getattr(other, key): + return False + return True + + def __post_init__(self) -> None: + if self.source_name is not None and self.source_url is None: + raise ValueError("If `source_name` is provided, `source_url` must also be provided.") + + +@dataclass +class CardData: + """Structure containing metadata from a RepoCard. + + [`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`]. + + Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data + (example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not + inherit from `dict` to allow this export step. + """ + + def __init__(self, ignore_metadata_errors: bool = False, **kwargs): + self.__dict__.update(kwargs) + + def to_dict(self): + """Converts CardData to a dict. + + Returns: + `dict`: CardData represented as a dictionary ready to be dumped to a YAML + block for inclusion in a README.md file. + """ + + data_dict = copy.deepcopy(self.__dict__) + self._to_dict(data_dict) + return {key: value for key, value in data_dict.items() if value is not None} + + def _to_dict(self, data_dict): + """Use this method in child classes to alter the dict representation of the data. Alter the dict in-place. + + Args: + data_dict (`dict`): The raw dict representation of the card data. + """ + pass + + def to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str: + """Dumps CardData to a YAML block for inclusion in a README.md file. + + Args: + line_break (str, *optional*): + The line break to use when dumping to yaml. + original_order (`list[str]`, *optional*): + If provided, reorder the metadata fields to match this list before dumping. + Any keys not in `original_order` are appended after the listed keys, preserving + their existing relative order. Useful for round-tripping a YAML block without + shuffling its keys. + + Returns: + `str`: CardData represented as a YAML block. + """ + if original_order: + original_order_set = set(original_order) + self.__dict__ = { + k: self.__dict__[k] + for k in original_order + [k for k in self.__dict__ if k not in original_order_set] + if k in self.__dict__ + } + return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip() + + def __repr__(self): + return repr(self.__dict__) + + def __str__(self): + return self.to_yaml() + + def get(self, key: str, default: Any = None) -> Any: + """Get value for a given metadata key.""" + value = self.__dict__.get(key) + return default if value is None else value + + def pop(self, key: str, default: Any = None) -> Any: + """Pop value for a given metadata key.""" + return self.__dict__.pop(key, default) + + def __getitem__(self, key: str) -> Any: + """Get value for a given metadata key.""" + return self.__dict__[key] + + def __setitem__(self, key: str, value: Any) -> None: + """Set value for a given metadata key.""" + self.__dict__[key] = value + + def __contains__(self, key: str) -> bool: + """Check if a given metadata key is set.""" + return key in self.__dict__ + + def __len__(self) -> int: + """Return the number of metadata keys set.""" + return len(self.__dict__) + + +def _validate_eval_results( + eval_results: EvalResult | list[EvalResult] | None, + model_name: str | None, +) -> list[EvalResult]: + if eval_results is None: + return [] + if isinstance(eval_results, EvalResult): + eval_results = [eval_results] + if not isinstance(eval_results, list) or not all(isinstance(r, EvalResult) for r in eval_results): + raise ValueError( + f"`eval_results` should be of type `EvalResult` or a list of `EvalResult`, got {type(eval_results)}." + ) + if model_name is None: + raise ValueError("Passing `eval_results` requires `model_name` to be set.") + return eval_results + + +class ModelCardData(CardData): + """Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + Args: + base_model (`str` or `list[str]`, *optional*): + The identifier of the base model from which the model derives. This is applicable for example if your model is a + fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs + if your model derives from multiple models). Defaults to None. + datasets (`Union[str, list[str]]`, *optional*): + Dataset or list of datasets that were used to train this model. Should be a dataset ID + found on https://hf.co/datasets. Defaults to None. + eval_results (`Union[list[EvalResult], EvalResult]`, *optional*): + List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided, + `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`. + language (`Union[str, list[str]]`, *optional*): + Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or + 639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`. + library_name (`str`, *optional*): + Name of library used by this model. Example: keras or any library from + https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts. + Defaults to None. + license (`str`, *optional*): + License of this model. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. Defaults to None. + license_name (`str`, *optional*): + Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`. + Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead. + license_link (`str`, *optional*): + Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`. + Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead. + metrics (`list[str]`, *optional*): + List of metrics used to evaluate this model. Should be a metric name that can be found + at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. + model_name (`str`, *optional*): + A name for this model. It is used along with + `eval_results` to construct the `model-index` within the card's metadata. The name + you supply here is what will be used on PapersWithCode's leaderboards. If None is provided + then the repo name is used as a default. Defaults to None. + pipeline_tag (`str`, *optional*): + The pipeline tag associated with the model. Example: "text-classification". + tags (`list[str]`, *optional*): + List of tags to add to your model that can be used when filtering on the Hugging + Face Hub. Defaults to None. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + kwargs (`dict`, *optional*): + Additional metadata that will be added to the model card. Defaults to None. + + Example: + ```python + >>> from huggingface_hub import ModelCardData + >>> card_data = ModelCardData( + ... language="en", + ... license="mit", + ... library_name="timm", + ... tags=['image-classification', 'resnet'], + ... ) + >>> card_data.to_dict() + {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']} + + ``` + """ + + def __init__( + self, + *, + base_model: str | list[str] | None = None, + datasets: str | list[str] | None = None, + eval_results: list[EvalResult] | None = None, + language: str | list[str] | None = None, + library_name: str | None = None, + license: str | None = None, + license_name: str | None = None, + license_link: str | None = None, + metrics: list[str] | None = None, + model_name: str | None = None, + pipeline_tag: str | None = None, + tags: list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.base_model = base_model + self.datasets = datasets + self.eval_results = eval_results + self.language = language + self.library_name = library_name + self.license = license + self.license_name = license_name + self.license_link = license_link + self.metrics = metrics + self.model_name = model_name + self.pipeline_tag = pipeline_tag + self.tags = _to_unique_list(tags) + + model_index = kwargs.pop("model-index", None) + if model_index: + try: + model_name, eval_results = model_index_to_eval_results(model_index) + self.model_name = model_name + self.eval_results = eval_results + except (KeyError, TypeError) as error: + if ignore_metadata_errors: + logger.warning("Invalid model-index. Not loading eval results into CardData.") + else: + raise ValueError( + f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" + " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" + " some information will be lost. Use it at your own risk." + ) + + super().__init__(**kwargs) + + if self.eval_results: + try: + self.eval_results = _validate_eval_results(self.eval_results, self.model_name) + except Exception as e: + if ignore_metadata_errors: + logger.warning(f"Failed to validate eval_results: {e}. Not loading eval results into CardData.") + else: + raise ValueError(f"Failed to validate eval_results: {e}") from e + + def _to_dict(self, data_dict): + """Format the internal data dict. In this case, we convert eval results to a valid model index""" + if self.eval_results is not None: + data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) # type: ignore + del data_dict["eval_results"], data_dict["model_name"] + + +class DatasetCardData(CardData): + """Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + Args: + language (`list[str]`, *optional*): + Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or + 639-3 code (two/three letters), or a special value like "code", "multilingual". + license (`Union[str, list[str]]`, *optional*): + License(s) of this dataset. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. + annotations_creators (`Union[str, list[str]]`, *optional*): + How the annotations for the dataset were created. + Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'. + language_creators (`Union[str, list[str]]`, *optional*): + How the text-based data in the dataset was created. + Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other' + multilinguality (`Union[str, list[str]]`, *optional*): + Whether the dataset is multilingual. + Options are: 'monolingual', 'multilingual', 'translation', 'other'. + size_categories (`Union[str, list[str]]`, *optional*): + The number of examples in the dataset. Options are: 'n<1K', '1K1T', and 'other'. + source_datasets (`list[str]]`, *optional*): + Indicates whether the dataset is an original dataset or extended from another existing dataset. + Options are: 'original' and 'extended'. + task_categories (`Union[str, list[str]]`, *optional*): + What categories of task does the dataset support? + task_ids (`Union[str, list[str]]`, *optional*): + What specific tasks does the dataset support? + paperswithcode_id (`str`, *optional*): + ID of the dataset on PapersWithCode. + pretty_name (`str`, *optional*): + A more human-readable name for the dataset. (ex. "Cats vs. Dogs") + train_eval_index (`dict`, *optional*): + A dictionary that describes the necessary spec for doing evaluation on the Hub. + If not provided, it will be gathered from the 'train-eval-index' key of the kwargs. + config_names (`Union[str, list[str]]`, *optional*): + A list of the available dataset configs for the dataset. + """ + + def __init__( + self, + *, + language: str | list[str] | None = None, + license: str | list[str] | None = None, + annotations_creators: str | list[str] | None = None, + language_creators: str | list[str] | None = None, + multilinguality: str | list[str] | None = None, + size_categories: str | list[str] | None = None, + source_datasets: list[str] | None = None, + task_categories: str | list[str] | None = None, + task_ids: str | list[str] | None = None, + paperswithcode_id: str | None = None, + pretty_name: str | None = None, + train_eval_index: dict | None = None, + config_names: str | list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.annotations_creators = annotations_creators + self.language_creators = language_creators + self.language = language + self.license = license + self.multilinguality = multilinguality + self.size_categories = size_categories + self.source_datasets = source_datasets + self.task_categories = task_categories + self.task_ids = task_ids + self.paperswithcode_id = paperswithcode_id + self.pretty_name = pretty_name + self.config_names = config_names + + # TODO - maybe handle this similarly to EvalResult? + self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None) + super().__init__(**kwargs) + + def _to_dict(self, data_dict): + data_dict["train-eval-index"] = data_dict.pop("train_eval_index") + + +class SpaceCardData(CardData): + """Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference. + + Args: + title (`str`, *optional*) + Title of the Space. + sdk (`str`, *optional*) + SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`). + sdk_version (`str`, *optional*) + Version of the used SDK (if Gradio/Streamlit sdk). + python_version (`str`, *optional*) + Python version used in the Space (if Gradio/Streamlit sdk). + app_file (`str`, *optional*) + Path to your main application file (which contains either gradio or streamlit Python code, or static html code). + Path is relative to the root of the repository. + app_port (`str`, *optional*) + Port on which your application is running. Used only if sdk is `docker`. + license (`str`, *optional*) + License of this model. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. + duplicated_from (`str`, *optional*) + ID of the original Space if this is a duplicated Space. + models (list[`str`], *optional*) + List of models related to this Space. Should be a dataset ID found on https://hf.co/models. + datasets (`list[str]`, *optional*) + List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets. + tags (`list[str]`, *optional*) + List of tags to add to your Space that can be used when filtering on the Hub. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + kwargs (`dict`, *optional*): + Additional metadata that will be added to the space card. + + Example: + ```python + >>> from huggingface_hub import SpaceCardData + >>> card_data = SpaceCardData( + ... title="Dreambooth Training", + ... license="mit", + ... sdk="gradio", + ... duplicated_from="multimodalart/dreambooth-training" + ... ) + >>> card_data.to_dict() + {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'} + ``` + """ + + def __init__( + self, + *, + title: str | None = None, + sdk: str | None = None, + sdk_version: str | None = None, + python_version: str | None = None, + app_file: str | None = None, + app_port: int | None = None, + license: str | None = None, + duplicated_from: str | None = None, + models: list[str] | None = None, + datasets: list[str] | None = None, + tags: list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.title = title + self.sdk = sdk + self.sdk_version = sdk_version + self.python_version = python_version + self.app_file = app_file + self.app_port = app_port + self.license = license + self.duplicated_from = duplicated_from + self.models = models + self.datasets = datasets + self.tags = _to_unique_list(tags) + super().__init__(**kwargs) + + +def model_index_to_eval_results(model_index: list[dict[str, Any]]) -> tuple[str, list[EvalResult]]: + """Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects. + + A detailed spec of the model index can be found here: + https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 + + Args: + model_index (`list[dict[str, Any]]`): + A model index data structure, likely coming from a README.md file on the + Hugging Face Hub. + + Returns: + model_name (`str`): + The name of the model as found in the model index. This is used as the + identifier for the model on leaderboards like PapersWithCode. + eval_results (`list[EvalResult]`): + A list of `huggingface_hub.EvalResult` objects containing the metrics + reported in the provided model_index. + + Example: + ```python + >>> from huggingface_hub.repocard_data import model_index_to_eval_results + >>> # Define a minimal model index + >>> model_index = [ + ... { + ... "name": "my-cool-model", + ... "results": [ + ... { + ... "task": { + ... "type": "image-classification" + ... }, + ... "dataset": { + ... "type": "beans", + ... "name": "Beans" + ... }, + ... "metrics": [ + ... { + ... "type": "accuracy", + ... "value": 0.9 + ... } + ... ] + ... } + ... ] + ... } + ... ] + >>> model_name, eval_results = model_index_to_eval_results(model_index) + >>> model_name + 'my-cool-model' + >>> eval_results[0].task_type + 'image-classification' + >>> eval_results[0].metric_type + 'accuracy' + + ``` + """ + + eval_results = [] + for elem in model_index: + name = elem["name"] + results = elem["results"] + for result in results: + task_type = result["task"]["type"] + task_name = result["task"].get("name") + dataset_type = result["dataset"]["type"] + dataset_name = result["dataset"]["name"] + dataset_config = result["dataset"].get("config") + dataset_split = result["dataset"].get("split") + dataset_revision = result["dataset"].get("revision") + dataset_args = result["dataset"].get("args") + source_name = result.get("source", {}).get("name") + source_url = result.get("source", {}).get("url") + + for metric in result["metrics"]: + metric_type = metric["type"] + metric_value = metric["value"] + metric_name = metric.get("name") + metric_args = metric.get("args") + metric_config = metric.get("config") + verified = metric.get("verified") + verify_token = metric.get("verifyToken") + + eval_result = EvalResult( + task_type=task_type, # Required + dataset_type=dataset_type, # Required + dataset_name=dataset_name, # Required + metric_type=metric_type, # Required + metric_value=metric_value, # Required + task_name=task_name, + dataset_config=dataset_config, + dataset_split=dataset_split, + dataset_revision=dataset_revision, + dataset_args=dataset_args, + metric_name=metric_name, + metric_args=metric_args, + metric_config=metric_config, + verified=verified, + verify_token=verify_token, + source_name=source_name, + source_url=source_url, + ) + eval_results.append(eval_result) + return name, eval_results + + +def _remove_none(obj): + """ + Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778 + """ + if isinstance(obj, (list, tuple, set)): + return type(obj)(_remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None) + else: + return obj + + +def eval_results_to_model_index(model_name: str, eval_results: list[EvalResult]) -> list[dict[str, Any]]: + """Takes in given model name and list of `huggingface_hub.EvalResult` and returns a + valid model-index that will be compatible with the format expected by the + Hugging Face Hub. + + Args: + model_name (`str`): + Name of the model (ex. "my-cool-model"). This is used as the identifier + for the model on leaderboards like PapersWithCode. + eval_results (`list[EvalResult]`): + List of `huggingface_hub.EvalResult` objects containing the metrics to be + reported in the model-index. + + Returns: + model_index (`list[dict[str, Any]]`): The eval_results converted to a model-index. + + Example: + ```python + >>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult + >>> # Define minimal eval_results + >>> eval_results = [ + ... EvalResult( + ... task_type="image-classification", # Required + ... dataset_type="beans", # Required + ... dataset_name="Beans", # Required + ... metric_type="accuracy", # Required + ... metric_value=0.9, # Required + ... ) + ... ] + >>> eval_results_to_model_index("my-cool-model", eval_results) + [{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}] + + ``` + """ + + # Metrics are reported on a unique task-and-dataset basis. + # Here, we make a map of those pairs and the associated EvalResults. + task_and_ds_types_map: dict[Any, list[EvalResult]] = defaultdict(list) + for eval_result in eval_results: + task_and_ds_types_map[eval_result.unique_identifier].append(eval_result) + + # Use the map from above to generate the model index data. + model_index_data: list[dict[str, Any]] = [] + for results in task_and_ds_types_map.values(): + # All items from `results` share same metadata + sample_result = results[0] + data: dict[str, Any] = { + "task": { + "type": sample_result.task_type, + "name": sample_result.task_name, + }, + "dataset": { + "name": sample_result.dataset_name, + "type": sample_result.dataset_type, + "config": sample_result.dataset_config, + "split": sample_result.dataset_split, + "revision": sample_result.dataset_revision, + "args": sample_result.dataset_args, + }, + "metrics": [ + { + "type": result.metric_type, + "value": result.metric_value, + "name": result.metric_name, + "config": result.metric_config, + "args": result.metric_args, + "verified": result.verified, + "verifyToken": result.verify_token, + } + for result in results + ], + } + if sample_result.source_url is not None: + source: dict[str, str] = { + "url": sample_result.source_url, + } + if sample_result.source_name is not None: + source["name"] = sample_result.source_name + data["source"] = source + model_index_data.append(data) + + # TODO - Check if there cases where this list is longer than one? + # Finally, the model index itself is list of dicts. + model_index = [ + { + "name": model_name, + "results": model_index_data, + } + ] + return _remove_none(model_index) + + +def _to_unique_list(tags: list[str] | None) -> list[str] | None: + if tags is None: + return tags + unique_tags = [] # make tags unique + keep order explicitly + for tag in tags: + if tag not in unique_tags: + unique_tags.append(tag) + return unique_tags diff --git a/.cache/uv/archive-v0/klGTILB7sY3oHSKQVSOtk/typing_extensions.py b/.cache/uv/archive-v0/klGTILB7sY3oHSKQVSOtk/typing_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..ced78373258ef307c9a94ef15286e6da359e7a80 --- /dev/null +++ b/.cache/uv/archive-v0/klGTILB7sY3oHSKQVSOtk/typing_extensions.py @@ -0,0 +1,4422 @@ +import abc +import builtins +import collections +import collections.abc +import contextlib +import enum +import functools +import inspect +import io +import keyword +import operator +import sys +import types as _types +import typing +import warnings + +# Breakpoint: https://github.com/python/cpython/pull/119891 +if sys.version_info >= (3, 14): + import annotationlib + +__all__ = [ + # Super-special typing primitives. + 'Any', + 'ClassVar', + 'Concatenate', + 'Final', + 'LiteralString', + 'ParamSpec', + 'ParamSpecArgs', + 'ParamSpecKwargs', + 'Self', + 'Type', + 'TypeVar', + 'TypeVarTuple', + 'Unpack', + + # ABCs (from collections.abc). + 'Awaitable', + 'AsyncIterator', + 'AsyncIterable', + 'Coroutine', + 'AsyncGenerator', + 'AsyncContextManager', + 'Buffer', + 'ChainMap', + + # Concrete collection types. + 'ContextManager', + 'Counter', + 'Deque', + 'DefaultDict', + 'NamedTuple', + 'OrderedDict', + 'TypedDict', + + # Structural checks, a.k.a. protocols. + 'SupportsAbs', + 'SupportsBytes', + 'SupportsComplex', + 'SupportsFloat', + 'SupportsIndex', + 'SupportsInt', + 'SupportsRound', + 'Reader', + 'Writer', + + # One-off things. + 'Annotated', + 'assert_never', + 'assert_type', + 'clear_overloads', + 'dataclass_transform', + 'deprecated', + 'disjoint_base', + 'Doc', + 'evaluate_forward_ref', + 'get_overloads', + 'final', + 'Format', + 'get_annotations', + 'get_args', + 'get_origin', + 'get_original_bases', + 'get_protocol_members', + 'get_type_hints', + 'IntVar', + 'is_protocol', + 'is_typeddict', + 'Literal', + 'NewType', + 'overload', + 'override', + 'Protocol', + 'sentinel', + 'Sentinel', + 'reveal_type', + 'runtime', + 'runtime_checkable', + 'Text', + 'TypeAlias', + 'TypeAliasType', + 'TypeForm', + 'TypeGuard', + 'TypeIs', + 'TYPE_CHECKING', + 'type_repr', + 'Never', + 'NoReturn', + 'ReadOnly', + 'Required', + 'NotRequired', + 'NoDefault', + 'NoExtraItems', + + # Pure aliases, have always been in typing + 'AbstractSet', + 'AnyStr', + 'BinaryIO', + 'Callable', + 'Collection', + 'Container', + 'Dict', + 'ForwardRef', + 'FrozenSet', + 'Generator', + 'Generic', + 'Hashable', + 'IO', + 'ItemsView', + 'Iterable', + 'Iterator', + 'KeysView', + 'List', + 'Mapping', + 'MappingView', + 'Match', + 'MutableMapping', + 'MutableSequence', + 'MutableSet', + 'Optional', + 'Pattern', + 'Reversible', + 'Sequence', + 'Set', + 'Sized', + 'TextIO', + 'Tuple', + 'Union', + 'ValuesView', + 'cast', + 'no_type_check', +] + +# for backward compatibility +PEP_560 = True +GenericMeta = type +# Breakpoint: https://github.com/python/cpython/pull/116129 +_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") + +# Added with bpo-45166 to 3.10.1+ and some 3.9 versions +_FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__ + + +def _caller(depth=1, default='__main__'): + try: + return sys._getframemodulename(depth + 1) or default + except AttributeError: # For platforms without _getframemodulename() + pass + try: + return sys._getframe(depth + 1).f_globals.get('__name__', default) + except (AttributeError, ValueError): # For platforms without _getframe() + pass + return None + + +# Placeholder for sentinel methods, because sentinels can not have their own sentinels +_sentinel_placeholder = object() + +if hasattr(builtins, "sentinel"): # 3.15+ + sentinel = builtins.sentinel +else: + class sentinel: + """Create a unique sentinel object. + + *name* should be the name of the variable to which the return value + shall be assigned. + """ + + def __init__( + self, + __name: str = _sentinel_placeholder, + __repr: typing.Optional[str] = _sentinel_placeholder, + /, + *, + repr: typing.Optional[str] = None, + name: str = _sentinel_placeholder, + ) -> None: + if name is not _sentinel_placeholder: + warnings.warn( + "Passing 'name' as a keyword argument is deprecated; " + "pass it positionally instead.", + DeprecationWarning, + stacklevel=2, + ) + __name = name + if __name is _sentinel_placeholder: + raise TypeError("First parameter 'name' is required") + if __repr is not _sentinel_placeholder: + warnings.warn( + "Passing 'repr' as a positional argument is deprecated; " + "pass it by keyword instead.", + DeprecationWarning, + stacklevel=2, + ) + repr = __repr + + self._name = __name + self._repr = repr if repr is not None else __name + + # For pickling as a singleton: + self.__module__ = _caller() + + def __init_subclass__(cls): + warnings.warn( + "Subclassing sentinel is deprecated " + "and will be disallowed in Python 3.15", + DeprecationWarning, + stacklevel=2, + ) + super().__init_subclass__() + + def __setattr__(self, attr: str, value: object) -> None: + if attr not in {"_name", "_repr", "__module__"}: + warnings.warn( + f"Setting attribute {attr!r} on sentinel objects is deprecated " + "and will be disallowed in Python 3.15.", + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(attr, value) + + @property + def __name__(self) -> str: + return self._name + + @__name__.setter + def __name__(self, value: str) -> None: + self._name = value + + def __repr__(self) -> str: + return self._repr + + if sys.version_info < (3, 11): + # The presence of this method convinces typing._type_check + # that Sentinels are types. + def __call__(self, *args, **kwargs): + raise TypeError(f"{type(self).__name__!r} object is not callable") + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __reduce__(self) -> str: + """Reduce this sentinel to a singleton.""" + return self.__name__ # Module is taken from the __module__ attribute + +Sentinel = sentinel + +_marker = sentinel("sentinel") + + +# The functions below are modified copies of typing internal helpers. +# They are needed by _ProtocolMeta and they provide support for PEP 646. + +# Breakpoint: https://github.com/python/cpython/pull/27342 +if sys.version_info >= (3, 10): + def _should_collect_from_parameters(t): + return isinstance( + t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ) +else: + def _should_collect_from_parameters(t): + return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) + + +NoReturn = typing.NoReturn + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = typing.TypeVar('T') # Any type. +KT = typing.TypeVar('KT') # Key type. +VT = typing.TypeVar('VT') # Value type. +T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. +T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. + + +# Breakpoint: https://github.com/python/cpython/pull/31841 +if sys.version_info >= (3, 11): + from typing import Any +else: + + class _AnyMeta(type): + def __instancecheck__(self, obj): + if self is Any: + raise TypeError("typing_extensions.Any cannot be used with isinstance()") + return super().__instancecheck__(obj) + + def __repr__(self): + if self is Any: + return "typing_extensions.Any" + return super().__repr__() + + class Any(metaclass=_AnyMeta): + """Special type indicating an unconstrained type. + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + checks. + """ + def __new__(cls, *args, **kwargs): + if cls is Any: + raise TypeError("Any cannot be instantiated") + return super().__new__(cls, *args, **kwargs) + + +ClassVar = typing.ClassVar + +# Vendored from cpython typing._SpecialFrom +# Having a separate class means that instances will not be rejected by +# typing._type_check. +class _SpecialForm(typing._Final, _root=True): + __slots__ = ('_name', '__doc__', '_getitem') + + def __init__(self, getitem): + self._getitem = getitem + self._name = getitem.__name__ + self.__doc__ = getitem.__doc__ + + def __getattr__(self, item): + if item in {'__name__', '__qualname__'}: + return self._name + + raise AttributeError(item) + + def __mro_entries__(self, bases): + raise TypeError(f"Cannot subclass {self!r}") + + def __repr__(self): + return f'typing_extensions.{self._name}' + + def __reduce__(self): + return self._name + + def __call__(self, *args, **kwds): + raise TypeError(f"Cannot instantiate {self!r}") + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __instancecheck__(self, obj): + raise TypeError(f"{self} cannot be used with isinstance()") + + def __subclasscheck__(self, cls): + raise TypeError(f"{self} cannot be used with issubclass()") + + @typing._tp_cache + def __getitem__(self, parameters): + return self._getitem(self, parameters) + + +# Note that inheriting from this class means that the object will be +# rejected by typing._type_check, so do not use it if the special form +# is arguably valid as a type by itself. +class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + +Final = typing.Final + +# Breakpoint: https://github.com/python/cpython/pull/30530 +if sys.version_info >= (3, 11): + final = typing.final +else: + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + +if hasattr(typing, "disjoint_base"): # 3.15 + disjoint_base = typing.disjoint_base +else: + def disjoint_base(cls): + """This decorator marks a class as a disjoint base. + + Child classes of a disjoint base cannot inherit from other disjoint bases that are + not parent classes of the disjoint base. + + For example: + + @disjoint_base + class Disjoint1: pass + + @disjoint_base + class Disjoint2: pass + + class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error + + Type checkers can use knowledge of disjoint bases to detect unreachable code + and determine when two types can overlap. + + See PEP 800.""" + cls.__disjoint_base__ = True + return cls + + +def IntVar(name): + return typing.TypeVar(name) + + +# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 +# Breakpoint: https://github.com/python/cpython/pull/29334 +if sys.version_info >= (3, 10, 1): + Literal = typing.Literal +else: + def _flatten_literal_params(parameters): + """An internal helper for Literal creation: flatten Literals among parameters""" + params = [] + for p in parameters: + if isinstance(p, _LiteralGenericAlias): + params.extend(p.__args__) + else: + params.append(p) + return tuple(params) + + def _value_and_type_iter(params): + for p in params: + yield p, type(p) + + class _LiteralGenericAlias(typing._GenericAlias, _root=True): + def __eq__(self, other): + if not isinstance(other, _LiteralGenericAlias): + return NotImplemented + these_args_deduped = set(_value_and_type_iter(self.__args__)) + other_args_deduped = set(_value_and_type_iter(other.__args__)) + return these_args_deduped == other_args_deduped + + def __hash__(self): + return hash(frozenset(_value_and_type_iter(self.__args__))) + + class _LiteralForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, doc: str): + self._name = 'Literal' + self._doc = self.__doc__ = doc + + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + + parameters = _flatten_literal_params(parameters) + + val_type_pairs = list(_value_and_type_iter(parameters)) + try: + deduped_pairs = set(val_type_pairs) + except TypeError: + # unhashable parameters + pass + else: + # similar logic to typing._deduplicate on Python 3.9+ + if len(deduped_pairs) < len(val_type_pairs): + new_parameters = [] + for pair in val_type_pairs: + if pair in deduped_pairs: + new_parameters.append(pair[0]) + deduped_pairs.remove(pair) + assert not deduped_pairs, deduped_pairs + parameters = tuple(new_parameters) + + return _LiteralGenericAlias(self, parameters) + + Literal = _LiteralForm(doc="""\ + A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") + + +_overload_dummy = typing._overload_dummy + + +if hasattr(typing, "get_overloads"): # 3.11+ + overload = typing.overload + get_overloads = typing.get_overloads + clear_overloads = typing.clear_overloads +else: + # {module: {qualname: {firstlineno: func}}} + _overload_registry = collections.defaultdict( + functools.partial(collections.defaultdict, dict) + ) + + def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + + The overloads for a function can be retrieved at runtime using the + get_overloads() function. + """ + # classmethod and staticmethod + f = getattr(func, "__func__", func) + try: + _overload_registry[f.__module__][f.__qualname__][ + f.__code__.co_firstlineno + ] = func + except AttributeError: + # Not a normal function; ignore. + pass + return _overload_dummy + + def get_overloads(func): + """Return all defined overloads for *func* as a sequence.""" + # classmethod and staticmethod + f = getattr(func, "__func__", func) + if f.__module__ not in _overload_registry: + return [] + mod_dict = _overload_registry[f.__module__] + if f.__qualname__ not in mod_dict: + return [] + return list(mod_dict[f.__qualname__].values()) + + def clear_overloads(): + """Clear all overloads in the registry.""" + _overload_registry.clear() + + +# This is not a real generic class. Don't use outside annotations. +Type = typing.Type + +# Various ABCs mimicking those in collections.abc. +# A few are simply re-exported for completeness. +Awaitable = typing.Awaitable +Coroutine = typing.Coroutine +AsyncIterable = typing.AsyncIterable +AsyncIterator = typing.AsyncIterator +Deque = typing.Deque +DefaultDict = typing.DefaultDict +OrderedDict = typing.OrderedDict +Counter = typing.Counter +ChainMap = typing.ChainMap +Text = typing.Text +TYPE_CHECKING = typing.TYPE_CHECKING + + +# Breakpoint: https://github.com/python/cpython/pull/118681 +if sys.version_info >= (3, 13, 0, "beta"): + from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator +else: + def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') + + + class _SpecialGenericAlias(typing._SpecialGenericAlias, _root=True): + def __init__(self, origin, nparams, *, defaults, inst=True, name=None): + assert nparams > 0, "`nparams` must be a positive integer" + assert defaults, "Must always specify a non-empty sequence for `defaults`" + super().__init__(origin, nparams, inst=inst, name=name) + self._defaults = defaults + + def __setattr__(self, attr, val): + allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} + if _is_dunder(attr) or attr in allowed_attrs: + object.__setattr__(self, attr, val) + else: + setattr(self.__origin__, attr, val) + + @typing._tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(typing._type_check(p, msg) for p in params) + if ( + len(params) < self._nparams + and len(params) + len(self._defaults) >= self._nparams + ): + params = (*params, *self._defaults[len(params) - self._nparams:]) + actual_len = len(params) + + if actual_len != self._nparams: + expected = f"at least {self._nparams - len(self._defaults)}" + raise TypeError( + f"Too {'many' if actual_len > self._nparams else 'few'}" + f" arguments for {self};" + f" actual {actual_len}, expected {expected}" + ) + return self.copy_with(params) + + _NoneType = type(None) + Generator = _SpecialGenericAlias( + collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) + ) + AsyncGenerator = _SpecialGenericAlias( + collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) + ) + ContextManager = _SpecialGenericAlias( + contextlib.AbstractContextManager, + 2, + name="ContextManager", + defaults=(typing.Optional[bool],) + ) + AsyncContextManager = _SpecialGenericAlias( + contextlib.AbstractAsyncContextManager, + 2, + name="AsyncContextManager", + defaults=(typing.Optional[bool],) + ) + + +_PROTO_ALLOWLIST = { + 'collections.abc': [ + 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', + 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection', + 'Reversible', 'Buffer', + ], + 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], + 'io': ['Reader', 'Writer'], + 'typing_extensions': ['Buffer'], + 'os': ['PathLike'], +} + + +_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { + "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", + "__final__", +} + + +def _get_protocol_attrs(cls): + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in {'Protocol', 'Generic'}: + continue + annotations = getattr(base, '__annotations__', {}) + for attr in (*base.__dict__, *annotations): + if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): + attrs.add(attr) + return attrs + + +# `__match_args__` attribute was removed from protocol members in 3.13, +# we want to backport this change to older Python versions. +# 3.14 additionally added `io.Reader`, `io.Writer` and `os.PathLike` to +# the list of allowed protocol allowlist. +# https://github.com/python/cpython/issues/127647 +if sys.version_info >= (3, 14): + Protocol = typing.Protocol +else: + def _allow_reckless_class_checks(depth=2): + """Allow instance and class checks for special stdlib modules. + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + """ + return _caller(depth) in {'abc', 'functools', None} + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + def _type_check_issubclass_arg_1(arg): + """Raise TypeError if `arg` is not an instance of `type` + in `issubclass(arg, )`. + + In most cases, this is verified by type.__subclasscheck__. + Checking it again unnecessarily would slow down issubclass() checks, + so, we don't perform this check unless we absolutely have to. + + For various error paths, however, + we want to ensure that *this* error message is shown to the user + where relevant, rather than a typing.py-specific error message. + """ + if not isinstance(arg, type): + # Same error message as for issubclass(1, int). + raise TypeError('issubclass() arg 1 must be a class') + + # Inheriting from typing._ProtocolMeta isn't actually desirable, + # but is necessary to allow typing.Protocol and typing_extensions.Protocol + # to mix without getting TypeErrors about "metaclass conflict" + class _ProtocolMeta(type(typing.Protocol)): + # This metaclass is somewhat unfortunate, + # but is necessary for several reasons... + # + # NOTE: DO NOT call super() in any methods in this class + # That would call the methods on typing._ProtocolMeta on Python <=3.11 + # and those are slow + def __new__(mcls, name, bases, namespace, **kwargs): + if name == "Protocol" and len(bases) < 2: + pass + elif {Protocol, typing.Protocol} & set(bases): + for base in bases: + if not ( + base in {object, typing.Generic, Protocol, typing.Protocol} + or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) + or is_protocol(base) + ): + raise TypeError( + f"Protocols can only inherit from other protocols, " + f"got {base!r}" + ) + return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) + + def __init__(cls, *args, **kwargs): + abc.ABCMeta.__init__(cls, *args, **kwargs) + if getattr(cls, "_is_protocol", False): + cls.__protocol_attrs__ = _get_protocol_attrs(cls) + + def __subclasscheck__(cls, other): + if cls is Protocol: + return type.__subclasscheck__(cls, other) + if ( + getattr(cls, '_is_protocol', False) + and not _allow_reckless_class_checks() + ): + if not getattr(cls, '_is_runtime_protocol', False): + _type_check_issubclass_arg_1(other) + raise TypeError( + "Instance and class checks can only be used with " + "@runtime_checkable protocols" + ) + if ( + # this attribute is set by @runtime_checkable: + cls.__non_callable_proto_members__ + and cls.__dict__.get("__subclasshook__") is _proto_hook + ): + _type_check_issubclass_arg_1(other) + non_method_attrs = sorted(cls.__non_callable_proto_members__) + raise TypeError( + "Protocols with non-method members don't support issubclass()." + f" Non-method members: {str(non_method_attrs)[1:-1]}." + ) + return abc.ABCMeta.__subclasscheck__(cls, other) + + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if cls is Protocol: + return type.__instancecheck__(cls, instance) + if not getattr(cls, "_is_protocol", False): + # i.e., it's a concrete subclass of a protocol + return abc.ABCMeta.__instancecheck__(cls, instance) + + if ( + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks() + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + + if abc.ABCMeta.__instancecheck__(cls, instance): + return True + + for attr in cls.__protocol_attrs__: + try: + val = inspect.getattr_static(instance, attr) + except AttributeError: + break + # this attribute is set by @runtime_checkable: + if val is None and attr not in cls.__non_callable_proto_members__: + break + else: + return True + + return False + + def __eq__(cls, other): + # Hack so that typing.Generic.__class_getitem__ + # treats typing_extensions.Protocol + # as equivalent to typing.Protocol + if abc.ABCMeta.__eq__(cls, other) is True: + return True + return cls is Protocol and other is typing.Protocol + + # This has to be defined, or the abc-module cache + # complains about classes with this metaclass being unhashable, + # if we define only __eq__! + def __hash__(cls) -> int: + return type.__hash__(cls) + + @classmethod + def _proto_hook(cls, other): + if not cls.__dict__.get('_is_protocol', False): + return NotImplemented + + for attr in cls.__protocol_attrs__: + for base in other.__mro__: + # Check if the members appears in the class dictionary... + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + + # ...or in annotations, if it is a sub-protocol. + annotations = getattr(base, '__annotations__', {}) + if ( + isinstance(annotations, collections.abc.Mapping) + and attr in annotations + and is_protocol(other) + ): + break + else: + return NotImplemented + return True + + class Protocol(typing.Generic, metaclass=_ProtocolMeta): + __doc__ = typing.Protocol.__doc__ + __slots__ = () + _is_protocol = True + _is_runtime_protocol = False + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', False): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # Prohibit instantiation for protocol classes + if cls._is_protocol and cls.__init__ is Protocol.__init__: + cls.__init__ = _no_init + + +# Breakpoint: https://github.com/python/cpython/pull/113401 +if sys.version_info >= (3, 13): + runtime_checkable = typing.runtime_checkable +else: + def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + """ + if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): + raise TypeError(f'@runtime_checkable can be only applied to protocol classes,' + f' got {cls!r}') + cls._is_runtime_protocol = True + + # typing.Protocol classes on <=3.11 break if we execute this block, + # because typing.Protocol classes on <=3.11 don't have a + # `__protocol_attrs__` attribute, and this block relies on the + # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ + # break if we *don't* execute this block, because *they* assume that all + # protocol classes have a `__non_callable_proto_members__` attribute + # (which this block sets) + if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): + # PEP 544 prohibits using issubclass() + # with protocols that have non-method members. + # See gh-113320 for why we compute this attribute here, + # rather than in `_ProtocolMeta.__init__` + cls.__non_callable_proto_members__ = set() + for attr in cls.__protocol_attrs__: + try: + is_callable = callable(getattr(cls, attr, None)) + except Exception as e: + raise TypeError( + f"Failed to determine whether protocol member {attr!r} " + "is a method member" + ) from e + else: + if not is_callable: + cls.__non_callable_proto_members__.add(attr) + + return cls + + +# The "runtime" alias exists for backwards compatibility. +runtime = runtime_checkable + + +# Our version of runtime-checkable protocols is faster on Python <=3.11 +# Breakpoint: https://github.com/python/cpython/pull/112717 +if sys.version_info >= (3, 12): + SupportsInt = typing.SupportsInt + SupportsFloat = typing.SupportsFloat + SupportsComplex = typing.SupportsComplex + SupportsBytes = typing.SupportsBytes + SupportsIndex = typing.SupportsIndex + SupportsAbs = typing.SupportsAbs + SupportsRound = typing.SupportsRound +else: + @runtime_checkable + class SupportsInt(Protocol): + """An ABC with one abstract method __int__.""" + __slots__ = () + + @abc.abstractmethod + def __int__(self) -> int: + pass + + @runtime_checkable + class SupportsFloat(Protocol): + """An ABC with one abstract method __float__.""" + __slots__ = () + + @abc.abstractmethod + def __float__(self) -> float: + pass + + @runtime_checkable + class SupportsComplex(Protocol): + """An ABC with one abstract method __complex__.""" + __slots__ = () + + @abc.abstractmethod + def __complex__(self) -> complex: + pass + + @runtime_checkable + class SupportsBytes(Protocol): + """An ABC with one abstract method __bytes__.""" + __slots__ = () + + @abc.abstractmethod + def __bytes__(self) -> bytes: + pass + + @runtime_checkable + class SupportsIndex(Protocol): + __slots__ = () + + @abc.abstractmethod + def __index__(self) -> int: + pass + + @runtime_checkable + class SupportsAbs(Protocol[T_co]): + """ + An ABC with one abstract method __abs__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __abs__(self) -> T_co: + pass + + @runtime_checkable + class SupportsRound(Protocol[T_co]): + """ + An ABC with one abstract method __round__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __round__(self, ndigits: int = 0) -> T_co: + pass + + +if hasattr(io, "Reader") and hasattr(io, "Writer"): + Reader = io.Reader + Writer = io.Writer +else: + @runtime_checkable + class Reader(Protocol[T_co]): + """Protocol for simple I/O reader instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def read(self, size: int = ..., /) -> T_co: + """Read data from the input stream and return it. + + If *size* is specified, at most *size* items (bytes/characters) will be + read. + """ + + @runtime_checkable + class Writer(Protocol[T_contra]): + """Protocol for simple I/O writer instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def write(self, data: T_contra, /) -> int: + """Write *data* to the output stream and return the number of items written.""" # noqa: E501 + + +_NEEDS_SINGLETONMETA = ( + not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems") +) + +if _NEEDS_SINGLETONMETA: + class SingletonMeta(type): + def __setattr__(cls, attr, value): + # TypeError is consistent with the behavior of NoneType + raise TypeError( + f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" + ) + + +if hasattr(typing, "NoDefault"): + NoDefault = typing.NoDefault +else: + class NoDefaultType(metaclass=SingletonMeta): + """The type of the NoDefault singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoDefault") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoDefault" + + def __reduce__(self): + return "NoDefault" + + NoDefault = NoDefaultType() + del NoDefaultType + +if hasattr(typing, "NoExtraItems"): + NoExtraItems = typing.NoExtraItems +else: + class NoExtraItemsType(metaclass=SingletonMeta): + """The type of the NoExtraItems singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoExtraItems") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoExtraItems" + + def __reduce__(self): + return "NoExtraItems" + + NoExtraItems = NoExtraItemsType() + del NoExtraItemsType + +if _NEEDS_SINGLETONMETA: + del SingletonMeta + + +# Update this to something like >=3.13.0b1 if and when +# PEP 764 is implemented in CPython +_PEP_764_IMPLEMENTED = False + +if _PEP_764_IMPLEMENTED: + # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" + # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 + # The standard library TypedDict below Python 3.11 does not store runtime + # information about optional and required keys when using Required or NotRequired. + # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. + # Aaaand on 3.12 we add __orig_bases__ to TypedDict + # to enable better runtime introspection. + # On 3.13 we deprecate some odd ways of creating TypedDicts. + # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. + # PEP 728 (Python 3.15+) adds the `extra_items` and `closed` keywords. + # PEP 764 (still pending) allows the `TypedDict` special form to be subscripted. + TypedDict = typing.TypedDict + _TypedDictMeta = typing._TypedDictMeta + is_typeddict = typing.is_typeddict +else: + # 3.10.0 and later + _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters + + def _get_typeddict_qualifiers(annotation_type): + while True: + annotation_origin = get_origin(annotation_type) + if annotation_origin is Annotated: + annotation_args = get_args(annotation_type) + if annotation_args: + annotation_type = annotation_args[0] + else: + break + elif annotation_origin is Required: + yield Required + annotation_type, = get_args(annotation_type) + elif annotation_origin is NotRequired: + yield NotRequired + annotation_type, = get_args(annotation_type) + elif annotation_origin is ReadOnly: + yield ReadOnly + annotation_type, = get_args(annotation_type) + else: + break + + class _TypedDictMeta(type): + + def __new__(cls, name, bases, ns, *, total=True, closed=None, + extra_items=NoExtraItems): + """Create new typed dict class object. + + This method is called when TypedDict is subclassed, + or when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries. + """ + for base in bases: + if type(base) is not _TypedDictMeta and base is not typing.Generic: + raise TypeError('cannot inherit from both a TypedDict type ' + 'and a non-TypedDict base class') + if closed is not None and extra_items is not NoExtraItems: + raise TypeError(f"Cannot combine closed={closed!r} and extra_items") + + if any(issubclass(b, typing.Generic) for b in bases): + generic_base = (typing.Generic,) + else: + generic_base = () + + ns_annotations = ns.pop('__annotations__', None) + + # typing.py generally doesn't let you inherit from plain Generic, unless + # the name of the class happens to be "Protocol" + tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) + tp_dict.__name__ = name + if tp_dict.__qualname__ == "Protocol": + tp_dict.__qualname__ = name + + if not hasattr(tp_dict, '__orig_bases__'): + tp_dict.__orig_bases__ = bases + + annotations = {} + own_annotate = None + if ns_annotations is not None: + own_annotations = ns_annotations + elif sys.version_info >= (3, 14): + if hasattr(annotationlib, "get_annotate_from_class_namespace"): + own_annotate = annotationlib.get_annotate_from_class_namespace(ns) + else: + # 3.14.0a7 and earlier + own_annotate = ns.get("__annotate__") + if own_annotate is not None: + own_annotations = annotationlib.call_annotate_function( + own_annotate, Format.FORWARDREF, owner=tp_dict + ) + else: + own_annotations = {} + else: + own_annotations = {} + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + if _TAKES_MODULE: + own_checked_annotations = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } + else: + own_checked_annotations = { + n: typing._type_check(tp, msg) + for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + readonly_keys = set() + mutable_keys = set() + extra_items_type = extra_items + + for base in bases: + base_dict = base.__dict__ + + if sys.version_info <= (3, 14): + annotations.update(base_dict.get('__annotations__', {})) + base_required = base_dict.get('__required_keys__', set()) + required_keys |= base_required + optional_keys -= base_required + + base_optional = base_dict.get('__optional_keys__', set()) + required_keys -= base_optional + optional_keys |= base_optional + + readonly_keys.update(base_dict.get('__readonly_keys__', ())) + mutable_keys.update(base_dict.get('__mutable_keys__', ())) + + # This was specified in an earlier version of PEP 728. Support + # is retained for backwards compatibility, but only for Python + # 3.13 and lower. + if (closed and sys.version_info < (3, 14) + and "__extra_items__" in own_checked_annotations): + annotation_type = own_checked_annotations.pop("__extra_items__") + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + if Required in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "Required" + ) + if NotRequired in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "NotRequired" + ) + extra_items_type = annotation_type + + annotations.update(own_checked_annotations) + for annotation_key, annotation_type in own_checked_annotations.items(): + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + + if Required in qualifiers: + is_required = True + elif NotRequired in qualifiers: + is_required = False + else: + is_required = total + + if is_required: + required_keys.add(annotation_key) + optional_keys.discard(annotation_key) + else: + optional_keys.add(annotation_key) + required_keys.discard(annotation_key) + + if ReadOnly in qualifiers: + mutable_keys.discard(annotation_key) + readonly_keys.add(annotation_key) + else: + mutable_keys.add(annotation_key) + readonly_keys.discard(annotation_key) + + # Breakpoint: https://github.com/python/cpython/pull/119891 + if sys.version_info >= (3, 14): + def __annotate__(format): + annos = {} + for base in bases: + if base is Generic: + continue + base_annotate = base.__annotate__ + if base_annotate is None: + continue + base_annos = annotationlib.call_annotate_function( + base_annotate, format, owner=base) + annos.update(base_annos) + if own_annotate is not None: + own = annotationlib.call_annotate_function( + own_annotate, format, owner=tp_dict) + if format != Format.STRING: + own = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own.items() + } + elif format == Format.STRING: + own = annotationlib.annotations_to_string(own_annotations) + elif format in (Format.FORWARDREF, Format.VALUE): + own = own_checked_annotations + else: + raise NotImplementedError(format) + annos.update(own) + return annos + + tp_dict.__annotate__ = __annotate__ + else: + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + tp_dict.__readonly_keys__ = frozenset(readonly_keys) + tp_dict.__mutable_keys__ = frozenset(mutable_keys) + tp_dict.__total__ = total + tp_dict.__closed__ = closed + tp_dict.__extra_items__ = extra_items_type + return tp_dict + + __call__ = dict # static method + + def __subclasscheck__(cls, other): + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + + __instancecheck__ = __subclasscheck__ + + _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) + + def _create_typeddict( + typename, + fields, + /, + *, + typing_is_inline, + total, + closed, + extra_items, + **kwargs, + ): + if fields is _marker or fields is None: + if fields is _marker: + deprecated_thing = ( + "Failing to pass a value for the 'fields' parameter" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + + example = f"`{typename} = TypedDict({typename!r}, {{}})`" + deprecation_msg = ( + f"{deprecated_thing} is deprecated and will be disallowed in " + "Python 3.15. To create a TypedDict class with 0 fields " + "using the functional syntax, pass an empty dictionary, e.g. " + ) + example + "." + warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) + # Support a field called "closed" + if closed is not False and closed is not True and closed is not None: + kwargs["closed"] = closed + closed = None + # Or "extra_items" + if extra_items is not NoExtraItems: + kwargs["extra_items"] = extra_items + extra_items = NoExtraItems + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + if kwargs: + # Breakpoint: https://github.com/python/cpython/pull/104891 + if sys.version_info >= (3, 13): + raise TypeError("TypedDict takes no keyword arguments") + warnings.warn( + "The kwargs-based syntax for TypedDict definitions is deprecated " + "in Python 3.11, will be removed in Python 3.13, and may not be " + "understood by third-party type checkers.", + DeprecationWarning, + stacklevel=2, + ) + + ns = {'__annotations__': dict(fields)} + module = _caller(depth=4 if typing_is_inline else 2) + if module is not None: + # Setting correct module is necessary to make typed dict classes + # pickleable. + ns['__module__'] = module + + td = _TypedDictMeta(typename, (), ns, total=total, closed=closed, + extra_items=extra_items) + td.__orig_bases__ = (TypedDict,) + return td + + class _TypedDictSpecialForm(_SpecialForm, _root=True): + def __call__( + self, + typename, + fields=_marker, + /, + *, + total=True, + closed=None, + extra_items=NoExtraItems, + **kwargs + ): + return _create_typeddict( + typename, + fields, + typing_is_inline=False, + total=total, + closed=closed, + extra_items=extra_items, + **kwargs, + ) + + def __mro_entries__(self, bases): + return (_TypedDict,) + + @_TypedDictSpecialForm + def TypedDict(self, args): + """A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type such that a type checker will expect all + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime. + + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports an additional equivalent form:: + + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + This means that a Point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The Required and NotRequired special forms can also be used to mark + individual keys as being required or not required:: + + class Point2D(TypedDict): + x: int # the "x" key must always be present (Required is the default) + y: NotRequired[int] # the "y" key can be omitted + + See PEP 655 for more details on Required and NotRequired. + """ + # This runs when creating inline TypedDicts: + if not isinstance(args, dict): + raise TypeError( + "TypedDict[...] should be used with a single dict argument" + ) + + return _create_typeddict( + "", + args, + typing_is_inline=True, + total=True, + closed=True, + extra_items=NoExtraItems, + ) + + _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) + + def is_typeddict(tp): + """Check if an annotation is a TypedDict class + + For example:: + class Film(TypedDict): + title: str + year: int + + is_typeddict(Film) # => True + is_typeddict(Union[list, str]) # => False + """ + return isinstance(tp, _TYPEDDICT_TYPES) + + +if hasattr(typing, "assert_type"): + assert_type = typing.assert_type + +else: + def assert_type(val, typ, /): + """Assert (to the type checker) that the value is of the given type. + + When the type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # ok + assert_type(name, int) # type checker error + + At runtime this returns the first argument unchanged and otherwise + does nothing. + """ + return val + + +if hasattr(typing, "ReadOnly"): # 3.13+ + get_type_hints = typing.get_type_hints +else: # <=3.13 + # replaces _strip_annotations() + def _strip_extras(t): + """Strips Annotated, Required and NotRequired from a given type.""" + if isinstance(t, typing._AnnotatedAlias): + return _strip_extras(t.__origin__) + if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): + return _strip_extras(t.__args__[0]) + if isinstance(t, typing._GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return t.copy_with(stripped_args) + if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return _types.GenericAlias(t.__origin__, stripped_args) + if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return functools.reduce(operator.or_, stripped_args) + + return t + + def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' + (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + hint = typing.get_type_hints( + obj, globalns=globalns, localns=localns, include_extras=True + ) + # Breakpoint: https://github.com/python/cpython/pull/30304 + if sys.version_info < (3, 11): + _clean_optional(obj, hint, globalns, localns) + if include_extras: + return hint + return {k: _strip_extras(t) for k, t in hint.items()} + + _NoneType = type(None) + + def _could_be_inserted_optional(t): + """detects Union[..., None] pattern""" + if not isinstance(t, typing._UnionGenericAlias): + return False + # Assume if last argument is not None they are user defined + if t.__args__[-1] is not _NoneType: + return False + return True + + # < 3.11 + def _clean_optional(obj, hints, globalns=None, localns=None): + # reverts injected Union[..., None] cases from typing.get_type_hints + # when a None default value is used. + # see https://github.com/python/typing_extensions/issues/310 + if not hints or isinstance(obj, type): + return + defaults = typing._get_defaults(obj) # avoid accessing __annotations___ + if not defaults: + return + original_hints = obj.__annotations__ + for name, value in hints.items(): + # Not a Union[..., None] or replacement conditions not fullfilled + if (not _could_be_inserted_optional(value) + or name not in defaults + or defaults[name] is not None + ): + continue + original_value = original_hints[name] + # value=NoneType should have caused a skip above but check for safety + if original_value is None: + original_value = _NoneType + # Forward reference + if isinstance(original_value, str): + if globalns is None: + if isinstance(obj, _types.ModuleType): + globalns = obj.__dict__ + else: + nsobj = obj + # Find globalns for the unwrapped object. + while hasattr(nsobj, '__wrapped__'): + nsobj = nsobj.__wrapped__ + globalns = getattr(nsobj, '__globals__', {}) + if localns is None: + localns = globalns + elif localns is None: + localns = globalns + + original_value = ForwardRef( + original_value, + is_argument=not isinstance(obj, _types.ModuleType) + ) + original_evaluated = typing._eval_type(original_value, globalns, localns) + # Compare if values differ. Note that even if equal + # value might be cached by typing._tp_cache contrary to original_evaluated + if original_evaluated != value or ( + # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias + hasattr(_types, "UnionType") + and isinstance(original_evaluated, _types.UnionType) + and not isinstance(value, _types.UnionType) + ): + hints[name] = original_evaluated + +# Python 3.9 has get_origin() and get_args() but those implementations don't support +# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. +# Breakpoint: https://github.com/python/cpython/pull/25298 +if sys.version_info >= (3, 10): + get_origin = typing.get_origin + get_args = typing.get_args +# 3.9 +else: + def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar + and Annotated. Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + get_origin(P.args) is P + """ + if isinstance(tp, typing._AnnotatedAlias): + return Annotated + if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is typing.Generic: + return typing.Generic + return None + + def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, typing._AnnotatedAlias): + return (tp.__origin__, *tp.__metadata__) + if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)): + res = tp.__args__ + if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return () + + +# 3.10+ +if hasattr(typing, 'TypeAlias'): + TypeAlias = typing.TypeAlias +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeAlias(self, parameters): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError(f"{self} is not subscriptable") + + +def _set_default(type_param, default): + type_param.has_default = lambda: default is not NoDefault + type_param.__default__ = default + + +def _set_module(typevarlike): + # for pickling: + def_mod = _caller(depth=2) + if def_mod != 'typing_extensions': + typevarlike.__module__ = def_mod + + +class _DefaultMixin: + """Mixin for TypeVarLike defaults.""" + + __slots__ = () + __init__ = _set_default + + +# Classes using this metaclass must provide a _backported_typevarlike ClassVar +class _TypeVarLikeMeta(type): + def __instancecheck__(cls, __instance: Any) -> bool: + return isinstance(__instance, cls._backported_typevarlike) + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVar +else: + # Add default and infer_variance parameters from PEP 696 and 695 + class TypeVar(metaclass=_TypeVarLikeMeta): + """Type variable.""" + + _backported_typevarlike = typing.TypeVar + + def __new__(cls, name, *constraints, bound=None, + covariant=False, contravariant=False, + default=NoDefault, infer_variance=False): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant, + infer_variance=infer_variance) + else: + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant) + if infer_variance and (covariant or contravariant): + raise ValueError("Variance cannot be specified with infer_variance.") + typevar.__infer_variance__ = infer_variance + + _set_default(typevar, default) + _set_module(typevar) + + def _tvar_prepare_subst(alias, args): + if ( + typevar.has_default() + and alias.__parameters__.index(typevar) == len(args) + ): + args += (typevar.__default__,) + return args + + typevar.__typing_prepare_subst__ = _tvar_prepare_subst + return typevar + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") + + +# Python 3.10+ has PEP 612 +if hasattr(typing, 'ParamSpecArgs'): + ParamSpecArgs = typing.ParamSpecArgs + ParamSpecKwargs = typing.ParamSpecKwargs +# 3.9 +else: + class _Immutable: + """Mixin to indicate that object should not be copied.""" + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + class ParamSpecArgs(_Immutable): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.args" + + def __eq__(self, other): + if not isinstance(other, ParamSpecArgs): + return NotImplemented + return self.__origin__ == other.__origin__ + + class ParamSpecKwargs(_Immutable): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.kwargs" + + def __eq__(self, other): + if not isinstance(other, ParamSpecKwargs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +if _PEP_696_IMPLEMENTED: + from typing import ParamSpec + +# 3.10+ +elif hasattr(typing, 'ParamSpec'): + + # Add default parameter - PEP 696 + class ParamSpec(metaclass=_TypeVarLikeMeta): + """Parameter specification.""" + + _backported_typevarlike = typing.ParamSpec + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented, can pass infer_variance to typing.TypeVar + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant, + infer_variance=infer_variance) + else: + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant) + paramspec.__infer_variance__ = bool(infer_variance) + + _set_default(paramspec, default) + _set_module(paramspec) + + def _paramspec_prepare_subst(alias, args): + params = alias.__parameters__ + i = params.index(paramspec) + if i == len(args) and paramspec.has_default(): + args = [*args, paramspec.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. + if len(params) == 1 and not typing._is_param_expr(args[0]): + assert i == 0 + args = (args,) + # Convert lists to tuples to help other libraries cache the results. + elif isinstance(args[i], list): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + return args + + paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst + return paramspec + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + +# 3.9 +else: + + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class ParamSpec(list, _DefaultMixin): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or s the first argument to ``Callable``. In Python 3.10 and higher, + they are also supported in user-defined Generics at runtime. + See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables defined with covariant=True or + contravariant=True can be used to declare covariant or contravariant + generic types. These keyword arguments are valid, but their actual semantics + are yet to be decided. See PEP 612 for details. + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'T' + P.__bound__ == None + P.__covariant__ == False + P.__contravariant__ == False + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + list.__init__(self, [self]) + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + self.__bound__ = bound + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + # Hack to get typing._type_check to pass. + def __call__(self, *args, **kwargs): + pass + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + + +# 3.9 +if not hasattr(typing, 'Concatenate'): + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + + # 3.9.0-1 + if not hasattr(typing, '_type_convert'): + def _type_convert(arg, module=None, *, allow_special_forms=False): + """For converting None to type(None), and strings to ForwardRef.""" + if arg is None: + return type(None) + if isinstance(arg, str): + if sys.version_info <= (3, 9, 6): + return ForwardRef(arg) + if sys.version_info <= (3, 9, 7): + return ForwardRef(arg, module=module) + return ForwardRef(arg, module=module, is_class=allow_special_forms) + return arg + else: + _type_convert = typing._type_convert + + class _ConcatenateGenericAlias(list): + + # Trick Generic into looking into this for __parameters__. + __class__ = typing._GenericAlias + + def __init__(self, origin, args): + # Cannot use `super().__init__` here because of the `__class__` assignment + # in the class body (https://github.com/python/typing_extensions/issues/661) + list.__init__(self, args) + self.__origin__ = origin + self.__args__ = args + + def __repr__(self): + _type_repr = typing._type_repr + return (f'{_type_repr(self.__origin__)}' + f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + # Hack to get typing._type_check to pass in Generic. + def __call__(self, *args, **kwargs): + pass + + @property + def __parameters__(self): + return tuple( + tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) + ) + + # 3.9 used by __getitem__ below + def copy_with(self, params): + if isinstance(params[-1], _ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return self.__class__(self.__origin__, params) + + # 3.9; accessed during GenericAlias.__getitem__ when substituting + def __getitem__(self, args): + if self.__origin__ in (Generic, Protocol): + # Can't subscript Generic[...] or Protocol[...]. + raise TypeError(f"Cannot subscript already-subscripted {self}") + if not self.__parameters__: + raise TypeError(f"{self} is not a generic class") + + if not isinstance(args, tuple): + args = (args,) + args = _unpack_args(*(_type_convert(p) for p in args)) + params = self.__parameters__ + for param in params: + prepare = getattr(param, "__typing_prepare_subst__", None) + if prepare is not None: + args = prepare(self, args) + # 3.9 & typing.ParamSpec + elif isinstance(param, ParamSpec): + i = params.index(param) + if ( + i == len(args) + and getattr(param, '__default__', NoDefault) is not NoDefault + ): + args = [*args, param.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {self}") + # Special case for Z[[int, str, bool]] == Z[int, str, bool] + if len(params) == 1 and not _is_param_expr(args[0]): + assert i == 0 + args = (args,) + elif ( + isinstance(args[i], list) + # 3.9 + # This class inherits from list do not convert + and not isinstance(args[i], _ConcatenateGenericAlias) + ): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + + alen = len(args) + plen = len(params) + if alen != plen: + raise TypeError( + f"Too {'many' if alen > plen else 'few'} arguments for {self};" + f" actual {alen}, expected {plen}" + ) + + subst = dict(zip(self.__parameters__, args)) + # determine new args + new_args = [] + for arg in self.__args__: + if isinstance(arg, type): + new_args.append(arg) + continue + if isinstance(arg, TypeVar): + arg = subst[arg] + if ( + (isinstance(arg, typing._GenericAlias) and _is_unpack(arg)) + or ( + hasattr(_types, "GenericAlias") + and isinstance(arg, _types.GenericAlias) + and getattr(arg, "__unpacked__", False) + ) + ): + raise TypeError(f"{arg} is not valid as type argument") + + elif isinstance(arg, + typing._GenericAlias + if not hasattr(_types, "GenericAlias") else + (typing._GenericAlias, _types.GenericAlias) + ): + subparams = arg.__parameters__ + if subparams: + subargs = tuple(subst[x] for x in subparams) + arg = arg[subargs] + new_args.append(arg) + return self.copy_with(tuple(new_args)) + +# 3.10+ +else: + _ConcatenateGenericAlias = typing._ConcatenateGenericAlias + + # 3.10 + if sys.version_info < (3, 11): + + class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): + # needed for checks in collections.abc.Callable to accept this class + __module__ = "typing" + + def copy_with(self, params): + if isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + if isinstance(params[-1], typing._ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return super(typing._ConcatenateGenericAlias, self).copy_with(params) + + def __getitem__(self, args): + value = super().__getitem__(args) + if isinstance(value, tuple) and any(_is_unpack(t) for t in value): + return tuple(_unpack_args(*(n for n in value))) + return value + + +# 3.9.2 +class _EllipsisDummy: ... + + +# <=3.10 +def _create_concatenate_alias(origin, parameters): + if parameters[-1] is ... and sys.version_info < (3, 9, 2): + # Hack: Arguments must be types, replace it with one. + parameters = (*parameters[:-1], _EllipsisDummy) + if sys.version_info >= (3, 10, 3): + concatenate = _ConcatenateGenericAlias(origin, parameters, + _typevar_types=(TypeVar, ParamSpec), + _paramspec_tvars=True) + else: + concatenate = _ConcatenateGenericAlias(origin, parameters) + if parameters[-1] is not _EllipsisDummy: + return concatenate + # Remove dummy again + concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... + for p in concatenate.__args__) + if sys.version_info < (3, 10): + # backport needs __args__ adjustment only + return concatenate + concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ + if p is not _EllipsisDummy) + return concatenate + + +# <=3.10 +@typing._tp_cache +def _concatenate_getitem(self, parameters): + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), + parameters[-1]) + return _create_concatenate_alias(self, parameters) + + +# 3.11+; Concatenate does not accept ellipsis in 3.10 +# Breakpoint: https://github.com/python/cpython/pull/30969 +if sys.version_info >= (3, 11): + Concatenate = typing.Concatenate +# <=3.10 +else: + @_ExtensionsSpecialForm + def Concatenate(self, parameters): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + return _concatenate_getitem(self, parameters) + + +# 3.10+ +if hasattr(typing, 'TypeGuard'): + TypeGuard = typing.TypeGuard +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeGuard(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.13+ +if hasattr(typing, 'TypeIs'): + TypeIs = typing.TypeIs +# <=3.12 +else: + @_ExtensionsSpecialForm + def TypeIs(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type narrower function. ``TypeIs`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeIs[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeIs`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the intersection of the type inside ``TypeIs`` and the argument's + previously known type. + + For example:: + + def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: + return hasattr(val, '__await__') + + def f(val: Union[int, Awaitable[int]]) -> int: + if is_awaitable(val): + assert_type(val, Awaitable[int]) + else: + assert_type(val, int) + + ``TypeIs`` also works with type variables. For more information, see + PEP 742 (Narrowing types with TypeIs). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.15+? +if hasattr(typing, 'TypeForm'): + TypeForm = typing.TypeForm +# <=3.14 +else: + class _TypeFormForm(_ExtensionsSpecialForm, _root=True): + # TypeForm(X) is equivalent to X but indicates to the type checker + # that the object is a TypeForm. + def __call__(self, obj, /): + return obj + + @_TypeFormForm + def TypeForm(self, parameters): + """A special form representing the value that results from the evaluation + of a type expression. This value encodes the information supplied in the + type expression, and it represents the type described by that type expression. + + When used in a type expression, TypeForm describes a set of type form objects. + It accepts a single type argument, which must be a valid type expression. + ``TypeForm[T]`` describes the set of all type form objects that represent + the type T or types that are assignable to T. + + Usage: + + def cast[T](typ: TypeForm[T], value: Any) -> T: ... + + reveal_type(cast(int, "x")) # int + + See PEP 747 for more information. + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + + + +if hasattr(typing, "LiteralString"): # 3.11+ + LiteralString = typing.LiteralString +else: + @_SpecialForm + def LiteralString(self, params): + """Represents an arbitrary literal string. + + Example:: + + from typing_extensions import LiteralString + + def query(sql: LiteralString) -> ...: + ... + + query("SELECT * FROM table") # ok + query(f"SELECT * FROM {input()}") # not ok + + See PEP 675 for details. + + """ + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Self"): # 3.11+ + Self = typing.Self +else: + @_SpecialForm + def Self(self, params): + """Used to spell the type of "self" in classes. + + Example:: + + from typing import Self + + class ReturnsSelf: + def parse(self, data: bytes) -> Self: + ... + return self + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Never"): # 3.11+ + Never = typing.Never +else: + @_SpecialForm + def Never(self, params): + """The bottom type, a type that has no members. + + This can be used to define a function that should never be + called, or a function that never returns:: + + from typing_extensions import Never + + def never_call_me(arg: Never) -> None: + pass + + def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # ok, arg is of type Never + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, 'Required'): # 3.11+ + Required = typing.Required + NotRequired = typing.NotRequired +else: # <=3.10 + @_ExtensionsSpecialForm + def Required(self, parameters): + """A special typing construct to mark a key of a total=False TypedDict + as required. For example: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + @_ExtensionsSpecialForm + def NotRequired(self, parameters): + """A special typing construct to mark a key of a TypedDict as + potentially missing. For example: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +if hasattr(typing, 'ReadOnly'): + ReadOnly = typing.ReadOnly +else: # <=3.12 + @_ExtensionsSpecialForm + def ReadOnly(self, parameters): + """A special typing construct to mark an item of a TypedDict as read-only. + + For example: + + class Movie(TypedDict): + title: ReadOnly[str] + year: int + + def mutate_movie(m: Movie) -> None: + m["year"] = 1992 # allowed + m["title"] = "The Matrix" # typechecker error + + There is no runtime checking for this property. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +_UNPACK_DOC = """\ +Type unpack operator. + +The type unpack operator takes the child types from some container type, +such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For +example: + + # For some generic class `Foo`: + Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] + + Ts = TypeVarTuple('Ts') + # Specifies that `Bar` is generic in an arbitrary number of types. + # (Think of `Ts` as a tuple of an arbitrary number of individual + # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the + # `Generic[]`.) + class Bar(Generic[Unpack[Ts]]): ... + Bar[int] # Valid + Bar[int, str] # Also valid + +From Python 3.11, this can also be done using the `*` operator: + + Foo[*tuple[int, str]] + class Bar(Generic[*Ts]): ... + +The operator can also be used along with a `TypedDict` to annotate +`**kwargs` in a function signature. For instance: + + class Movie(TypedDict): + name: str + year: int + + # This function expects two keyword arguments - *name* of type `str` and + # *year* of type `int`. + def foo(**kwargs: Unpack[Movie]): ... + +Note that there is only some runtime checking of this operator. Not +everything the runtime allows may be accepted by static type checkers. + +For more information, see PEP 646 and PEP 692. +""" + + +# PEP 692 changed the repr of Unpack[] +# Breakpoint: https://github.com/python/cpython/pull/104048 +if sys.version_info >= (3, 12): + Unpack = typing.Unpack + + def _is_unpack(obj): + return get_origin(obj) is Unpack + +else: # <=3.11 + class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, getitem): + super().__init__(getitem) + self.__doc__ = _UNPACK_DOC + + class _UnpackAlias(typing._GenericAlias, _root=True): + if sys.version_info < (3, 11): + # needed for compatibility with Generic[Unpack[Ts]] + __class__ = typing.TypeVar + + @property + def __typing_unpacked_tuple_args__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + arg, = self.__args__ + if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): + if arg.__origin__ is not tuple: + raise TypeError("Unpack[...] must be used with a tuple type") + return arg.__args__ + return None + + @property + def __typing_is_unpacked_typevartuple__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + return isinstance(self.__args__[0], TypeVarTuple) + + def __getitem__(self, args): + if self.__typing_is_unpacked_typevartuple__: + return args + # Cannot use `super().__getitem__` here because of the `__class__` assignment + # in the class body on Python <=3.11 + # (https://github.com/python/typing_extensions/issues/661) + return typing._GenericAlias.__getitem__(self, args) + + @_UnpackSpecialForm + def Unpack(self, parameters): + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return _UnpackAlias(self, (item,)) + + def _is_unpack(obj): + return isinstance(obj, _UnpackAlias) + + +def _unpack_args(*args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs is not None and (not (subargs and subargs[-1] is ...)): + newargs.extend(subargs) + else: + newargs.append(arg) + return newargs + + +if sys.version_info >= (3, 15): + from typing import TypeVarTuple + +elif hasattr(typing, "TypeVarTuple"): # 3.11+ + + # Add default parameter - PEP 696 and bound/variance parameters + class TypeVarTuple(metaclass=_TypeVarLikeMeta): + """Type variable tuple.""" + + _backported_typevarlike = typing.TypeVarTuple + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + + if _PEP_696_IMPLEMENTED: + # can pass default argument + tvt = typing.TypeVarTuple(name, default=default) + else: + tvt = typing.TypeVarTuple(name) + _set_default(tvt, default) + + tvt.__bound__ = bound + tvt.__covariant__ = bool(covariant) + tvt.__contravariant__ = bool(contravariant) + tvt.__infer_variance__ = bool(infer_variance) + + _set_module(tvt) + + def _typevartuple_prepare_subst(alias, args): + params = alias.__parameters__ + typevartuple_index = params.index(tvt) + for param in params[typevartuple_index + 1:]: + if isinstance(param, TypeVarTuple): + raise TypeError( + f"More than one TypeVarTuple parameter in {alias}" + ) + + alen = len(args) + plen = len(params) + left = typevartuple_index + right = plen - typevartuple_index - 1 + var_tuple_index = None + fillarg = None + for k, arg in enumerate(args): + if not isinstance(arg, type): + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs and len(subargs) == 2 and subargs[-1] is ...: + if var_tuple_index is not None: + raise TypeError( + "More than one unpacked " + "arbitrary-length tuple argument" + ) + var_tuple_index = k + fillarg = subargs[0] + if var_tuple_index is not None: + left = min(left, var_tuple_index) + right = min(right, alen - var_tuple_index - 1) + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen - 1}") + if left == alen - right and tvt.has_default(): + replacement = _unpack_args(tvt.__default__) + else: + replacement = args[left: alen - right] + + return ( + *args[:left], + *([fillarg] * (typevartuple_index - left)), + replacement, + *([fillarg] * (plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) + + tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst + return tvt + + def __init_subclass__(self, *args, **kwds): + raise TypeError("Cannot subclass special typing classes") + +else: # <=3.10 + class TypeVarTuple(_DefaultMixin): + """Type variable tuple. + + Usage:: + + Ts = TypeVarTuple('Ts') + + In the same way that a normal type variable is a stand-in for a single + type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* + type such as ``Tuple[int, str]``. + + Type variable tuples can be used in ``Generic`` declarations. + Consider the following example:: + + class Array(Generic[*Ts]): ... + + The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, + where ``T1`` and ``T2`` are type variables. To use these type variables + as type parameters of ``Array``, we must *unpack* the type variable tuple using + the star operator: ``*Ts``. The signature of ``Array`` then behaves + as if we had simply written ``class Array(Generic[T1, T2]): ...``. + In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows + us to parameterise the class with an *arbitrary* number of type parameters. + + Type variable tuples can be used anywhere a normal ``TypeVar`` can. + This includes class definitions, as shown above, as well as function + signatures and variable annotations:: + + class Array(Generic[*Ts]): + + def __init__(self, shape: Tuple[*Ts]): + self._shape: Tuple[*Ts] = shape + + def get_shape(self) -> Tuple[*Ts]: + return self._shape + + shape = (Height(480), Width(640)) + x: Array[Height, Width] = Array(shape) + y = abs(x) # Inferred type is Array[Height, Width] + z = x + x # ... is Array[Height, Width] + x.get_shape() # ... is tuple[Height, Width] + + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + def __iter__(self): + yield self.__unpacked__ + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + self.__bound__ = bound + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + self.__unpacked__ = Unpack[self] + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(self, *args, **kwds): + if '_root' not in kwds: + raise TypeError("Cannot subclass special typing classes") + + +if hasattr(typing, "reveal_type"): # 3.11+ + reveal_type = typing.reveal_type +else: # <=3.10 + def reveal_type(obj: T, /) -> T: + """Reveal the inferred type of a variable. + + When a static type checker encounters a call to ``reveal_type()``, + it will emit the inferred type of the argument:: + + x: int = 1 + reveal_type(x) + + Running a static type checker (e.g., ``mypy``) on this example + will produce output similar to 'Revealed type is "builtins.int"'. + + At runtime, the function prints the runtime type of the + argument and returns it unchanged. + + """ + print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) + return obj + + +if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ + _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH +else: # <=3.10 + _ASSERT_NEVER_REPR_MAX_LENGTH = 100 + + +if hasattr(typing, "assert_never"): # 3.11+ + assert_never = typing.assert_never +else: # <=3.10 + def assert_never(arg: Never, /) -> Never: + """Assert to the type checker that a line of code is unreachable. + + Example:: + + def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + assert_never(arg) + + If a type checker finds that a call to assert_never() is + reachable, it will emit an error. + + At runtime, this throws an exception when called. + + """ + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' + raise AssertionError(f"Expected code to be unreachable, but got: {value}") + + +# dataclass_transform exists in 3.11 but lacks the frozen_default parameter +# Breakpoint: https://github.com/python/cpython/pull/99958 +if sys.version_info >= (3, 12): # 3.12+ + dataclass_transform = typing.dataclass_transform +else: # <=3.11 + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: typing.Tuple[ + typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], + ... + ] = (), + **kwargs: typing.Any, + ) -> typing.Callable[[T], T]: + """Decorator that marks a function, class, or metaclass as providing + dataclass-like behavior. + + Example: + + from typing_extensions import dataclass_transform + + _T = TypeVar("_T") + + # Used on a decorator function + @dataclass_transform() + def create_model(cls: type[_T]) -> type[_T]: + ... + return cls + + @create_model + class CustomerModel: + id: int + name: str + + # Used on a base class + @dataclass_transform() + class ModelBase: ... + + class CustomerModel(ModelBase): + id: int + name: str + + # Used on a metaclass + @dataclass_transform() + class ModelMeta(type): ... + + class ModelBase(metaclass=ModelMeta): ... + + class CustomerModel(ModelBase): + id: int + name: str + + Each of the ``CustomerModel`` classes defined in this example will now + behave similarly to a dataclass created with the ``@dataclasses.dataclass`` + decorator. For example, the type checker will synthesize an ``__init__`` + method. + + The arguments to this decorator can be used to customize this behavior: + - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be + True or False if it is omitted by the caller. + - ``order_default`` indicates whether the ``order`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``kw_only_default`` indicates whether the ``kw_only`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``frozen_default`` indicates whether the ``frozen`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``field_specifiers`` specifies a static list of supported classes + or functions that describe fields, similar to ``dataclasses.field()``. + + At runtime, this decorator records its arguments in the + ``__dataclass_transform__`` attribute on the decorated object. + + See PEP 681 for details. + + """ + def decorator(cls_or_fn): + cls_or_fn.__dataclass_transform__ = { + "eq_default": eq_default, + "order_default": order_default, + "kw_only_default": kw_only_default, + "frozen_default": frozen_default, + "field_specifiers": field_specifiers, + "kwargs": kwargs, + } + return cls_or_fn + return decorator + + +if hasattr(typing, "override"): # 3.12+ + override = typing.override +else: # <=3.11 + _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) + + def override(arg: _F, /) -> _F: + """Indicate that a method is intended to override a method in a base class. + + Usage: + + class Base: + def method(self) -> None: + pass + + class Child(Base): + @override + def method(self) -> None: + super().method() + + When this decorator is applied to a method, the type checker will + validate that it overrides a method with the same name on a base class. + This helps prevent bugs that may occur when a base class is changed + without an equivalent change to a child class. + + There is no runtime checking of these properties. The decorator + sets the ``__override__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + + See PEP 698 for details. + + """ + try: + arg.__override__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return arg + + +# Python 3.13.8+ and 3.14.1+ contain a fix for the wrapped __init_subclass__ +# Breakpoint: https://github.com/python/cpython/pull/138210 +if ((3, 13, 8) <= sys.version_info < (3, 14)) or sys.version_info >= (3, 14, 1): + deprecated = warnings.deprecated +else: + _T = typing.TypeVar("_T") + + class deprecated: + """Indicate that a class, function or overload is deprecated. + + When this decorator is applied to an object, the type checker + will generate a diagnostic on usage of the deprecated object. + + Usage: + + @deprecated("Use B instead") + class A: + pass + + @deprecated("Use g instead") + def f(): + pass + + @overload + @deprecated("int support is deprecated") + def g(x: int) -> int: ... + @overload + def g(x: str) -> int: ... + + The warning specified by *category* will be emitted at runtime + on use of deprecated objects. For functions, that happens on calls; + for classes, on instantiation and on creation of subclasses. + If the *category* is ``None``, no warning is emitted at runtime. + The *stacklevel* determines where the + warning is emitted. If it is ``1`` (the default), the warning + is emitted at the direct caller of the deprecated object; if it + is higher, it is emitted further up the stack. + Static type checker behavior is not affected by the *category* + and *stacklevel* arguments. + + The deprecation message passed to the decorator is saved in the + ``__deprecated__`` attribute on the decorated object. + If applied to an overload, the decorator + must be after the ``@overload`` decorator for the attribute to + exist on the overload as returned by ``get_overloads()``. + + See PEP 702 for details. + + """ + def __init__( + self, + message: str, + /, + *, + category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, + stacklevel: int = 1, + ) -> None: + if not isinstance(message, str): + raise TypeError( + "Expected an object of type str for 'message', not " + f"{type(message).__name__!r}" + ) + self.message = message + self.category = category + self.stacklevel = stacklevel + + def __call__(self, arg: _T, /) -> _T: + # Make sure the inner functions created below don't + # retain a reference to self. + msg = self.message + category = self.category + stacklevel = self.stacklevel + if category is None: + arg.__deprecated__ = msg + return arg + elif isinstance(arg, type): + import functools + from types import MethodType + + original_new = arg.__new__ + + @functools.wraps(original_new) + def __new__(cls, /, *args, **kwargs): + if cls is arg: + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + if original_new is not object.__new__: + return original_new(cls, *args, **kwargs) + # Mirrors a similar check in object.__new__. + elif cls.__init__ is object.__init__ and (args or kwargs): + raise TypeError(f"{cls.__name__}() takes no arguments") + else: + return original_new(cls) + + arg.__new__ = staticmethod(__new__) + + if "__init_subclass__" in arg.__dict__: + # __init_subclass__ is directly present on the decorated class. + # Synthesize a wrapper that calls this method directly. + original_init_subclass = arg.__init_subclass__ + # We need slightly different behavior if __init_subclass__ + # is a bound method (likely if it was implemented in Python). + # Otherwise, it likely means it's a builtin such as + # object's implementation of __init_subclass__. + if isinstance(original_init_subclass, MethodType): + original_init_subclass = original_init_subclass.__func__ + + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + else: + def __init_subclass__(cls, *args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return super(arg, cls).__init_subclass__(*args, **kwargs) + + arg.__init_subclass__ = classmethod(__init_subclass__) + + arg.__deprecated__ = __new__.__deprecated__ = msg + __init_subclass__.__deprecated__ = msg + return arg + elif callable(arg): + import functools + import inspect + + @functools.wraps(arg) + def wrapper(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return arg(*args, **kwargs) + + if inspect.iscoroutinefunction(arg): + # Breakpoint: https://github.com/python/cpython/pull/99247 + if sys.version_info >= (3, 12): + wrapper = inspect.markcoroutinefunction(wrapper) + else: + import asyncio.coroutines + + wrapper._is_coroutine = asyncio.coroutines._is_coroutine + + arg.__deprecated__ = wrapper.__deprecated__ = msg + return wrapper + else: + raise TypeError( + "@deprecated decorator with non-None category must be applied to " + f"a class or callable, not {arg!r}" + ) + +# Breakpoint: https://github.com/python/cpython/pull/23702 +if sys.version_info < (3, 10): + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias) + ) +else: + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, + ( + tuple, + list, + ParamSpec, + _ConcatenateGenericAlias, + typing._ConcatenateGenericAlias, + ), + ) + + +# We have to do some monkey patching to deal with the dual nature of +# Unpack/TypeVarTuple: +# - We want Unpack to be a kind of TypeVar so it gets accepted in +# Generic[Unpack[Ts]] +# - We want it to *not* be treated as a TypeVar for the purposes of +# counting generic parameters, so that when we subscript a generic, +# the runtime doesn't try to substitute the Unpack with the subscripted type. +if not hasattr(typing, "TypeVarTuple"): + def _check_generic(cls, parameters, elen=_marker): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + # If substituting a single ParamSpec with multiple arguments + # we do not check the count + if (inspect.isclass(cls) and issubclass(cls, typing.Generic) + and len(cls.__parameters__) == 1 + and isinstance(cls.__parameters__[0], ParamSpec) + and parameters + and not _is_param_expr(parameters[0]) + ): + # Generic modifies parameters variable, but here we cannot do this + return + + if not elen: + raise TypeError(f"{cls} is not a generic class") + if elen is _marker: + if not hasattr(cls, "__parameters__") or not cls.__parameters__: + raise TypeError(f"{cls} is not a generic class") + elen = len(cls.__parameters__) + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) + if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): + return + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + # Breakpoint: https://github.com/python/cpython/pull/27515 + things = "arguments" if sys.version_info >= (3, 10) else "parameters" + raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" + f" for {cls}; actual {alen}, expected {expect_val}") +else: + # Python 3.11+ + + def _check_generic(cls, parameters, elen): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" + f" for {cls}; actual {alen}, expected {expect_val}") + +if not _PEP_696_IMPLEMENTED: + typing._check_generic = _check_generic + + +def _has_generic_or_protocol_as_origin() -> bool: + try: + frame = sys._getframe(2) + # - Catch AttributeError: not all Python implementations have sys._getframe() + # - Catch ValueError: maybe we're called from an unexpected module + # and the call stack isn't deep enough + except (AttributeError, ValueError): + return False # err on the side of leniency + else: + # If we somehow get invoked from outside typing.py, + # also err on the side of leniency + if frame.f_globals.get("__name__") != "typing": + return False + origin = frame.f_locals.get("origin") + # Cannot use "in" because origin may be an object with a buggy __eq__ that + # throws an error. + return origin is typing.Generic or origin is Protocol or origin is typing.Protocol + + +_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} + + +def _is_unpacked_typevartuple(x) -> bool: + if get_origin(x) is not Unpack: + return False + args = get_args(x) + return ( + bool(args) + and len(args) == 1 + and type(args[0]) in _TYPEVARTUPLE_TYPES + ) + + +# Python 3.11+ _collect_type_vars was renamed to _collect_parameters +if hasattr(typing, '_collect_type_vars'): + def _collect_type_vars(types, typevar_types=None): + """Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + """ + if typevar_types is None: + typevar_types = typing.TypeVar + tvars = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with a default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in types: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + elif ( + isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias) + and t not in tvars + ): + if enforce_default_ordering: + has_default = getattr(t, '__default__', NoDefault) is not NoDefault + if has_default: + if type_var_tuple_encountered: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + tvars.append(t) + if _should_collect_from_parameters(t): + tvars.extend([t for t in t.__parameters__ if t not in tvars]) + elif isinstance(t, tuple): + # Collect nested type_vars + # tuple wrapped by _prepare_paramspec_params(cls, params) + for x in t: + for collected in _collect_type_vars([x]): + if collected not in tvars: + tvars.append(collected) + return tuple(tvars) + + typing._collect_type_vars = _collect_type_vars +else: + def _collect_parameters(args): + """Collect all type variables and parameter specifications in args + in order of first appearance (lexicographic order). + + For example:: + + assert _collect_parameters((T, Callable[P, T])) == (T, P) + """ + parameters = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in args: + if isinstance(t, type): + # We don't want __parameters__ descriptor of a bare Python class. + pass + elif isinstance(t, tuple): + # `t` might be a tuple, when `ParamSpec` is substituted with + # `[T, int]`, or `[int, *Ts]`, etc. + for x in t: + for collected in _collect_parameters([x]): + if collected not in parameters: + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: + if enforce_default_ordering: + has_default = ( + getattr(t, '__default__', NoDefault) is not NoDefault + ) + + if type_var_tuple_encountered and has_default: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + + if has_default: + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + parameters.append(t) + else: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + + return tuple(parameters) + + if not _PEP_696_IMPLEMENTED: + typing._collect_parameters = _collect_parameters + +# Backport typing.NamedTuple as it exists in Python 3.13. +# In 3.11, the ability to define generic `NamedTuple`s was supported. +# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. +# On 3.12, we added __orig_bases__ to call-based NamedTuples +# On 3.13, we deprecated kwargs-based NamedTuples +# Breakpoint: https://github.com/python/cpython/pull/105609 +if sys.version_info >= (3, 13): + NamedTuple = typing.NamedTuple +else: + def _make_nmtuple(name, types, module, defaults=()): + fields = [n for n, t in types] + annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations + return nm_tpl + + _prohibited_namedtuple_fields = typing._prohibited + _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) + + class _NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not typing.Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + if "__annotations__" in ns: + types = ns["__annotations__"] + elif "__annotate__" in ns: + # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated + types = ns["__annotate__"](1) + else: + types = {} + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple( + typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__'] + ) + nm_tpl.__bases__ = bases + if typing.Generic in bases: + if hasattr(typing, '_generic_class_getitem'): # 3.12+ + nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) + else: + class_getitem = typing.Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key, val in ns.items(): + if key in _prohibited_namedtuple_fields: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special_namedtuple_fields: + if key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + try: + set_name = type(val).__set_name__ + except AttributeError: + pass + else: + try: + set_name(val, nm_tpl, key) + except BaseException as e: + msg = ( + f"Error calling __set_name__ on {type(val).__name__!r} " + f"instance {key!r} in {typename!r}" + ) + # BaseException.add_note() existed on py311, + # but the __set_name__ machinery didn't start + # using add_note() until py312. + # Making sure exceptions are raised in the same way + # as in "normal" classes seems most important here. + # Breakpoint: https://github.com/python/cpython/pull/95915 + if sys.version_info >= (3, 12): + e.add_note(msg) + raise + else: + raise RuntimeError(msg) from e + + if typing.Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) + + def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + + def NamedTuple(typename, fields=_marker, /, **kwargs): + """Typed version of namedtuple. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + An alternative equivalent functional syntax is also accepted:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + """ + if fields is _marker: + if kwargs: + deprecated_thing = "Creating NamedTuple classes using keyword arguments" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "Use the class-based or functional syntax instead." + ) + else: + deprecated_thing = "Failing to pass a value for the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif fields is None: + if kwargs: + raise TypeError( + "Cannot pass `None` as the 'fields' parameter " + "and also specify fields using keyword arguments" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + if fields is _marker or fields is None: + warnings.warn( + deprecation_msg.format(name=deprecated_thing, remove="3.15"), + DeprecationWarning, + stacklevel=2, + ) + fields = kwargs.items() + nt = _make_nmtuple(typename, fields, module=_caller()) + nt.__orig_bases__ = (NamedTuple,) + return nt + + NamedTuple.__mro_entries__ = _namedtuple_mro_entries + + +if hasattr(collections.abc, "Buffer"): + Buffer = collections.abc.Buffer +else: + class Buffer(abc.ABC): # noqa: B024 + """Base class for classes that implement the buffer protocol. + + The buffer protocol allows Python objects to expose a low-level + memory buffer interface. Before Python 3.12, it is not possible + to implement the buffer protocol in pure Python code, or even + to check whether a class implements the buffer protocol. In + Python 3.12 and higher, the ``__buffer__`` method allows access + to the buffer protocol from Python code, and the + ``collections.abc.Buffer`` ABC allows checking whether a class + implements the buffer protocol. + + To indicate support for the buffer protocol in earlier versions, + inherit from this ABC, either in a stub file or at runtime, + or use ABC registration. This ABC provides no methods, because + there is no Python-accessible methods shared by pre-3.12 buffer + classes. It is useful primarily for static checks. + + """ + + # As a courtesy, register the most common stdlib buffer classes. + Buffer.register(memoryview) + Buffer.register(bytearray) + Buffer.register(bytes) + + +# Backport of types.get_original_bases, available on 3.12+ in CPython +if hasattr(_types, "get_original_bases"): + get_original_bases = _types.get_original_bases +else: + def get_original_bases(cls, /): + """Return the class's "original" bases prior to modification by `__mro_entries__`. + + Examples:: + + from typing import TypeVar, Generic + from typing_extensions import NamedTuple, TypedDict + + T = TypeVar("T") + class Foo(Generic[T]): ... + class Bar(Foo[int], float): ... + class Baz(list[str]): ... + Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) + Spam = TypedDict("Spam", {"a": int, "b": str}) + + assert get_original_bases(Bar) == (Foo[int], float) + assert get_original_bases(Baz) == (list[str],) + assert get_original_bases(Eggs) == (NamedTuple,) + assert get_original_bases(Spam) == (TypedDict,) + assert get_original_bases(int) == (object,) + """ + try: + return cls.__dict__.get("__orig_bases__", cls.__bases__) + except AttributeError: + raise TypeError( + f'Expected an instance of type, not {type(cls).__name__!r}' + ) from None + + +# NewType is a class on Python 3.10+, making it pickleable +# The error message for subclassing instances of NewType was improved on 3.11+ +# Breakpoint: https://github.com/python/cpython/pull/30268 +if sys.version_info >= (3, 11): + NewType = typing.NewType +else: + class NewType: + """NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy callable that simply returns its argument. Usage:: + UserId = NewType('UserId', int) + def name_by_id(user_id: UserId) -> str: + ... + UserId('user') # Fails type check + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + num = UserId(5) + 1 # type: int + """ + + def __call__(self, obj, /): + return obj + + def __init__(self, name, tp): + self.__qualname__ = name + if '.' in name: + name = name.rpartition('.')[-1] + self.__name__ = name + self.__supertype__ = tp + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __mro_entries__(self, bases): + # We defined __mro_entries__ to get a better error message + # if a user attempts to subclass a NewType instance. bpo-46170 + supercls_name = self.__name__ + + class Dummy: + def __init_subclass__(cls): + subcls_name = cls.__name__ + raise TypeError( + f"Cannot subclass an instance of NewType. " + f"Perhaps you were looking for: " + f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" + ) + + return (Dummy,) + + def __repr__(self): + return f'{self.__module__}.{self.__qualname__}' + + def __reduce__(self): + return self.__qualname__ + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + # PEP 604 methods + # It doesn't make sense to have these methods on Python <3.10 + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + +# Breakpoint: https://github.com/python/cpython/pull/149172 +if sys.version_info >= (3, 15): + TypeAliasType = typing.TypeAliasType +# <=3.14 +else: + # Breakpoint: https://github.com/python/cpython/pull/103764 + if sys.version_info >= (3, 12): + # 3.12-3.14 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + typing.TypeAliasType, + TypeAliasType, + )) + else: + # <=3.11 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + TypeAliasType, + )) + + if sys.version_info < (3, 10): + # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582, + # so that we emulate the behaviour of `types.GenericAlias` + # on the latest versions of CPython + _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({ + "__class__", + "__bases__", + "__origin__", + "__args__", + "__unpacked__", + "__parameters__", + "__typing_unpacked_tuple_args__", + "__mro_entries__", + "__reduce_ex__", + "__reduce__", + "__copy__", + "__deepcopy__", + }) + + class _TypeAliasGenericAlias(typing._GenericAlias, _root=True): + def __getattr__(self, attr): + if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS: + return object.__getattr__(self, attr) + return getattr(self.__origin__, attr) + + + class TypeAliasType: + """Create named, parameterized type aliases. + + This provides a backport of the new `type` statement in Python 3.12: + + type ListOrSet[T] = list[T] | set[T] + + is equivalent to: + + T = TypeVar("T") + ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) + + The name ListOrSet can then be used as an alias for the type it refers to. + + The type_params argument should contain all the type parameters used + in the value of the type alias. If the alias is not generic, this + argument is omitted. + + Static type checkers should only support type aliases declared using + TypeAliasType that follow these rules: + + - The first argument (the name) must be a string literal. + - The TypeAliasType instance must be immediately assigned to a variable + of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, + as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). + + """ + + def __init__(self, name: str, value, *, type_params=()): + if not isinstance(name, str): + raise TypeError("TypeAliasType name must be a string") + if not isinstance(type_params, tuple): + raise TypeError("type_params must be a tuple") + self.__value__ = value + self.__type_params__ = type_params + + default_value_encountered = False + parameters = [] + for type_param in type_params: + if ( + not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec)) + # <=3.11 + # Unpack Backport passes isinstance(type_param, TypeVar) + or _is_unpack(type_param) + ): + raise TypeError(f"Expected a type param, got {type_param!r}") + has_default = ( + getattr(type_param, '__default__', NoDefault) is not NoDefault + ) + if default_value_encountered and not has_default: + raise TypeError(f"non-default type parameter '{type_param!r}'" + " follows default type parameter") + if has_default: + default_value_encountered = True + if isinstance(type_param, TypeVarTuple): + parameters.extend(type_param) + else: + parameters.append(type_param) + self.__parameters__ = tuple(parameters) + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + # Setting this attribute closes the TypeAliasType from further modification + self.__name__ = name + + def __setattr__(self, name: str, value: object, /) -> None: + if hasattr(self, "__name__") and name != "__module__": + self._raise_attribute_error(name) + super().__setattr__(name, value) + + def __delattr__(self, name: str, /) -> Never: + self._raise_attribute_error(name) + + def _raise_attribute_error(self, name: str) -> Never: + # Match the Python 3.12 error messages exactly + if name == "__name__": + raise AttributeError("readonly attribute") + elif name in {"__value__", "__type_params__", "__parameters__"}: + raise AttributeError( + f"attribute '{name}' of 'typing.TypeAliasType' objects " + "is not writable" + ) + else: + raise AttributeError( + f"'typing.TypeAliasType' object has no attribute '{name}'" + ) + + def __repr__(self) -> str: + return self.__name__ + + if sys.version_info < (3, 11): + def _check_single_param(self, param, recursion=0): + # Allow [], [int], [int, str], [int, ...], [int, T] + if param is ...: + return ... + if param is None: + return None + # Note in <= 3.9 _ConcatenateGenericAlias inherits from list + if isinstance(param, list) and recursion == 0: + return [self._check_single_param(arg, recursion+1) + for arg in param] + return typing._type_check( + param, f'Subscripting {self.__name__} requires a type.' + ) + + def _check_parameters(self, parameters): + if sys.version_info < (3, 11): + return tuple( + self._check_single_param(item) + for item in parameters + ) + return tuple(typing._type_check( + item, f'Subscripting {self.__name__} requires a type.' + ) + for item in parameters + ) + + def __getitem__(self, parameters): + if not self.__type_params__: + raise TypeError("Only generic type aliases are subscriptable") + if not isinstance(parameters, tuple): + parameters = (parameters,) + # Using 3.9 here will create problems with Concatenate + if sys.version_info >= (3, 10): + return _types.GenericAlias(self, parameters) + type_vars = _collect_type_vars(parameters) + parameters = self._check_parameters(parameters) + alias = _TypeAliasGenericAlias(self, parameters) + # alias.__parameters__ is not complete if Concatenate is present + # as it is converted to a list from which no parameters are extracted. + if alias.__parameters__ != type_vars: + alias.__parameters__ = type_vars + return alias + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "type 'typing_extensions.TypeAliasType' is not an acceptable base type" + ) + + # The presence of this method convinces typing._type_check + # that TypeAliasTypes are types. + def __call__(self): + raise TypeError("Type alias is not callable") + + # Breakpoint: https://github.com/python/cpython/pull/21515 + if sys.version_info >= (3, 10): + def __or__(self, right): + # For forward compatibility with 3.12, reject Unions + # that are not accepted by the built-in Union. + if not _is_unionable(right): + return NotImplemented + return typing.Union[self, right] + + def __ror__(self, left): + if not _is_unionable(left): + return NotImplemented + return typing.Union[left, self] + + +if hasattr(typing, "is_protocol"): + is_protocol = typing.is_protocol + get_protocol_members = typing.get_protocol_members +else: + def is_protocol(tp: type, /) -> bool: + """Return True if the given type is a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, is_protocol + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> is_protocol(P) + True + >>> is_protocol(int) + False + """ + return ( + isinstance(tp, type) + and getattr(tp, '_is_protocol', False) + and tp is not Protocol + and tp is not typing.Protocol + ) + + def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: + """Return the set of members defined in a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, get_protocol_members + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> get_protocol_members(P) == frozenset({'a', 'b'}) + True + + Raise a TypeError for arguments that are not Protocols. + """ + if not is_protocol(tp): + raise TypeError(f'{tp!r} is not a Protocol') + if hasattr(tp, '__protocol_attrs__'): + return frozenset(tp.__protocol_attrs__) + return frozenset(_get_protocol_attrs(tp)) + + +if hasattr(typing, "Doc"): + Doc = typing.Doc +else: + class Doc: + """Define the documentation of a type annotation using ``Annotated``, to be + used in class attributes, function and method parameters, return values, + and variables. + + The value should be a positional-only string literal to allow static tools + like editors and documentation generators to use it. + + This complements docstrings. + + The string value passed is available in the attribute ``documentation``. + + Example:: + + >>> from typing_extensions import Annotated, Doc + >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... + """ + def __init__(self, documentation: str, /) -> None: + self.documentation = documentation + + def __repr__(self) -> str: + return f"Doc({self.documentation!r})" + + def __hash__(self) -> int: + return hash(self.documentation) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Doc): + return NotImplemented + return self.documentation == other.documentation + + +_CapsuleType = getattr(_types, "CapsuleType", None) + +if _CapsuleType is None: + try: + import _socket + except ImportError: + pass + else: + _CAPI = getattr(_socket, "CAPI", None) + if _CAPI is not None: + _CapsuleType = type(_CAPI) + +if _CapsuleType is not None: + CapsuleType = _CapsuleType + __all__.append("CapsuleType") + + +if sys.version_info >= (3, 14): + from annotationlib import Format, get_annotations +else: + # Available since Python 3.14.0a3 + # PR: https://github.com/python/cpython/pull/124415 + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + # Available since Python 3.14.0a1 + # PR: https://github.com/python/cpython/pull/119891 + def get_annotations(obj, *, globals=None, locals=None, eval_str=False, + format=Format.VALUE): + """Compute the annotations dict for an object. + + obj may be a callable, class, or module. + Passing in an object of any other type raises TypeError. + + Returns a dict. get_annotations() returns a new dict every time + it's called; calling it twice on the same object will return two + different but equivalent dicts. + + This is a backport of `inspect.get_annotations`, which has been + in the standard library since Python 3.10. See the standard library + documentation for more: + + https://docs.python.org/3/library/inspect.html#inspect.get_annotations + + This backport adds the *format* argument introduced by PEP 649. The + three formats supported are: + * VALUE: the annotations are returned as-is. This is the default and + it is compatible with the behavior on previous Python versions. + * FORWARDREF: return annotations as-is if possible, but replace any + undefined names with ForwardRef objects. The implementation proposed by + PEP 649 relies on language changes that cannot be backported; the + typing-extensions implementation simply returns the same result as VALUE. + * STRING: return annotations as strings, in a format close to the original + source. Again, this behavior cannot be replicated directly in a backport. + As an approximation, typing-extensions retrieves the annotations under + VALUE semantics and then stringifies them. + + The purpose of this backport is to allow users who would like to use + FORWARDREF or STRING semantics once PEP 649 is implemented, but who also + want to support earlier Python versions, to simply write: + + typing_extensions.get_annotations(obj, format=Format.FORWARDREF) + + """ + format = Format(format) + if format is Format.VALUE_WITH_FAKE_GLOBALS: + raise ValueError( + "The VALUE_WITH_FAKE_GLOBALS format is for internal use only" + ) + + if eval_str and format is not Format.VALUE: + raise ValueError("eval_str=True is only supported with format=Format.VALUE") + + if isinstance(obj, type): + # class + obj_dict = getattr(obj, '__dict__', None) + if obj_dict and hasattr(obj_dict, 'get'): + ann = obj_dict.get('__annotations__', None) + if isinstance(ann, _types.GetSetDescriptorType): + ann = None + else: + ann = None + + obj_globals = None + module_name = getattr(obj, '__module__', None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + obj_globals = getattr(module, '__dict__', None) + obj_locals = dict(vars(obj)) + unwrap = obj + elif isinstance(obj, _types.ModuleType): + # module + ann = getattr(obj, '__annotations__', None) + obj_globals = obj.__dict__ + obj_locals = None + unwrap = None + elif callable(obj): + # this includes types.Function, types.BuiltinFunctionType, + # types.BuiltinMethodType, functools.partial, functools.singledispatch, + # "class funclike" from Lib/test/test_inspect... on and on it goes. + ann = getattr(obj, '__annotations__', None) + obj_globals = getattr(obj, '__globals__', None) + obj_locals = None + unwrap = obj + elif hasattr(obj, '__annotations__'): + ann = obj.__annotations__ + obj_globals = obj_locals = unwrap = None + else: + raise TypeError(f"{obj!r} is not a module, class, or callable.") + + if ann is None: + return {} + + if not isinstance(ann, dict): + raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None") + + if not ann: + return {} + + if not eval_str: + if format is Format.STRING: + return { + key: value if isinstance(value, str) else typing._type_repr(value) + for key, value in ann.items() + } + return dict(ann) + + if unwrap is not None: + while True: + if hasattr(unwrap, '__wrapped__'): + unwrap = unwrap.__wrapped__ + continue + if isinstance(unwrap, functools.partial): + unwrap = unwrap.func + continue + break + if hasattr(unwrap, "__globals__"): + obj_globals = unwrap.__globals__ + + if globals is None: + globals = obj_globals + if locals is None: + locals = obj_locals or {} + + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + if type_params := getattr(obj, "__type_params__", ()): + locals = {param.__name__: param for param in type_params} | locals + + return_value = {key: + value if not isinstance(value, str) else eval(value, globals, locals) + for key, value in ann.items() } + return return_value + + +if hasattr(typing, "evaluate_forward_ref"): + evaluate_forward_ref = typing.evaluate_forward_ref +else: + # Implements annotationlib.ForwardRef.evaluate + def _eval_with_owner( + forward_ref, *, owner=None, globals=None, locals=None, type_params=None + ): + if forward_ref.__forward_evaluated__: + return forward_ref.__forward_value__ + if getattr(forward_ref, "__cell__", None) is not None: + try: + value = forward_ref.__cell__.cell_contents + except ValueError: + pass + else: + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + if owner is None: + owner = getattr(forward_ref, "__owner__", None) + + if ( + globals is None + and getattr(forward_ref, "__forward_module__", None) is not None + ): + globals = getattr( + sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None + ) + if globals is None: + globals = getattr(forward_ref, "__globals__", None) + if globals is None: + if isinstance(owner, type): + module_name = getattr(owner, "__module__", None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + globals = getattr(module, "__dict__", None) + elif isinstance(owner, _types.ModuleType): + globals = getattr(owner, "__dict__", None) + elif callable(owner): + globals = getattr(owner, "__globals__", None) + + # If we pass None to eval() below, the globals of this module are used. + if globals is None: + globals = {} + + if locals is None: + locals = {} + if isinstance(owner, type): + locals.update(vars(owner)) + + if type_params is None and owner is not None: + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + type_params = getattr(owner, "__type_params__", None) + + # Type parameters exist in their own scope, which is logically + # between the locals and the globals. We simulate this by adding + # them to the globals. + if type_params is not None: + globals = dict(globals) + for param in type_params: + globals[param.__name__] = param + + arg = forward_ref.__forward_arg__ + if arg.isidentifier() and not keyword.iskeyword(arg): + if arg in locals: + value = locals[arg] + elif arg in globals: + value = globals[arg] + elif hasattr(builtins, arg): + return getattr(builtins, arg) + else: + raise NameError(arg) + else: + code = forward_ref.__forward_code__ + value = eval(code, globals, locals) + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + + def evaluate_forward_ref( + forward_ref, + *, + owner=None, + globals=None, + locals=None, + type_params=None, + format=None, + _recursive_guard=frozenset(), + ): + """Evaluate a forward reference as a type hint. + + This is similar to calling the ForwardRef.evaluate() method, + but unlike that method, evaluate_forward_ref() also: + + * Recursively evaluates forward references nested within the type hint. + * Rejects certain objects that are not valid type hints. + * Replaces type hints that evaluate to None with types.NoneType. + * Supports the *FORWARDREF* and *STRING* formats. + + *forward_ref* must be an instance of ForwardRef. *owner*, if given, + should be the object that holds the annotations that the forward reference + derived from, such as a module, class object, or function. It is used to + infer the namespaces to use for looking up names. *globals* and *locals* + can also be explicitly given to provide the global and local namespaces. + *type_params* is a tuple of type parameters that are in scope when + evaluating the forward reference. This parameter must be provided (though + it may be an empty tuple) if *owner* is not given and the forward reference + does not already have an owner set. *format* specifies the format of the + annotation and is a member of the annotationlib.Format enum. + + """ + if format == Format.STRING: + return forward_ref.__forward_arg__ + if forward_ref.__forward_arg__ in _recursive_guard: + return forward_ref + + # Evaluate the forward reference + try: + value = _eval_with_owner( + forward_ref, + owner=owner, + globals=globals, + locals=locals, + type_params=type_params, + ) + except NameError: + if format == Format.FORWARDREF: + return forward_ref + else: + raise + + if isinstance(value, str): + value = ForwardRef(value) + + # Recursively evaluate the type + if isinstance(value, ForwardRef): + if getattr(value, "__forward_module__", True) is not None: + globals = None + return evaluate_forward_ref( + value, + globals=globals, + locals=locals, + type_params=type_params, owner=owner, + _recursive_guard=_recursive_guard, format=format + ) + if sys.version_info < (3, 12, 5) and type_params: + # Make use of type_params + locals = dict(locals) if locals else {} + for tvar in type_params: + if tvar.__name__ not in locals: # lets not overwrite something present + locals[tvar.__name__] = tvar + if sys.version_info < (3, 12, 5): + return typing._eval_type( + value, + globals, + locals, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + else: + return typing._eval_type( + value, + globals, + locals, + type_params, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + + +if sys.version_info >= (3, 14, 0, "beta"): + type_repr = annotationlib.type_repr +else: + def type_repr(value): + """Convert a Python value to a format suitable for use with the STRING format. + + This is intended as a helper for tools that support the STRING format but do + not have access to the code that originally produced the annotations. It uses + repr() for most objects. + + """ + if isinstance(value, (type, _types.FunctionType, _types.BuiltinFunctionType)): + if value.__module__ == "builtins": + return value.__qualname__ + return f"{value.__module__}.{value.__qualname__}" + if value is ...: + return "..." + return repr(value) + + +# Aliases for items that are in typing in all supported versions. +# We use hasattr() checks so this library will continue to import on +# future versions of Python that may remove these names. +_typing_names = [ + "AbstractSet", + "AnyStr", + "BinaryIO", + "Callable", + "Collection", + "Container", + "Dict", + "FrozenSet", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Optional", + "Pattern", + "Reversible", + "Sequence", + "Set", + "Sized", + "TextIO", + "Tuple", + "Union", + "ValuesView", + "cast", + "no_type_check", + # This is private, but it was defined by typing_extensions for a long time + # and some users rely on it. + "_AnnotatedAlias", +] + +# Breakpoint: https://github.com/python/cpython/pull/133602 +if sys.version_info < (3, 15, 0): + _typing_names.append("no_type_check_decorator") + __all__.append("no_type_check_decorator") + +globals().update( + {name: getattr(typing, name) for name in _typing_names if hasattr(typing, name)} +) +# These are defined unconditionally because they are used in +# typing-extensions itself. +Generic = typing.Generic +ForwardRef = typing.ForwardRef +Annotated = typing.Annotated diff --git a/.cache/uv/sdists-v9/.gitignore b/.cache/uv/sdists-v9/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.cache/uv/simple-v18/pypi/click.rkyv b/.cache/uv/simple-v18/pypi/click.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..ba11bfc49e95f3a58b0434230c369569a694e9dc Binary files /dev/null and b/.cache/uv/simple-v18/pypi/click.rkyv differ diff --git a/.cache/uv/simple-v18/pypi/filelock.rkyv b/.cache/uv/simple-v18/pypi/filelock.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..7fa5bde63a7201316b1e75519532cc32907d1ee8 --- /dev/null +++ b/.cache/uv/simple-v18/pypi/filelock.rkyv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d62206e75fb9d646ad4fef8e3cf227b6eed3000be3e577ccb1589acdb4837d7 +size 107024 diff --git a/.cache/uv/simple-v18/pypi/fsspec.rkyv b/.cache/uv/simple-v18/pypi/fsspec.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..7eb82ba2a68ed0559872ba3a843c43220d4f8b5f Binary files /dev/null and b/.cache/uv/simple-v18/pypi/fsspec.rkyv differ diff --git a/.cache/uv/simple-v18/pypi/httpx.rkyv b/.cache/uv/simple-v18/pypi/httpx.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..7a60af8dbd5ab19e3f17d9d5b98a85065a33031c Binary files /dev/null and b/.cache/uv/simple-v18/pypi/httpx.rkyv differ diff --git a/.cache/uv/simple-v18/pypi/huggingface-hub.rkyv b/.cache/uv/simple-v18/pypi/huggingface-hub.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..5ee10a25e02ecaa92159cec495ea762b92839b4d --- /dev/null +++ b/.cache/uv/simple-v18/pypi/huggingface-hub.rkyv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ab2ff9477b47086ea2722de53169911ae0196ca393bc4156696a86c640eeeee +size 343432 diff --git a/.cache/uv/simple-v18/pypi/pyyaml.rkyv b/.cache/uv/simple-v18/pypi/pyyaml.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..553571f4c418ce1042288fdebccf52ed019cba92 --- /dev/null +++ b/.cache/uv/simple-v18/pypi/pyyaml.rkyv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7033c823b591dcc75775c5ba88f813a73ff5c8fe81695fbb0aa89fa50c591506 +size 322520 diff --git a/.cache/uv/simple-v18/pypi/typing-extensions.rkyv b/.cache/uv/simple-v18/pypi/typing-extensions.rkyv new file mode 100644 index 0000000000000000000000000000000000000000..50e7c703d679811061ce43cbcb826da840b9fb29 Binary files /dev/null and b/.cache/uv/simple-v18/pypi/typing-extensions.rkyv differ diff --git a/.cache/uv/wheels-v5/pypi/typing-extensions/4.16.0-py3-none-any.http b/.cache/uv/wheels-v5/pypi/typing-extensions/4.16.0-py3-none-any.http new file mode 100644 index 0000000000000000000000000000000000000000..6662bbfe3670f0e65967c8f64d2648424c59772a Binary files /dev/null and b/.cache/uv/wheels-v5/pypi/typing-extensions/4.16.0-py3-none-any.http differ diff --git a/.gitattributes b/.gitattributes index f5f4edfcc03cccfb03dd966eab8a70fd9c9ef880..a7f81b51c028d2417310dcb9ed6a0c4cc5d9c3fe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -76,3 +76,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .cache/pip/http-v2/a/b/e/2/c/abe2c30c0d105321771461cb84423576f0ec11c835b815e82e629cf7.body filter=lfs diff=lfs merge=lfs -text .cache/pip/http-v2/a/a/0/d/7/aa0d704d97a2f85d8db67bd1a027229056e18fcc8fef4bddcbbb3312.body filter=lfs diff=lfs merge=lfs -text .cache/pip/http-v2/6/f/8/5/3/6f85318aff6bc08a703c4373e64cad2794f5ca3b63a775113e76c6f8.body filter=lfs diff=lfs merge=lfs -text +runs/_stats/UPerNet_PVTv2_b2__s2_vs_s3_stats.xlsx filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5.body filter=lfs diff=lfs merge=lfs -text +.cache/uv/simple-v18/pypi/filelock.rkyv filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124.body filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875.body filter=lfs diff=lfs merge=lfs -text +.cache/uv/simple-v18/pypi/pyyaml.rkyv filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535.body filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/7/f/f/b/a/7ffbaade46b578649cfc115650c307df3346f8f8e3d20f832aa9ec7b.body filter=lfs diff=lfs merge=lfs -text +.cache/uv/simple-v18/pypi/huggingface-hub.rkyv filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c.body filter=lfs diff=lfs merge=lfs -text +.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4.body filter=lfs diff=lfs merge=lfs -text diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/norm_stats_BUSI_with_classes_stratified_80_10_10_100pct_phase002_repeat01.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/norm_stats_BUSI_with_classes_stratified_80_10_10_100pct_phase002_repeat01.json new file mode 100644 index 0000000000000000000000000000000000000000..7cb00b6f373d63ef37265d6363f0ebdd09f5cb1b --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/norm_stats_BUSI_with_classes_stratified_80_10_10_100pct_phase002_repeat01.json @@ -0,0 +1,525 @@ +{ + "filenames": [ + "BUSI_0193_M.png", + "BUSI_0083_M.png", + "BUSI_0187_M.png", + "BUSI_0074_B.png", + "BUSI_0355_B.png", + "BUSI_0087_M.png", + "BUSI_0143_M.png", + "BUSI_0074_M.png", + "BUSI_0038_B.png", + "BUSI_0189_B.png", + "BUSI_0407_B.png", + "BUSI_0166_M.png", + "BUSI_0433_B.png", + "BUSI_0254_B.png", + "BUSI_0116_B.png", + "BUSI_0139_M.png", + "BUSI_0336_B.png", + "BUSI_0136_M.png", + "BUSI_0201_M.png", + "BUSI_0157_B.png", + "BUSI_0176_M.png", + "BUSI_0011_B.png", + "BUSI_0181_B.png", + "BUSI_0008_B.png", + "BUSI_0101_B.png", + "BUSI_0062_B.png", + "BUSI_0192_M.png", + "BUSI_0299_B.png", + "BUSI_0145_B.png", + "BUSI_0090_B.png", + "BUSI_0100_B.png", + "BUSI_0041_M.png", + "BUSI_0015_B.png", + "BUSI_0341_B.png", + "BUSI_0054_B.png", + "BUSI_0382_B.png", + "BUSI_0003_M.png", + "BUSI_0372_B.png", + "BUSI_0087_B.png", + "BUSI_0114_M.png", + "BUSI_0134_M.png", + "BUSI_0306_B.png", + "BUSI_0163_M.png", + "BUSI_0317_B.png", + "BUSI_0138_B.png", + "BUSI_0156_B.png", + "BUSI_0225_B.png", + "BUSI_0185_B.png", + "BUSI_0283_B.png", + "BUSI_0049_B.png", + "BUSI_0234_B.png", + "BUSI_0113_M.png", + "BUSI_0031_M.png", + "BUSI_0181_M.png", + "BUSI_0069_B.png", + "BUSI_0045_M.png", + "BUSI_0017_B.png", + "BUSI_0383_B.png", + "BUSI_0130_M.png", + "BUSI_0065_M.png", + "BUSI_0156_M.png", + "BUSI_0112_M.png", + "BUSI_0205_B.png", + "BUSI_0168_B.png", + "BUSI_0151_B.png", + "BUSI_0085_M.png", + "BUSI_0287_B.png", + "BUSI_0134_B.png", + "BUSI_0421_B.png", + "BUSI_0216_B.png", + "BUSI_0094_B.png", + "BUSI_0174_B.png", + "BUSI_0077_M.png", + "BUSI_0356_B.png", + "BUSI_0119_B.png", + "BUSI_0202_B.png", + "BUSI_0050_B.png", + "BUSI_0204_B.png", + "BUSI_0288_B.png", + "BUSI_0223_B.png", + "BUSI_0362_B.png", + "BUSI_0098_M.png", + "BUSI_0184_M.png", + "BUSI_0138_M.png", + "BUSI_0103_B.png", + "BUSI_0208_B.png", + "BUSI_0150_B.png", + "BUSI_0131_B.png", + "BUSI_0105_B.png", + "BUSI_0193_B.png", + "BUSI_0024_B.png", + "BUSI_0271_B.png", + "BUSI_0120_B.png", + "BUSI_0079_B.png", + "BUSI_0009_M.png", + "BUSI_0178_M.png", + "BUSI_0004_B.png", + "BUSI_0384_B.png", + "BUSI_0357_B.png", + "BUSI_0035_B.png", + "BUSI_0204_M.png", + "BUSI_0056_B.png", + "BUSI_0257_B.png", + "BUSI_0300_B.png", + "BUSI_0192_B.png", + "BUSI_0252_B.png", + "BUSI_0159_M.png", + "BUSI_0070_M.png", + "BUSI_0227_B.png", + "BUSI_0056_M.png", + "BUSI_0091_B.png", + "BUSI_0251_B.png", + "BUSI_0061_B.png", + "BUSI_0398_B.png", + "BUSI_0047_B.png", + "BUSI_0098_B.png", + "BUSI_0158_B.png", + "BUSI_0291_B.png", + "BUSI_0264_B.png", + "BUSI_0141_B.png", + "BUSI_0360_B.png", + "BUSI_0155_M.png", + "BUSI_0293_B.png", + "BUSI_0354_B.png", + "BUSI_0025_B.png", + "BUSI_0107_B.png", + "BUSI_0352_B.png", + "BUSI_0039_M.png", + "BUSI_0112_B.png", + "BUSI_0095_B.png", + "BUSI_0028_M.png", + "BUSI_0057_M.png", + "BUSI_0236_B.png", + "BUSI_0093_M.png", + "BUSI_0013_M.png", + "BUSI_0337_B.png", + "BUSI_0022_B.png", + "BUSI_0325_B.png", + "BUSI_0023_M.png", + "BUSI_0124_B.png", + "BUSI_0097_M.png", + "BUSI_0015_M.png", + "BUSI_0123_M.png", + "BUSI_0253_B.png", + "BUSI_0032_M.png", + "BUSI_0148_M.png", + "BUSI_0416_B.png", + "BUSI_0198_B.png", + "BUSI_0262_B.png", + "BUSI_0068_M.png", + "BUSI_0026_B.png", + "BUSI_0127_M.png", + "BUSI_0167_B.png", + "BUSI_0405_B.png", + "BUSI_0034_M.png", + "BUSI_0010_B.png", + "BUSI_0027_M.png", + "BUSI_0196_B.png", + "BUSI_0141_M.png", + "BUSI_0048_M.png", + "BUSI_0110_M.png", + "BUSI_0402_B.png", + "BUSI_0386_B.png", + "BUSI_0263_B.png", + "BUSI_0145_M.png", + "BUSI_0019_M.png", + "BUSI_0186_B.png", + "BUSI_0042_M.png", + "BUSI_0152_B.png", + "BUSI_0226_B.png", + "BUSI_0150_M.png", + "BUSI_0002_M.png", + "BUSI_0196_M.png", + "BUSI_0135_B.png", + "BUSI_0371_B.png", + "BUSI_0064_B.png", + "BUSI_0041_B.png", + "BUSI_0249_B.png", + "BUSI_0315_B.png", + "BUSI_0203_B.png", + "BUSI_0051_M.png", + "BUSI_0020_B.png", + "BUSI_0169_M.png", + "BUSI_0363_B.png", + "BUSI_0248_B.png", + "BUSI_0044_M.png", + "BUSI_0137_M.png", + "BUSI_0348_B.png", + "BUSI_0194_B.png", + "BUSI_0370_B.png", + "BUSI_0129_B.png", + "BUSI_0053_B.png", + "BUSI_0347_B.png", + "BUSI_0183_B.png", + "BUSI_0239_B.png", + "BUSI_0095_M.png", + "BUSI_0286_B.png", + "BUSI_0102_M.png", + "BUSI_0182_M.png", + "BUSI_0017_M.png", + "BUSI_0381_B.png", + "BUSI_0012_B.png", + "BUSI_0121_B.png", + "BUSI_0359_B.png", + "BUSI_0379_B.png", + "BUSI_0419_B.png", + "BUSI_0418_B.png", + "BUSI_0055_B.png", + "BUSI_0375_B.png", + "BUSI_0063_B.png", + "BUSI_0339_B.png", + "BUSI_0121_M.png", + "BUSI_0219_B.png", + "BUSI_0073_M.png", + "BUSI_0179_B.png", + "BUSI_0080_B.png", + "BUSI_0160_M.png", + "BUSI_0349_B.png", + "BUSI_0059_B.png", + "BUSI_0028_B.png", + "BUSI_0208_M.png", + "BUSI_0184_B.png", + "BUSI_0200_M.png", + "BUSI_0409_B.png", + "BUSI_0388_B.png", + "BUSI_0165_B.png", + "BUSI_0072_M.png", + "BUSI_0314_B.png", + "BUSI_0327_B.png", + "BUSI_0247_B.png", + "BUSI_0186_M.png", + "BUSI_0133_M.png", + "BUSI_0153_M.png", + "BUSI_0154_M.png", + "BUSI_0116_M.png", + "BUSI_0423_B.png", + "BUSI_0289_B.png", + "BUSI_0149_B.png", + "BUSI_0129_M.png", + "BUSI_0410_B.png", + "BUSI_0205_M.png", + "BUSI_0081_B.png", + "BUSI_0162_M.png", + "BUSI_0313_B.png", + "BUSI_0397_B.png", + "BUSI_0162_B.png", + "BUSI_0099_M.png", + "BUSI_0021_B.png", + "BUSI_0009_B.png", + "BUSI_0342_B.png", + "BUSI_0036_M.png", + "BUSI_0378_B.png", + "BUSI_0256_B.png", + "BUSI_0298_B.png", + "BUSI_0319_B.png", + "BUSI_0202_M.png", + "BUSI_0259_B.png", + "BUSI_0217_B.png", + "BUSI_0086_M.png", + "BUSI_0096_M.png", + "BUSI_0082_B.png", + "BUSI_0103_M.png", + "BUSI_0285_B.png", + "BUSI_0281_B.png", + "BUSI_0242_B.png", + "BUSI_0185_M.png", + "BUSI_0008_M.png", + "BUSI_0309_B.png", + "BUSI_0018_B.png", + "BUSI_0312_B.png", + "BUSI_0228_B.png", + "BUSI_0018_M.png", + "BUSI_0128_B.png", + "BUSI_0261_B.png", + "BUSI_0425_B.png", + "BUSI_0120_M.png", + "BUSI_0173_B.png", + "BUSI_0200_B.png", + "BUSI_0324_B.png", + "BUSI_0210_B.png", + "BUSI_0057_B.png", + "BUSI_0278_B.png", + "BUSI_0115_B.png", + "BUSI_0100_M.png", + "BUSI_0155_B.png", + "BUSI_0212_B.png", + "BUSI_0345_B.png", + "BUSI_0182_B.png", + "BUSI_0346_B.png", + "BUSI_0303_B.png", + "BUSI_0166_B.png", + "BUSI_0064_M.png", + "BUSI_0391_B.png", + "BUSI_0111_B.png", + "BUSI_0422_B.png", + "BUSI_0077_B.png", + "BUSI_0088_B.png", + "BUSI_0040_B.png", + "BUSI_0326_B.png", + "BUSI_0071_B.png", + "BUSI_0110_B.png", + "BUSI_0276_B.png", + "BUSI_0063_M.png", + "BUSI_0117_B.png", + "BUSI_0144_M.png", + "BUSI_0037_B.png", + "BUSI_0133_B.png", + "BUSI_0062_M.png", + "BUSI_0118_B.png", + "BUSI_0221_B.png", + "BUSI_0016_M.png", + "BUSI_0078_B.png", + "BUSI_0068_B.png", + "BUSI_0027_B.png", + "BUSI_0198_M.png", + "BUSI_0206_B.png", + "BUSI_0119_M.png", + "BUSI_0132_B.png", + "BUSI_0048_B.png", + "BUSI_0076_B.png", + "BUSI_0238_B.png", + "BUSI_0302_B.png", + "BUSI_0220_B.png", + "BUSI_0404_B.png", + "BUSI_0245_B.png", + "BUSI_0049_M.png", + "BUSI_0190_M.png", + "BUSI_0094_M.png", + "BUSI_0131_M.png", + "BUSI_0284_B.png", + "BUSI_0108_M.png", + "BUSI_0434_B.png", + "BUSI_0122_B.png", + "BUSI_0126_B.png", + "BUSI_0195_M.png", + "BUSI_0406_B.png", + "BUSI_0340_B.png", + "BUSI_0070_B.png", + "BUSI_0311_B.png", + "BUSI_0060_B.png", + "BUSI_0106_B.png", + "BUSI_0114_B.png", + "BUSI_0329_B.png", + "BUSI_0328_B.png", + "BUSI_0373_B.png", + "BUSI_0358_B.png", + "BUSI_0175_M.png", + "BUSI_0024_M.png", + "BUSI_0258_B.png", + "BUSI_0322_B.png", + "BUSI_0060_M.png", + "BUSI_0065_B.png", + "BUSI_0005_M.png", + "BUSI_0282_B.png", + "BUSI_0241_B.png", + "BUSI_0232_B.png", + "BUSI_0203_M.png", + "BUSI_0146_M.png", + "BUSI_0437_B.png", + "BUSI_0365_B.png", + "BUSI_0066_M.png", + "BUSI_0235_B.png", + "BUSI_0435_B.png", + "BUSI_0412_B.png", + "BUSI_0054_M.png", + "BUSI_0275_B.png", + "BUSI_0420_B.png", + "BUSI_0426_B.png", + "BUSI_0178_B.png", + "BUSI_0069_M.png", + "BUSI_0233_B.png", + "BUSI_0167_M.png", + "BUSI_0273_B.png", + "BUSI_0005_B.png", + "BUSI_0007_B.png", + "BUSI_0390_B.png", + "BUSI_0163_B.png", + "BUSI_0171_B.png", + "BUSI_0392_B.png", + "BUSI_0436_B.png", + "BUSI_0072_B.png", + "BUSI_0333_B.png", + "BUSI_0403_B.png", + "BUSI_0308_B.png", + "BUSI_0318_B.png", + "BUSI_0093_B.png", + "BUSI_0010_M.png", + "BUSI_0037_M.png", + "BUSI_0034_B.png", + "BUSI_0147_B.png", + "BUSI_0125_B.png", + "BUSI_0431_B.png", + "BUSI_0137_B.png", + "BUSI_0218_B.png", + "BUSI_0413_B.png", + "BUSI_0099_B.png", + "BUSI_0043_M.png", + "BUSI_0053_M.png", + "BUSI_0237_B.png", + "BUSI_0209_B.png", + "BUSI_0109_M.png", + "BUSI_0295_B.png", + "BUSI_0213_B.png", + "BUSI_0113_B.png", + "BUSI_0165_M.png", + "BUSI_0417_B.png", + "BUSI_0224_B.png", + "BUSI_0197_B.png", + "BUSI_0368_B.png", + "BUSI_0270_B.png", + "BUSI_0190_B.png", + "BUSI_0128_M.png", + "BUSI_0376_B.png", + "BUSI_0394_B.png", + "BUSI_0210_M.png", + "BUSI_0428_B.png", + "BUSI_0353_B.png", + "BUSI_0006_B.png", + "BUSI_0172_M.png", + "BUSI_0266_B.png", + "BUSI_0029_M.png", + "BUSI_0335_B.png", + "BUSI_0076_M.png", + "BUSI_0151_M.png", + "BUSI_0377_B.png", + "BUSI_0177_B.png", + "BUSI_0012_M.png", + "BUSI_0071_M.png", + "BUSI_0073_B.png", + "BUSI_0079_M.png", + "BUSI_0021_M.png", + "BUSI_0130_B.png", + "BUSI_0189_M.png", + "BUSI_0080_M.png", + "BUSI_0032_B.png", + "BUSI_0135_M.png", + "BUSI_0171_M.png", + "BUSI_0267_B.png", + "BUSI_0351_B.png", + "BUSI_0067_B.png", + "BUSI_0350_B.png", + "BUSI_0144_B.png", + "BUSI_0330_B.png", + "BUSI_0316_B.png", + "BUSI_0366_B.png", + "BUSI_0411_B.png", + "BUSI_0279_B.png", + "BUSI_0022_M.png", + "BUSI_0304_B.png", + "BUSI_0003_B.png", + "BUSI_0194_M.png", + "BUSI_0331_B.png", + "BUSI_0052_B.png", + "BUSI_0215_B.png", + "BUSI_0040_M.png", + "BUSI_0269_B.png", + "BUSI_0092_B.png", + "BUSI_0430_B.png", + "BUSI_0115_M.png", + "BUSI_0424_B.png", + "BUSI_0097_B.png", + "BUSI_0047_M.png", + "BUSI_0179_M.png", + "BUSI_0301_B.png", + "BUSI_0052_M.png", + "BUSI_0310_B.png", + "BUSI_0088_M.png", + "BUSI_0199_M.png", + "BUSI_0146_B.png", + "BUSI_0323_B.png", + "BUSI_0191_B.png", + "BUSI_0149_M.png", + "BUSI_0104_B.png", + "BUSI_0158_M.png", + "BUSI_0176_B.png", + "BUSI_0240_B.png", + "BUSI_0091_M.png", + "BUSI_0414_B.png", + "BUSI_0026_M.png", + "BUSI_0152_M.png", + "BUSI_0106_M.png", + "BUSI_0108_B.png", + "BUSI_0432_B.png", + "BUSI_0014_M.png", + "BUSI_0214_B.png", + "BUSI_0199_B.png", + "BUSI_0332_B.png", + "BUSI_0104_M.png", + "BUSI_0043_B.png", + "BUSI_0038_M.png", + "BUSI_0016_B.png", + "BUSI_0075_M.png", + "BUSI_0107_M.png", + "BUSI_0006_M.png", + "BUSI_0036_B.png", + "BUSI_0164_M.png", + "BUSI_0408_B.png", + "BUSI_0307_B.png", + "BUSI_0211_B.png", + "BUSI_0173_M.png", + "BUSI_0109_B.png", + "BUSI_0019_B.png", + "BUSI_0111_M.png", + "BUSI_0023_B.png", + "BUSI_0191_M.png", + "BUSI_0338_B.png", + "BUSI_0011_M.png", + "BUSI_0081_M.png", + "BUSI_0089_B.png", + "BUSI_0401_B.png", + "BUSI_0046_B.png", + "BUSI_0082_M.png", + "BUSI_0183_M.png", + "BUSI_0187_B.png", + "BUSI_0030_M.png", + "BUSI_0244_B.png", + "BUSI_0089_M.png" + ], + "global_mean": 83.4100715893549, + "global_std": 56.74386539563672, + "num_images": 517, + "total_pixels": 477590838 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation.json new file mode 100644 index 0000000000000000000000000000000000000000..e6d8a64d42a85197053ed85bb5fd754769cf16ab --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation.json @@ -0,0 +1,836 @@ +{ + "best_metric_name": "val_iou", + "best_metric_value": 0.7069892349333782, + "checkpoint_mode": "best", + "checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt", + "metrics": { + "biou": { + "mean": 0.3781984746456146, + "std": 0.2127406746149063 + }, + "biou_contour": { + "mean": 0.10553458333015442, + "std": 0.07625986635684967 + }, + "dice": { + "mean": 0.7896647453308105, + "std": 0.2421818971633911 + }, + "hd95": { + "mean": 15.18199348449707, + "std": 27.79026985168457 + }, + "iou": { + "mean": 0.7016277313232422, + "std": 0.2495580017566681 + }, + "ppv": { + "mean": 0.824587881565094, + "std": 0.23476456105709076 + }, + "sen": { + "mean": 0.8144153952598572, + "std": 0.24154168367385864 + } + }, + "per_sample": [ + { + "biou": 0.04923723653001134, + "biou_contour": 0.010283030775570495, + "dice": 0.225750588542861, + "hd95": 63.78871536254883, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.12723724166551836, + "ppv": 0.1314065009005797, + "sample_id": "BUSI_0195_B", + "sen": 0.800409437010293 + }, + { + "biou": 0.24932742158498458, + "biou_contour": 0.04249318909541386, + "dice": 0.9100118198546038, + "hd95": 5.879896640777588, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8348822851647372, + "ppv": 0.9882654936462966, + "sample_id": "BUSI_0122_M", + "sen": 0.8432415568447573 + }, + { + "biou": 0.32666278242126057, + "biou_contour": 0.06261527391983907, + "dice": 0.957835370230728, + "hd95": 4.123105525970459, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9190825934920424, + "ppv": 0.9470260230081515, + "sample_id": "BUSI_0188_B", + "sen": 0.9688943226175724 + }, + { + "biou": 0.38247876442761447, + "biou_contour": 0.141936037460621, + "dice": 0.8843813465597467, + "hd95": 4.123105525970459, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7927272978512366, + "ppv": 0.9969512199769481, + "sample_id": "BUSI_0125_M", + "sen": 0.7946537309047714 + }, + { + "biou": 0.18864788169484448, + "biou_contour": 0.031414119678471374, + "dice": 0.7271581772427109, + "hd95": 13.913954734802246, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.571287171159686, + "ppv": 0.9948275870986919, + "sample_id": "BUSI_0092_M", + "sen": 0.572989118869005 + }, + { + "biou": 0.4472364586751464, + "biou_contour": 0.17500103124871094, + "dice": 0.6625001054687171, + "hd95": 43.06497573852539, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.4953273386320848, + "ppv": 0.538071300471421, + "sample_id": "BUSI_0083_B", + "sen": 0.8617887302530648 + }, + { + "biou": 0.489071177849405, + "biou_contour": 0.11029477184207952, + "dice": 0.8938967235777724, + "hd95": 3.1622776985168457, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8081494383447473, + "ppv": 1.0, + "sample_id": "BUSI_0075_B", + "sen": 0.8081494383447473 + }, + { + "biou": 0.5176056904218673, + "biou_contour": 0.20212794250782185, + "dice": 0.9497498379432273, + "hd95": 3.605551242828369, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9043082061181357, + "ppv": 0.9629466271307178, + "sample_id": "BUSI_0274_B", + "sen": 0.9369098739523659 + }, + { + "biou": 0.6413795576692706, + "biou_contour": 0.1746044847547861, + "dice": 0.865051949809014, + "hd95": 2.2360680103302, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7621952669541056, + "ppv": 0.8223685379154356, + "sample_id": "BUSI_0159_B", + "sen": 0.9124088230592532 + }, + { + "biou": 0.29670338257589957, + "biou_contour": 0.08396981527869647, + "dice": 0.8764367851598625, + "hd95": 7.211102485656738, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7800511621457206, + "ppv": 0.9813384825393512, + "sample_id": "BUSI_0078_M", + "sen": 0.7917964801767144 + }, + { + "biou": 0.6383562634640375, + "biou_contour": 0.2164184952100782, + "dice": 0.9364945015669347, + "hd95": 2.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8805732674246389, + "ppv": 0.92166667972222, + "sample_id": "BUSI_0002_B", + "sen": 0.9518072372104583 + }, + { + "biou": 0.17157590783682564, + "biou_contour": 0.04556986188104763, + "dice": 0.8383825271306393, + "hd95": 15.09261703491211, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7217371900215539, + "ppv": 0.9277697862512292, + "sample_id": "BUSI_0393_B", + "sen": 0.764705887933921 + }, + { + "biou": 0.233229388983667, + "biou_contour": 0.06443323081617763, + "dice": 0.8994966731693997, + "hd95": 6.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8173502562009367, + "ppv": 0.9181305960182102, + "sample_id": "BUSI_0168_M", + "sen": 0.8816040776064902 + }, + { + "biou": 0.4587040077885632, + "biou_contour": 0.10219010868974136, + "dice": 0.9497498379432273, + "hd95": 3.605551242828369, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9043082061181357, + "ppv": 0.9337040233659528, + "sample_id": "BUSI_0096_B", + "sen": 0.9663567965313503 + }, + { + "biou": 0.2594491185490635, + "biou_contour": 0.04858318854591325, + "dice": 0.9089983465826862, + "hd95": 6.119029998779297, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8331777920397155, + "ppv": 0.8874254501136817, + "sample_id": "BUSI_0059_M", + "sen": 0.9316462318902626 + }, + { + "biou": 0.4522822713107321, + "biou_contour": 0.13068231211232265, + "dice": 0.8992661841717022, + "hd95": 3.2066009044647217, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8169697191551856, + "ppv": 0.9374130824182083, + "sample_id": "BUSI_0055_M", + "sen": 0.86410258152531 + }, + { + "biou": 0.242905874812046, + "biou_contour": 0.062271405761389835, + "dice": 0.8811771271189026, + "hd95": 6.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7875930626504684, + "ppv": 0.9318849129838571, + "sample_id": "BUSI_0118_M", + "sen": 0.8357030102315424 + }, + { + "biou": 0.19409944145190672, + "biou_contour": 0.058201307354151494, + "dice": 0.8164251235443067, + "hd95": 18.879810333251953, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.6897959262807162, + "ppv": 0.6954732588612845, + "sample_id": "BUSI_0124_M", + "sen": 0.9883040939947334 + }, + { + "biou": 0.43869225103753384, + "biou_contour": 0.08088302876247885, + "dice": 0.8773679085375964, + "hd95": 3.4725677967071533, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7815275698885311, + "ppv": 0.7913669439987511, + "sample_id": "BUSI_0389_B", + "sen": 0.9843400482460742 + }, + { + "biou": 0.7613637267561641, + "biou_contour": 0.29411833909966756, + "dice": 0.9533169590519707, + "hd95": 1.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9107981430051307, + "ppv": 0.9724310846037382, + "sample_id": "BUSI_0180_B", + "sen": 0.9349397747133072 + }, + { + "biou": 0.5953609290306885, + "biou_contour": 0.13422876897398056, + "dice": 0.9346356172324856, + "hd95": 2.2360680103302, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8772919778149537, + "ppv": 0.9027576338523028, + "sample_id": "BUSI_0139_B", + "sen": 0.9688473568773588 + }, + { + "biou": 0.5147061202420979, + "biou_contour": 0.06818287706491243, + "dice": 0.855813987020003, + "hd95": 2.2360680103302, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7479675821269991, + "ppv": 0.7863248776389412, + "sample_id": "BUSI_0161_B", + "sen": 0.9387755414410502 + }, + { + "biou": 0.407692763313259, + "biou_contour": 0.01470733131274807, + "dice": 0.6424872318719006, + "hd95": 10.541412353515625, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.47328284482225585, + "ppv": 0.7045457902888747, + "sample_id": "BUSI_0153_B", + "sen": 0.5904765804984948 + }, + { + "biou": 0.6614700085812898, + "biou_contour": 0.2625004609372119, + "dice": 0.9523809549873588, + "hd95": 2.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9090909185902907, + "ppv": 0.9797297320124175, + "sample_id": "BUSI_0229_B", + "sen": 0.9265175797105879 + }, + { + "biou": 0.6705883644751512, + "biou_contour": 0.20792157631527097, + "dice": 0.9262295182746559, + "hd95": 2.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8625954548103169, + "ppv": 0.9390581886265406, + "sample_id": "BUSI_0039_B", + "sen": 0.9137466539766431 + }, + { + "biou": 0.24709306702947284, + "biou_contour": 0.061776242900339215, + "dice": 0.9228944252118175, + "hd95": 11.180339813232422, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8568281956876368, + "ppv": 0.9792684735781361, + "sample_id": "BUSI_0415_B", + "sen": 0.8726576950031975 + }, + { + "biou": 0.5664234209600845, + "biou_contour": 0.11904796863175848, + "dice": 0.9449196050318301, + "hd95": 2.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8955901494429216, + "ppv": 0.976661953559975, + "sample_id": "BUSI_0268_B", + "sen": 0.9151756186099657 + }, + { + "biou": 0.6953317701887543, + "biou_contour": 0.243421550380559, + "dice": 0.9564676643987771, + "hd95": 1.4142135381698608, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9165673520181941, + "ppv": 0.9447174515089126, + "sample_id": "BUSI_0102_B", + "sen": 0.9685138578697912 + }, + { + "biou": 0.7335641060331813, + "biou_contour": 0.2636370330572427, + "dice": 0.9492671985042618, + "hd95": 1.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9034334971172753, + "ppv": 0.9232456308671863, + "sample_id": "BUSI_0320_B", + "sen": 0.9767981492347682 + }, + { + "biou": 0.14764673451665156, + "biou_contour": 0.06666688122600432, + "dice": 0.8278999263596168, + "hd95": 16.671924591064453, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7063389455295613, + "ppv": 0.7074066139622843, + "sample_id": "BUSI_0058_M", + "sen": 0.9978678039028996 + }, + { + "biou": 0.0824428881766583, + "biou_contour": 0.02645554155791452, + "dice": 0.3209877067139115, + "hd95": 29.528459548950195, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.1911765449286264, + "ppv": 0.873949632794272, + "sample_id": "BUSI_0272_B", + "sen": 0.1965974294331352 + }, + { + "biou": 0.2343751993814585, + "biou_contour": 0.05343583707188009, + "dice": 0.6747868849224257, + "hd95": 10.865039825439453, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.5091912666927818, + "ppv": 0.9295302249898574, + "sample_id": "BUSI_0061_M", + "sen": 0.5296368012166728 + }, + { + "biou": 0.651761564801956, + "biou_contour": 0.2460940444945139, + "dice": 0.9692893976846134, + "hd95": 3.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9404088760152729, + "ppv": 0.9638876520781252, + "sample_id": "BUSI_0013_B", + "sen": 0.9747520299931456 + }, + { + "biou": 0.35979521641546525, + "biou_contour": 0.15163969195094593, + "dice": 0.9066749101769187, + "hd95": 5.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8292820899218717, + "ppv": 0.9952510179612607, + "sample_id": "BUSI_0180_M", + "sen": 0.8325766269820303 + }, + { + "biou": 0.43517481001411384, + "biou_contour": 0.08469085189223066, + "dice": 0.9304306689439028, + "hd95": 4.334437370300293, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8699115101809065, + "ppv": 0.9529810977711537, + "sample_id": "BUSI_0296_B", + "sen": 0.908922796628627 + }, + { + "biou": 0.5772361160681984, + "biou_contour": 0.1428586734666545, + "dice": 0.8075118274592359, + "hd95": 2.8284270763397217, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.6771656085310169, + "ppv": 0.6935486342349724, + "sample_id": "BUSI_0169_B", + "sen": 0.9662921727054239 + }, + { + "biou": 0.13274343260310278, + "biou_contour": 0.06376838731351092, + "dice": 0.6702619477992692, + "hd95": 29.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.5040556342973455, + "ppv": 0.5074365847933338, + "sample_id": "BUSI_0085_B", + "sen": 0.9869540563270529 + }, + { + "biou": 0.7237443553095079, + "biou_contour": 0.2625004609372119, + "dice": 0.9648293981716851, + "hd95": 1.4142135381698608, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9320486884331959, + "ppv": 0.9818376087780333, + "sample_id": "BUSI_0033_B", + "sen": 0.9484004181217319 + }, + { + "biou": 0.7297299123446538, + "biou_contour": 0.25396943814374895, + "dice": 0.910828053876416, + "hd95": 1.0414206981658936, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8362574056974236, + "ppv": 0.8881988272056974, + "sample_id": "BUSI_0051_B", + "sen": 0.9346405655944016 + }, + { + "biou": 0.2794118971669307, + "biou_contour": 0.06818234762366612, + "dice": 0.8325550478615712, + "hd95": 7.046193599700928, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7131428899265269, + "ppv": 0.7402135539485701, + "sample_id": "BUSI_0292_B", + "sen": 0.9512195196311708 + }, + { + "biou": 0.3769970041543118, + "biou_contour": 0.11926686305792379, + "dice": 0.8033708141333126, + "hd95": 6.382966995239258, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.6713615794925869, + "ppv": 0.9022082327418824, + "sample_id": "BUSI_0172_B", + "sen": 0.7240507027719739 + }, + { + "biou": 0.5833334122474598, + "biou_contour": 0.16230410350570496, + "dice": 0.9453432468148996, + "hd95": 2.2360680103302, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.8963515840504491, + "ppv": 0.9765131005859891, + "sample_id": "BUSI_0387_B", + "sen": 0.9161017020252795 + }, + { + "biou": 0.5280001887999245, + "biou_contour": 0.1720439010280634, + "dice": 0.881469134980111, + "hd95": 2.591482639312744, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7880597647582792, + "ppv": 0.7904192244253819, + "sample_id": "BUSI_0127_B", + "sen": 0.9962264165183334 + }, + { + "biou": 0.12990460604959672, + "biou_contour": 0.03171659856033609, + "dice": 0.780197114597787, + "hd95": 15.185378074645996, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.6396091762568739, + "ppv": 0.9338820319922625, + "sample_id": "BUSI_0025_M", + "sen": 0.6699468673499928 + }, + { + "biou": 0.37455208341360513, + "biou_contour": 0.1141309162331977, + "dice": 0.9018645779261738, + "hd95": 5.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.82126900614218, + "ppv": 0.9892357385106848, + "sample_id": "BUSI_0265_B", + "sen": 0.828674496963526 + }, + { + "biou": 0.47091937421019003, + "biou_contour": 0.1029812729048041, + "dice": 0.9535759103893364, + "hd95": 3.0, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.9112709858731719, + "ppv": 0.9517845976272825, + "sample_id": "BUSI_0140_B", + "sen": 0.9553739800322445 + }, + { + "biou": 9.643200612998977e-08, + "biou_contour": 3.636362314050068e-07, + "dice": 3.112355956664925e-08, + "hd95": 76.56410217285156, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 3.112355956664925e-08, + "ppv": 3.466204385920125e-08, + "sample_id": "BUSI_0157_M", + "sen": 3.0487795582989155e-07 + }, + { + "biou": 0.2571959835472624, + "biou_contour": 0.07374658591546139, + "dice": 0.8294036108348513, + "hd95": 41.387638092041016, + "inference_time_ms": 1.2497724189112585, + "inference_time_seconds": 0.0012497724189112585, + "iou": 0.7085308195009089, + "ppv": 0.87992937728491, + "sample_id": "BUSI_0140_M", + "sen": 0.7843651739577558 + }, + { + "biou": 0.30673771157132773, + "biou_contour": 0.04736892243740924, + "dice": 0.8694638770708696, + "hd95": 3.605551242828369, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.7690721887554445, + "ppv": 0.8644264351765428, + "sample_id": "BUSI_0364_B", + "sen": 0.8745603898522404 + }, + { + "biou": 0.4871795883274974, + "biou_contour": 0.07407456398171218, + "dice": 0.9139847914578823, + "hd95": 2.8284270763397217, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.841594844655728, + "ppv": 0.8425027138616275, + "sample_id": "BUSI_0170_B", + "sen": 0.9987212277850093 + }, + { + "biou": 0.5648537385549212, + "biou_contour": 0.13829878904384144, + "dice": 0.8938356346171858, + "hd95": 2.0, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.8080495950310851, + "ppv": 0.8474026469471926, + "sample_id": "BUSI_0380_B", + "sen": 0.9456521936042777 + }, + { + "biou": 1.1848339828395756e-07, + "biou_contour": 4.424776803196105e-07, + "dice": 4.935833912347783e-08, + "hd95": 77.34329223632812, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 4.935833912347783e-08, + "ppv": 3.3112571817029206e-07, + "sample_id": "BUSI_0243_B", + "sen": 5.8004637006691596e-08 + }, + { + "biou": 0.04404169843479316, + "biou_contour": 8.547001241879281e-07, + "dice": 0.24128696497493768, + "hd95": 22.829803466796875, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.13719525347633332, + "ppv": 0.13719525347633332, + "sample_id": "BUSI_0374_B", + "sen": 1.0 + }, + { + "biou": 0.06349222866098261, + "biou_contour": 0.012346288675130448, + "dice": 0.45386538205607796, + "hd95": 17.891170501708984, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.29354846305930504, + "ppv": 0.3734610980217376, + "sample_id": "BUSI_0427_B", + "sen": 0.5783899198326441 + }, + { + "biou": 0.2691846960920446, + "biou_contour": 0.07465637040149894, + "dice": 0.9087698655211902, + "hd95": 10.29563045501709, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.8327939620137728, + "ppv": 0.9321795143453508, + "sample_id": "BUSI_0170_M", + "sen": 0.8865071792056042 + }, + { + "biou": 0.2987748069015262, + "biou_contour": 0.07988192902901509, + "dice": 0.8687704054674558, + "hd95": 9.848857879638672, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.7679876964991267, + "ppv": 0.8247933956696943, + "sample_id": "BUSI_0188_M", + "sen": 0.9177011532091423 + }, + { + "biou": 0.33100248694580725, + "biou_contour": 0.0961544255420349, + "dice": 0.77837840233747, + "hd95": 78.80036163330078, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.637168205810937, + "ppv": 0.77087799338801, + "sample_id": "BUSI_0105_M", + "sen": 0.7860262475925224 + }, + { + "biou": 0.1579963086712315, + "biou_contour": 0.060976182331596136, + "dice": 0.5438766110051484, + "hd95": 10.913829803466797, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.37351001675364015, + "ppv": 0.9894736879039692, + "sample_id": "BUSI_0147_M", + "sen": 0.37500008311169103 + }, + { + "biou": 0.2969121975163661, + "biou_contour": 0.06181852297508256, + "dice": 0.8866963753438455, + "hd95": 5.0, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.7964551288476198, + "ppv": 0.9182597285260561, + "sample_id": "BUSI_0084_M", + "sen": 0.8572307780165676 + }, + { + "biou": 0.0372295205861887, + "biou_contour": 0.009554455555905875, + "dice": 0.40650872376509495, + "hd95": 40.03989791870117, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.25510572357199124, + "ppv": 0.4830393837829455, + "sample_id": "BUSI_0207_B", + "sen": 0.3509118111921236 + }, + { + "biou": 0.669014317595551, + "biou_contour": 0.1384628639032863, + "dice": 0.8865979771140972, + "hd95": 1.4142135381698608, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.7962964220392457, + "ppv": 0.8113208733830986, + "sample_id": "BUSI_0154_B", + "sen": 0.9772727444903451 + }, + { + "biou": 3.0769221301778066e-07, + "biou_contour": 1.0638286555014303e-06, + "dice": 2.525251887562655e-07, + "hd95": 181.01933598375618, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 2.525251887562655e-07, + "ppv": 1.0, + "sample_id": "BUSI_0201_B", + "sen": 2.525251887562655e-07 + }, + { + "biou": 0.40995274645669516, + "biou_contour": 0.0723690313361636, + "dice": 0.8853755031323713, + "hd95": 2.8284270763397217, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.7943262703083305, + "ppv": 0.8151383092957337, + "sample_id": "BUSI_0222_B", + "sen": 0.9688581368757548 + }, + { + "biou": 0.3736585976918441, + "biou_contour": 0.08381529369500183, + "dice": 0.9323688981488445, + "hd95": 4.0, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.8733062373541247, + "ppv": 0.9677177189295151, + "sample_id": "BUSI_0035_M", + "sen": 0.8995115178118801 + }, + { + "biou": 0.6666667336010575, + "biou_contour": 0.2000004324321987, + "dice": 0.9486033548266283, + "hd95": 2.0, + "inference_time_ms": 1.4802593299571205, + "inference_time_seconds": 0.0014802593299571205, + "iou": 0.9022316788276643, + "ppv": 0.945434304517338, + "sample_id": "BUSI_0231_B", + "sen": 0.9517937273773848 + } + ], + "strategy": 2, + "timing": { + "avg_batch_inference_ms": 42.576742358505726, + "avg_sample_inference_ms": 1.3100536110309455, + "device": "cuda", + "mean_per_image_inference_ms": 1.3100536110309455, + "mean_per_image_inference_seconds": 0.0013100536110309455, + "num_batches": 2, + "num_samples": 65, + "scope": "test_set_evaluation", + "std_batch_inference_ms": 17.412333749234676, + "std_per_image_inference_ms": 0.1012926633199967, + "std_per_image_inference_seconds": 0.0001012926633199967, + "std_sample_inference_ms": 0.1012926633199967, + "strategy": 2, + "tmax": 5, + "total_inference_ms": 85.15348471701145 + } +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_results.xlsx b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_results.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4c4264cc14c1d071a391421ee8e3adfffe0943d7 Binary files /dev/null and b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_results.xlsx differ diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_summary.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..43a29578b7d40a7e722a82275aeefef31a19c3de --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/evaluation_summary.json @@ -0,0 +1,4 @@ +{ + "mean_dice": 0.7896647453308105, + "mean_iou": 0.7016277313232422 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/history.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/history.json new file mode 100644 index 0000000000000000000000000000000000000000..56c79d9d0bc9ec450af4872bc63c27cc4803bc6f --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/history.json @@ -0,0 +1,6502 @@ +[ + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.13466455481516626, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.13466455481516626, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00015788861866259895, + "epoch": 1, + "epoch_seconds": 250.1944412351586, + "grad_norm": 3.210658138448542, + "lr": 7.242689438865582e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.13466455481516626, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.751746345650066, + "train_critic_loss": 0.0, + "train_dice": 0.2528901415588274, + "train_dice_loss": 0.7503458153117787, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.1604685012645661, + "train_loss": 0.7510460777716204, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.00719953553822787, + "val_biou_gain": null, + "val_ce_loss": 1.0720584392547607, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.21929791731616624, + "val_dice_gain": null, + "val_dice_loss": 0.7774865925312042, + "val_entropy": 0.0, + "val_iou": 0.13466455481516626, + "val_iou_gain": null, + "val_loss": 0.9247725009918213, + "val_refine_score": 0.07093204517669706, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.3099447975787921, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.3099447975787921, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.0001577725056209501, + "epoch": 2, + "epoch_seconds": 1.0624393951147795, + "grad_norm": 2.0943712212822656, + "lr": 7.237403144656545e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.3099447975787921, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.6081817746162415, + "train_critic_loss": 0.0, + "train_dice": 0.3425429364497004, + "train_dice_loss": 0.6816487203944813, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.2290214782009683, + "train_loss": 0.6449152447960593, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.045320530069359155, + "val_biou_gain": null, + "val_ce_loss": 0.3942171484231949, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.43817478691946427, + "val_dice_gain": null, + "val_dice_loss": 0.6597289144992828, + "val_entropy": 0.0, + "val_iou": 0.3099447975787921, + "val_iou_gain": null, + "val_loss": 0.5269730389118195, + "val_refine_score": 0.17763266382407564, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.3099447975787921, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.27497210039828834, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00015757911121078467, + "epoch": 3, + "epoch_seconds": 1.0914078797213733, + "grad_norm": 2.033475333994085, + "lr": 7.228598451092412e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.27497210039828834, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.3723694086074829, + "train_critic_loss": 0.0, + "train_dice": 0.5258635416808444, + "train_dice_loss": 0.5770275646989996, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.40328850034116576, + "train_loss": 0.4746984974904494, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.02138627494529684, + "val_biou_gain": null, + "val_ce_loss": 1.008586823940277, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.400523495932038, + "val_dice_gain": null, + "val_dice_loss": 0.6721342504024506, + "val_entropy": 0.0, + "val_iou": 0.27497210039828834, + "val_iou_gain": null, + "val_loss": 0.8403605222702026, + "val_refine_score": 0.14817918767179258, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.3993584507252448, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.3993584507252448, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.0001573086262890367, + "epoch": 4, + "epoch_seconds": 0.973518384154886, + "grad_norm": 1.9122894352132624, + "lr": 7.216284047342728e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.3993584507252448, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.2648327106779272, + "train_critic_loss": 0.0, + "train_dice": 0.5739747661836553, + "train_dice_loss": 0.45042526721954346, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.4649284779941356, + "train_loss": 0.35762899030338635, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.09283810717701597, + "val_biou_gain": null, + "val_ce_loss": 1.1454928517341614, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.5222940870668166, + "val_dice_gain": null, + "val_dice_loss": 0.5541152656078339, + "val_entropy": 0.0, + "val_iou": 0.3993584507252448, + "val_iou_gain": null, + "val_loss": 0.8498040437698364, + "val_refine_score": 0.24609827895113037, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.4087222887059817, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.4087222887059817, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.0001569613177916679, + "epoch": 5, + "epoch_seconds": 0.8831896372139454, + "grad_norm": 2.227979053150524, + "lr": 7.200472086237256e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.4087222887059817, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.223572162064639, + "train_critic_loss": 0.0, + "train_dice": 0.6093115483734363, + "train_dice_loss": 0.410793201489882, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.4965168155139492, + "train_loss": 0.3171826817772605, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.06427070579720424, + "val_biou_gain": null, + "val_ce_loss": 0.5344916880130768, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.540683624205681, + "val_dice_gain": null, + "val_dice_loss": 0.5062533318996429, + "val_entropy": 0.0, + "val_iou": 0.4087222887059817, + "val_iou_gain": null, + "val_loss": 0.5203725099563599, + "val_refine_score": 0.23649649725159297, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5521352079738294, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5521352079738294, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00015653752847023415, + "epoch": 6, + "epoch_seconds": 0.9262108271941543, + "grad_norm": 1.3585128675807605, + "lr": 7.181178172272607e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5521352079738294, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.19679883799769662, + "train_critic_loss": 0.0, + "train_dice": 0.6289052828402508, + "train_dice_loss": 0.3832688710906289, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5201792591428744, + "train_loss": 0.29003386064009234, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.21463332776205943, + "val_biou_gain": null, + "val_ce_loss": 0.15963375568389893, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6705116543745268, + "val_dice_gain": null, + "val_dice_loss": 0.3930521011352539, + "val_entropy": 0.0, + "val_iou": 0.5521352079738294, + "val_iou_gain": null, + "val_loss": 0.2763429209589958, + "val_refine_score": 0.38338426786794444, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5521352079738294, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.44738132611973674, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00015603767655363095, + "epoch": 7, + "epoch_seconds": 0.9233642346225679, + "grad_norm": 1.340160239826549, + "lr": 7.158421346212479e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.44738132611973674, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.17188928073102777, + "train_critic_loss": 0.0, + "train_dice": 0.6648933381525143, + "train_dice_loss": 0.3455344655297019, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5552009418135897, + "train_loss": 0.25871187719431793, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.14652537852175396, + "val_biou_gain": null, + "val_ce_loss": 0.1663631573319435, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.5456686517014157, + "val_dice_gain": null, + "val_dice_loss": 0.3667917549610138, + "val_entropy": 0.0, + "val_iou": 0.44738132611973674, + "val_iou_gain": null, + "val_loss": 0.26657745987176895, + "val_refine_score": 0.2969533523207454, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5937160816979881, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5937160816979881, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00015546225533535216, + "epoch": 8, + "epoch_seconds": 0.9169554868713021, + "grad_norm": 1.1345622864636509, + "lr": 7.132224066296732e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5937160816979881, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.14857504720037634, + "train_critic_loss": 0.0, + "train_dice": 0.6570260217294625, + "train_dice_loss": 0.33165086941285565, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5476474710346754, + "train_loss": 0.24011296033859253, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.2574033253197348, + "val_biou_gain": null, + "val_ce_loss": 0.15737314522266388, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.70885919224377, + "val_dice_gain": null, + "val_dice_loss": 0.3385756015777588, + "val_entropy": 0.0, + "val_iou": 0.5937160816979881, + "val_iou_gain": null, + "val_loss": 0.24797437340021133, + "val_refine_score": 0.4255597035088614, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5937160816979881, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5883257752330049, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00015481183268666878, + "epoch": 9, + "epoch_seconds": 0.9292954099364579, + "grad_norm": 1.2006659291007302, + "lr": 7.102612186077805e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5883257752330049, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.12447268109429967, + "train_critic_loss": 0.0, + "train_dice": 0.6959252355502485, + "train_dice_loss": 0.30410586162046954, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5886898996382515, + "train_loss": 0.21428927237337286, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.253493593577081, + "val_biou_gain": null, + "val_ce_loss": 0.16473493725061417, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7035659583617653, + "val_dice_gain": null, + "val_dice_loss": 0.3343488574028015, + "val_entropy": 0.0, + "val_iou": 0.5883257752330049, + "val_iou_gain": null, + "val_loss": 0.24954189360141754, + "val_refine_score": 0.42090968440504295, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.598017678128105, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00015408705049620858, + "epoch": 10, + "epoch_seconds": 0.9408729462884367, + "grad_norm": 1.3743054920976812, + "lr": 7.06961492890639e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.598017678128105, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.12683295526287772, + "train_critic_loss": 0.0, + "train_dice": 0.6955148880959565, + "train_dice_loss": 0.2959324609149586, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5886240565236592, + "train_loss": 0.21138270876624368, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.2823568882165871, + "val_biou_gain": null, + "val_ce_loss": 0.12965480983257294, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7065206711157377, + "val_dice_gain": null, + "val_dice_loss": 0.33672770857810974, + "val_entropy": 0.0, + "val_iou": 0.598017678128105, + "val_iou_gain": null, + "val_loss": 0.23319126665592194, + "val_refine_score": 0.44018728317234607, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.585207686786783, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00015328862403648954, + "epoch": 11, + "epoch_seconds": 0.9479437968693674, + "grad_norm": 1.3955165852199902, + "lr": 7.033264859091507e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.585207686786783, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.12571156431328168, + "train_critic_loss": 0.0, + "train_dice": 0.6957276094356774, + "train_dice_loss": 0.2862375757910989, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.590093452055091, + "train_loss": 0.20597457208416678, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.28361851944417793, + "val_biou_gain": null, + "val_ce_loss": 0.11360088363289833, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.690498169495824, + "val_dice_gain": null, + "val_dice_loss": 0.3239445984363556, + "val_entropy": 0.0, + "val_iou": 0.585207686786783, + "val_iou_gain": null, + "val_loss": 0.2187727391719818, + "val_refine_score": 0.4344131031154805, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5748921392972286, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.00015241734125803218, + "epoch": 12, + "epoch_seconds": 0.9586942782625556, + "grad_norm": 1.292943911118941, + "lr": 6.993597849763466e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5748921392972286, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.1260375197638165, + "train_critic_loss": 0.0, + "train_dice": 0.7044561785364395, + "train_dice_loss": 0.2801138162612915, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.5958267617616361, + "train_loss": 0.2030756717378443, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.2607782407558638, + "val_biou_gain": null, + "val_ce_loss": 0.1638278141617775, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6827484298267823, + "val_dice_gain": null, + "val_dice_loss": 0.3264201879501343, + "val_entropy": 0.0, + "val_iou": 0.5748921392972286, + "val_iou_gain": null, + "val_loss": 0.2451239973306656, + "val_refine_score": 0.41783519002654623, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.577427738878537, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 0.00015147406201174762, + "epoch": 13, + "epoch_seconds": 0.9319290858693421, + "grad_norm": 1.0601104768839749, + "lr": 6.950653047471417e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.577427738878537, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.11779470470818607, + "train_critic_loss": 0.0, + "train_dice": 0.7371388091974443, + "train_dice_loss": 0.2665867805480957, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6277478012944755, + "train_loss": 0.1921907433054664, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.2769091500265144, + "val_biou_gain": null, + "val_ce_loss": 0.1383563131093979, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6828394506005763, + "val_dice_gain": null, + "val_dice_loss": 0.33293870091438293, + "val_entropy": 0.0, + "val_iou": 0.577427738878537, + "val_iou_gain": null, + "val_loss": 0.23564749956130981, + "val_refine_score": 0.4271684444525257, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5764720175990729, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 0.00015045971720036846, + "epoch": 14, + "epoch_seconds": 0.9902117811143398, + "grad_norm": 0.8346128301186995, + "lr": 6.904472833550436e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5764720175990729, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.10715274986895648, + "train_critic_loss": 0.0, + "train_dice": 0.7244277646934102, + "train_dice_loss": 0.25557560270482843, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6208412855661022, + "train_loss": 0.1813641759482297, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.22190213247141516, + "val_biou_gain": null, + "val_ce_loss": 0.13658174872398376, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6977377440066329, + "val_dice_gain": null, + "val_dice_loss": 0.31999751925468445, + "val_entropy": 0.0, + "val_iou": 0.5764720175990729, + "val_iou_gain": null, + "val_loss": 0.2282896414399147, + "val_refine_score": 0.399187075035244, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598017678128105, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5737326930471368, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 0.00014937530785976016, + "epoch": 15, + "epoch_seconds": 1.0399007080122828, + "grad_norm": 1.0018138397823682, + "lr": 6.855102782296256e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5737326930471368, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.10901563546874306, + "train_critic_loss": 0.0, + "train_dice": 0.7374375952948716, + "train_dice_loss": 0.2590485702861439, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.631386574230267, + "train_loss": 0.18403210287744348, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.20367190780099703, + "val_biou_gain": null, + "val_ce_loss": 0.13296566158533096, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6987926697051325, + "val_dice_gain": null, + "val_dice_loss": 0.3358730375766754, + "val_entropy": 0.0, + "val_iou": 0.5737326930471368, + "val_iou_gain": null, + "val_loss": 0.2344193458557129, + "val_refine_score": 0.38870230042406695, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6064391649136633, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6064391649136633, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.0001482219041710196, + "epoch": 16, + "epoch_seconds": 0.9446938023902476, + "grad_norm": 0.9100835106589578, + "lr": 6.802591615988946e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6064391649136633, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.10631215233694423, + "train_critic_loss": 0.0, + "train_dice": 0.7351566762045499, + "train_dice_loss": 0.2506658272309737, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6290523473597339, + "train_loss": 0.17848899147727273, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.2973673202846734, + "val_biou_gain": null, + "val_ce_loss": 0.15826347470283508, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7151268577083256, + "val_dice_gain": null, + "val_dice_loss": 0.30305272340774536, + "val_entropy": 0.0, + "val_iou": 0.6064391649136633, + "val_iou_gain": null, + "val_loss": 0.23065809905529022, + "val_refine_score": 0.45190324259916836, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6215583856610222, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6215583856610222, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00014700064440433547, + "epoch": 17, + "epoch_seconds": 0.9464375656098127, + "grad_norm": 0.8445964672348716, + "lr": 6.746991156809904e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6215583856610222, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.10157768021930348, + "train_critic_loss": 0.0, + "train_dice": 0.7676961903132238, + "train_dice_loss": 0.23493980277668347, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6660909650765571, + "train_loss": 0.16825874149799347, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3027815349770644, + "val_biou_gain": null, + "val_ce_loss": 0.1291542872786522, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7323691671032243, + "val_dice_gain": null, + "val_dice_loss": 0.30671870708465576, + "val_entropy": 0.0, + "val_iou": 0.6215583856610222, + "val_iou_gain": null, + "val_loss": 0.21793650090694427, + "val_refine_score": 0.4621699603190433, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6308157070125237, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6308157070125237, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00014571273379565297, + "epoch": 18, + "epoch_seconds": 0.91397824883461, + "grad_norm": 0.7748768790201708, + "lr": 6.688356275699613e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6308157070125237, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.09139089760455218, + "train_critic_loss": 0.0, + "train_dice": 0.7766735947815018, + "train_dice_loss": 0.22071269967339255, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6788866554469596, + "train_loss": 0.15605180100961166, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.30862649415642357, + "val_biou_gain": null, + "val_ce_loss": 0.14077701419591904, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7385858415497895, + "val_dice_gain": null, + "val_dice_loss": 0.29869863390922546, + "val_entropy": 0.0, + "val_iou": 0.6308157070125237, + "val_iou_gain": null, + "val_loss": 0.21973782032728195, + "val_refine_score": 0.4697211005844736, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6359560213316554, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6359560213316554, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00014435944335725156, + "epoch": 19, + "epoch_seconds": 0.937543781939894, + "grad_norm": 0.826984928412871, + "lr": 6.626744838206654e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6359560213316554, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.09280893342061476, + "train_critic_loss": 0.0, + "train_dice": 0.7678388770684954, + "train_dice_loss": 0.21781783212314954, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6704520730014358, + "train_loss": 0.15531338344920764, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.32853455098861356, + "val_biou_gain": null, + "val_ce_loss": 0.10826616361737251, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7420396207523496, + "val_dice_gain": null, + "val_dice_loss": 0.2863181531429291, + "val_entropy": 0.0, + "val_iou": 0.6359560213316554, + "val_iou_gain": null, + "val_loss": 0.19729216396808624, + "val_refine_score": 0.4822452861601345, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6359560213316554, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.5695153663843265, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00014294210862340922, + "epoch": 20, + "epoch_seconds": 0.9157909830100834, + "grad_norm": 0.8189668682488528, + "lr": 6.562217647381393e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.5695153663843265, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.08658054674213583, + "train_critic_loss": 0.0, + "train_dice": 0.7800458601084114, + "train_dice_loss": 0.2148401141166687, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6806897066797415, + "train_loss": 0.15071033347736706, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.27131220489259944, + "val_biou_gain": null, + "val_ce_loss": 0.10339968279004097, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.6773076968029683, + "val_dice_gain": null, + "val_dice_loss": 0.2995724081993103, + "val_entropy": 0.0, + "val_iou": 0.5695153663843265, + "val_iou_gain": null, + "val_loss": 0.20148605108261108, + "val_refine_score": 0.420413785638463, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6359560213316554, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6175539636231363, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.0001414621283323913, + "epoch": 21, + "epoch_seconds": 0.847124510910362, + "grad_norm": 0.7845223952423442, + "lr": 6.494838383770712e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6175539636231363, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.08968175033276732, + "train_critic_loss": 0.0, + "train_dice": 0.7798796945998742, + "train_dice_loss": 0.20644944364374335, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6819233412841401, + "train_loss": 0.14806559749624945, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3241842662517135, + "val_biou_gain": null, + "val_ce_loss": 0.10187559947371483, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7231359995864882, + "val_dice_gain": null, + "val_dice_loss": 0.28081777691841125, + "val_entropy": 0.0, + "val_iou": 0.6175539636231363, + "val_iou_gain": null, + "val_loss": 0.1913466900587082, + "val_refine_score": 0.4708691149374249, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.643409485587232, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.643409485587232, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00013992096304606496, + "epoch": 22, + "epoch_seconds": 0.913078092969954, + "grad_norm": 0.6503843719309027, + "lr": 6.424673542573e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.643409485587232, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.08068043196743185, + "train_critic_loss": 0.0, + "train_dice": 0.7922318909769203, + "train_dice_loss": 0.2034731994975697, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6931259129539368, + "train_loss": 0.14207681742581454, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3070630863061261, + "val_biou_gain": null, + "val_ce_loss": 0.12781471014022827, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7518172716459238, + "val_dice_gain": null, + "val_dice_loss": 0.2794938385486603, + "val_entropy": 0.0, + "val_iou": 0.643409485587232, + "val_iou_gain": null, + "val_loss": 0.20365427434444427, + "val_refine_score": 0.47523628594667905, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6708172794814702, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00013832013370850056, + "epoch": 23, + "epoch_seconds": 0.9830166827887297, + "grad_norm": 0.668712629513307, + "lr": 6.351792368015414e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6708172794814702, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.082649538801475, + "train_critic_loss": 0.0, + "train_dice": 0.7869491410503433, + "train_dice_loss": 0.20190368999134412, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.6943001091035348, + "train_loss": 0.14227661693638022, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.34743813460165446, + "val_biou_gain": null, + "val_ce_loss": 0.12164920940995216, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7745801263227321, + "val_dice_gain": null, + "val_dice_loss": 0.2751840651035309, + "val_entropy": 0.0, + "val_iou": 0.6708172794814702, + "val_iou_gain": null, + "val_loss": 0.19841664284467697, + "val_refine_score": 0.5091277070415623, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6666632320383487, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00013666122014498384, + "epoch": 24, + "epoch_seconds": 0.9542150041088462, + "grad_norm": 0.5910226973620328, + "lr": 6.276266785018192e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6666632320383487, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0791243582286618, + "train_critic_loss": 0.0, + "train_dice": 0.7997654293629197, + "train_dice_loss": 0.19429043206301602, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7063567191220596, + "train_loss": 0.1367073959924958, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3591687940901313, + "val_biou_gain": null, + "val_ce_loss": 0.11581242829561234, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7695599147271717, + "val_dice_gain": null, + "val_dice_loss": 0.27955153584480286, + "val_entropy": 0.0, + "val_iou": 0.6666632320383487, + "val_iou_gain": null, + "val_loss": 0.1976819783449173, + "val_refine_score": 0.51291601306424, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6586276671612888, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.00013494585950291893, + "epoch": 25, + "epoch_seconds": 0.9183973078615963, + "grad_norm": 0.5957130085338246, + "lr": 6.198171328213437e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6586276671612888, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.07536205107515509, + "train_critic_loss": 0.0, + "train_dice": 0.8126503910364145, + "train_dice_loss": 0.186244168064811, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7184694171592316, + "train_loss": 0.13080311160195957, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3367886635020292, + "val_biou_gain": null, + "val_ce_loss": 0.11316284909844398, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7676693226834153, + "val_dice_gain": null, + "val_dice_loss": 0.26672783493995667, + "val_entropy": 0.0, + "val_iou": 0.6586276671612888, + "val_iou_gain": null, + "val_loss": 0.18994534760713577, + "val_refine_score": 0.497708165331659, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6310419643067571, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 0.00013317574463616157, + "epoch": 26, + "epoch_seconds": 0.9364506308920681, + "grad_norm": 0.6976548677141016, + "lr": 6.117583068388437e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6310419643067571, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.07896024191921408, + "train_critic_loss": 0.0, + "train_dice": 0.8098619350499887, + "train_dice_loss": 0.18582455136559226, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7148011815202091, + "train_loss": 0.13239239765839142, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3412427461039019, + "val_biou_gain": null, + "val_ce_loss": 0.09689264371991158, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7352155249765461, + "val_dice_gain": null, + "val_dice_loss": 0.26809653639793396, + "val_entropy": 0.0, + "val_iou": 0.6310419643067571, + "val_iou_gain": null, + "val_loss": 0.18249459564685822, + "val_refine_score": 0.48614235520532945, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6144802878951459, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 0.00013135262243437666, + "epoch": 27, + "epoch_seconds": 0.9435989200137556, + "grad_norm": 0.6287874606522647, + "lr": 6.034581536426101e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6144802878951459, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.07486262849786064, + "train_critic_loss": 0.0, + "train_dice": 0.8044466498202013, + "train_dice_loss": 0.18746902184052902, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7111005187413088, + "train_loss": 0.1311658261851831, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.31035501529288867, + "val_biou_gain": null, + "val_ce_loss": 0.10200000181794167, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7229620454672099, + "val_dice_gain": null, + "val_dice_loss": 0.2641138732433319, + "val_entropy": 0.0, + "val_iou": 0.6144802878951459, + "val_iou_gain": null, + "val_loss": 0.18305693566799164, + "val_refine_score": 0.46241765159401726, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6607978656755396, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 0.00012947829209906917, + "epoch": 28, + "epoch_seconds": 0.9253716976381838, + "grad_norm": 0.6811401410536333, + "lr": 5.949248644817579e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6607978656755396, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.07170042226260359, + "train_critic_loss": 0.0, + "train_dice": 0.8156282814503413, + "train_dice_loss": 0.1795210079713301, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.721742729805834, + "train_loss": 0.12561071596362375, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3424017160636515, + "val_biou_gain": null, + "val_ce_loss": 0.11789891868829727, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.764631971839736, + "val_dice_gain": null, + "val_dice_loss": 0.2690393328666687, + "val_entropy": 0.0, + "val_iou": 0.6607978656755396, + "val_iou_gain": null, + "val_loss": 0.19346912950277328, + "val_refine_score": 0.5015997908695955, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6708172794814702, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6553464284061045, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 6, + "encoder_lr": 0.00012755460336798938, + "epoch": 29, + "epoch_seconds": 0.93338513514027, + "grad_norm": 0.5739290064031427, + "lr": 5.861668606824525e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6553464284061045, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0692529979754578, + "train_critic_loss": 0.0, + "train_dice": 0.8206393920138497, + "train_dice_loss": 0.17702119458805432, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7294217225758203, + "train_loss": 0.1231370981444012, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3450837666004731, + "val_biou_gain": null, + "val_ce_loss": 0.11652466654777527, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7607142704934834, + "val_dice_gain": null, + "val_dice_loss": 0.27065375447273254, + "val_entropy": 0.0, + "val_iou": 0.6553464284061045, + "val_iou_gain": null, + "val_loss": 0.1935892105102539, + "val_refine_score": 0.5002150975032887, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6725459516271459, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6725459516271459, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00012558345468966514, + "epoch": 30, + "epoch_seconds": 0.9245867510326207, + "grad_norm": 0.63837146488103, + "lr": 5.77192785337077e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6725459516271459, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0688044818287546, + "train_critic_loss": 0.0, + "train_dice": 0.8239113958155473, + "train_dice_loss": 0.17342951622876254, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7346104062053557, + "train_loss": 0.12111700055274097, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3658752197389441, + "val_biou_gain": null, + "val_ce_loss": 0.12042753398418427, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7748441167971919, + "val_dice_gain": null, + "val_dice_loss": 0.25775307416915894, + "val_entropy": 0.0, + "val_iou": 0.6725459516271459, + "val_iou_gain": null, + "val_loss": 0.1890903115272522, + "val_refine_score": 0.519210585683045, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6725459516271459, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6580036279539273, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00012356679134986227, + "epoch": 31, + "epoch_seconds": 0.9829380246810615, + "grad_norm": 0.5340482050722296, + "lr": 5.6801149477454415e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6580036279539273, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.06561283191496675, + "train_critic_loss": 0.0, + "train_dice": 0.8247460047048563, + "train_dice_loss": 0.16605846990238537, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7379218997656021, + "train_loss": 0.11583565175533295, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.35602914817176406, + "val_biou_gain": null, + "val_ce_loss": 0.12282738462090492, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7618636164966307, + "val_dice_gain": null, + "val_dice_loss": 0.26544055342674255, + "val_entropy": 0.0, + "val_iou": 0.6580036279539273, + "val_iou_gain": null, + "val_loss": 0.19413397461175919, + "val_refine_score": 0.5070163880628457, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6725459516271459, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6355969482172633, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.00012150660355182244, + "epoch": 32, + "epoch_seconds": 0.940703643951565, + "grad_norm": 0.522315347736532, + "lr": 5.5863204982016844e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6355969482172633, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.06591661037369208, + "train_critic_loss": 0.0, + "train_dice": 0.8278705691098983, + "train_dice_loss": 0.1654790477319197, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7379140569269905, + "train_loss": 0.11569782956080003, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.33080450235041475, + "val_biou_gain": null, + "val_ce_loss": 0.13190779834985733, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7426954111656956, + "val_dice_gain": null, + "val_dice_loss": 0.26669588685035706, + "val_entropy": 0.0, + "val_iou": 0.6355969482172633, + "val_iou_gain": null, + "val_loss": 0.1993018388748169, + "val_refine_score": 0.48320072528383906, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6815052394145028, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6815052394145028, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00011940492445217285, + "epoch": 33, + "epoch_seconds": 0.9388420600444078, + "grad_norm": 0.5323448181152344, + "lr": 5.4906370685372594e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6815052394145028, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.06450087915767323, + "train_critic_loss": 0.0, + "train_dice": 0.8227099680791968, + "train_dice_loss": 0.1598128622228449, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7313363352028323, + "train_loss": 0.1121568733995611, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.371730286779358, + "val_biou_gain": null, + "val_ce_loss": 0.1289144530892372, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7823441978292042, + "val_dice_gain": null, + "val_dice_loss": 0.2618168890476227, + "val_entropy": 0.0, + "val_iou": 0.6815052394145028, + "val_iou_gain": null, + "val_loss": 0.19536566734313965, + "val_refine_score": 0.5266177630969304, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6815052394145028, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6787789541671734, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00011726382815444605, + "epoch": 34, + "epoch_seconds": 0.9192042057402432, + "grad_norm": 0.4993014362725345, + "lr": 5.393159086745243e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6787789541671734, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.06450381604107944, + "train_critic_loss": 0.0, + "train_dice": 0.840044608160359, + "train_dice_loss": 0.15889473394914108, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.752765084983355, + "train_loss": 0.11169927567243576, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3757326835433762, + "val_biou_gain": null, + "val_ce_loss": 0.11867799609899521, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7793676915953617, + "val_dice_gain": null, + "val_dice_loss": 0.253786563873291, + "val_entropy": 0.0, + "val_iou": 0.6787789541671734, + "val_iou_gain": null, + "val_loss": 0.1862322837114334, + "val_refine_score": 0.5272558188552747, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6815052394145028, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6788893293918121, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.00011508542766219021, + "epoch": 35, + "epoch_seconds": 0.885435642208904, + "grad_norm": 0.5039308016950433, + "lr": 5.2939827518250046e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6788893293918121, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.058884772726080635, + "train_critic_loss": 0.0, + "train_dice": 0.8411923124396297, + "train_dice_loss": 0.1526529843156988, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.755925341952509, + "train_loss": 0.10576887835155833, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3752731990540764, + "val_biou_gain": null, + "val_ce_loss": 0.11370141804218292, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7799135143982473, + "val_dice_gain": null, + "val_dice_loss": 0.24465855956077576, + "val_entropy": 0.0, + "val_iou": 0.6788893293918121, + "val_iou_gain": null, + "val_loss": 0.17917998880147934, + "val_refine_score": 0.5270812642229443, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6815052394145028, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6796211205049819, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 0.00011287187279368971, + "epoch": 36, + "epoch_seconds": 0.9212150648236275, + "grad_norm": 0.5255165479399941, + "lr": 5.193205938845408e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6796211205049819, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.059352612630887466, + "train_critic_loss": 0.0, + "train_dice": 0.8429133818042402, + "train_dice_loss": 0.15228965065696023, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7556189114414589, + "train_loss": 0.1058211319825866, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3632272327955636, + "val_biou_gain": null, + "val_ce_loss": 0.11638562008738518, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.780395038904426, + "val_dice_gain": null, + "val_dice_loss": 0.24885299801826477, + "val_entropy": 0.0, + "val_iou": 0.6796211205049819, + "val_iou_gain": null, + "val_loss": 0.18261930346488953, + "val_refine_score": 0.5214241766502727, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.687001451934456, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.687001451934456, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00011062534806035402, + "epoch": 37, + "epoch_seconds": 0.9314013067632914, + "grad_norm": 0.608214408159256, + "lr": 5.09092810235393e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.687001451934456, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.06655619632114064, + "train_critic_loss": 0.0, + "train_dice": 0.843239291287707, + "train_dice_loss": 0.15330680392005228, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7575466631360329, + "train_loss": 0.10993150079792197, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.37226927960919565, + "val_biou_gain": null, + "val_ce_loss": 0.10376682132482529, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.786899929807433, + "val_dice_gain": null, + "val_dice_loss": 0.24395990371704102, + "val_entropy": 0.0, + "val_iou": 0.687001451934456, + "val_iou_gain": null, + "val_loss": 0.17386336624622345, + "val_refine_score": 0.5296353657718258, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.687001451934456, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6789421401017852, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.00010834807051086878, + "epoch": 38, + "epoch_seconds": 0.8725407980382442, + "grad_norm": 0.48353078961372375, + "lr": 4.987250178227037e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6789421401017852, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.057348465716296974, + "train_critic_loss": 0.0, + "train_dice": 0.8432956342397797, + "train_dice_loss": 0.15114461291920056, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7584294344100145, + "train_loss": 0.1042465405030684, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.36866965993710965, + "val_biou_gain": null, + "val_ce_loss": 0.10832805186510086, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7801595181472891, + "val_dice_gain": null, + "val_dice_loss": 0.2432447075843811, + "val_entropy": 0.0, + "val_iou": 0.6789421401017852, + "val_iou_gain": null, + "val_loss": 0.17578638345003128, + "val_refine_score": 0.5238059000194475, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.687001451934456, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6663887297982825, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 0.00010604228754323621, + "epoch": 39, + "epoch_seconds": 0.8998690959997475, + "grad_norm": 0.5788166983561083, + "lr": 4.882274484058652e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6663887297982825, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.059218851002779876, + "train_critic_loss": 0.0, + "train_dice": 0.8413383296637974, + "train_dice_loss": 0.1499738097190857, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7544699656646717, + "train_loss": 0.10459633239290932, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.327077603666925, + "val_biou_gain": null, + "val_ce_loss": 0.14592154324054718, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7733012529624814, + "val_dice_gain": null, + "val_dice_loss": 0.25788384675979614, + "val_entropy": 0.0, + "val_iou": 0.6663887297982825, + "val_iou_gain": null, + "val_loss": 0.20190269500017166, + "val_refine_score": 0.4967331667326037, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6871779099625692, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6871779099625692, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 0.00010371027468686484, + "epoch": 40, + "epoch_seconds": 0.9099456607364118, + "grad_norm": 0.5736530125141144, + "lr": 4.776104618185052e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6871779099625692, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.05682113123210994, + "train_critic_loss": 0.0, + "train_dice": 0.850018445888536, + "train_dice_loss": 0.14500936594876376, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.763526723274963, + "train_loss": 0.10091524909843098, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3822524558481125, + "val_biou_gain": null, + "val_ce_loss": 0.11645104736089706, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.788027163818788, + "val_dice_gain": null, + "val_dice_loss": 0.2448424994945526, + "val_entropy": 0.0, + "val_iou": 0.6871779099625692, + "val_iou_gain": null, + "val_loss": 0.18064677715301514, + "val_refine_score": 0.5347151829053409, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6871779099625692, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6818000586541619, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 0.0001013543333568966, + "epoch": 41, + "epoch_seconds": 1.0738688232377172, + "grad_norm": 0.5501963956789537, + "lr": 4.668845357445811e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6818000586541619, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.059889895672147926, + "train_critic_loss": 0.0, + "train_dice": 0.845988097006289, + "train_dice_loss": 0.14596993272954767, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7616768699663775, + "train_loss": 0.10292991453951056, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.38415231882940637, + "val_biou_gain": null, + "val_ce_loss": 0.11229291558265686, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7807909861761609, + "val_dice_gain": null, + "val_dice_loss": 0.24539950489997864, + "val_entropy": 0.0, + "val_iou": 0.6818000586541619, + "val_iou_gain": null, + "val_loss": 0.17884621024131775, + "val_refine_score": 0.5329761887417841, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6871779099625692, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6859655745036838, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 9.897678858298789e-05, + "epoch": 42, + "epoch_seconds": 1.053900192026049, + "grad_norm": 0.5227477983994917, + "lr": 4.560602553781709e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6859655745036838, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.055187435312704605, + "train_critic_loss": 0.0, + "train_dice": 0.8486134748289358, + "train_dice_loss": 0.14264801415530118, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7655823828889824, + "train_loss": 0.09891772676597942, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3654007121444838, + "val_biou_gain": null, + "val_ce_loss": 0.1251538023352623, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.786980312173922, + "val_dice_gain": null, + "val_dice_loss": 0.24682053923606873, + "val_entropy": 0.0, + "val_iou": 0.6859655745036838, + "val_iou_gain": null, + "val_loss": 0.1859871670603752, + "val_refine_score": 0.5256831433240838, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6972983991358224, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6972983991358224, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 9.657998671478617e-05, + "epoch": 43, + "epoch_seconds": 0.8679125141352415, + "grad_norm": 0.4291134097359397, + "lr": 4.451483029771655e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6972983991358224, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.05463103577494621, + "train_critic_loss": 0.0, + "train_dice": 0.8533781967926639, + "train_dice_loss": 0.14053462310270828, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7709656098903542, + "train_loss": 0.0975828306241469, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.38664193955917964, + "val_biou_gain": null, + "val_ce_loss": 0.12333779409527779, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7968479850605211, + "val_dice_gain": null, + "val_dice_loss": 0.24649059772491455, + "val_entropy": 0.0, + "val_iou": 0.6972983991358224, + "val_iou_gain": null, + "val_loss": 0.18491419404745102, + "val_refine_score": 0.541970169347501, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6998696121295981, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 9.416629310636589e-05, + "epoch": 44, + "epoch_seconds": 0.9471998079679906, + "grad_norm": 0.42689659378745337, + "lr": 4.341594473211683e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6998696121295981, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.05458009852604433, + "train_critic_loss": 0.0, + "train_dice": 0.8501069056023945, + "train_dice_loss": 0.13610458374023438, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7697529614129084, + "train_loss": 0.09534234147180211, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3902486699288975, + "val_biou_gain": null, + "val_ce_loss": 0.11395341157913208, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7967889806809257, + "val_dice_gain": null, + "val_dice_loss": 0.24014994502067566, + "val_entropy": 0.0, + "val_iou": 0.6998696121295981, + "val_iou_gain": null, + "val_loss": 0.17705167829990387, + "val_refine_score": 0.5450591410292478, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6948693953124954, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 9.17380897819098e-05, + "epoch": 45, + "epoch_seconds": 1.0097478600218892, + "grad_norm": 0.42317618294195697, + "lr": 4.231045330840112e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6948693953124954, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.051177337088368156, + "train_critic_loss": 0.0, + "train_dice": 0.860445299423486, + "train_dice_loss": 0.13412015546451916, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7796848979750457, + "train_loss": 0.09264874661510641, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3753080701914829, + "val_biou_gain": null, + "val_ce_loss": 0.13034310564398766, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7938056029049827, + "val_dice_gain": null, + "val_dice_loss": 0.24556145071983337, + "val_entropy": 0.0, + "val_iou": 0.6948693953124954, + "val_iou_gain": null, + "val_loss": 0.18795228004455566, + "val_refine_score": 0.5350887327519891, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6971606452027024, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 8.929777308493866e-05, + "epoch": 46, + "epoch_seconds": 1.0128225847147405, + "grad_norm": 0.4578447070988742, + "lr": 4.1199447013137047e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6971606452027024, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.051678943363103, + "train_critic_loss": 0.0, + "train_dice": 0.8608639627202662, + "train_dice_loss": 0.13504535501653497, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7795986918805742, + "train_loss": 0.09336215122179552, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3902965148682041, + "val_biou_gain": null, + "val_ce_loss": 0.11880891770124435, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7957236911537386, + "val_dice_gain": null, + "val_dice_loss": 0.23480626940727234, + "val_entropy": 0.0, + "val_iou": 0.6971606452027024, + "val_iou_gain": null, + "val_loss": 0.17680759727954865, + "val_refine_score": 0.5437285800354532, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6930951930227311, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 8.684775131340929e-05, + "epoch": 47, + "epoch_seconds": 0.9822556423023343, + "grad_norm": 0.4147814742543481, + "lr": 4.0084022275404595e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6930951930227311, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.050425524400039154, + "train_critic_loss": 0.0, + "train_dice": 0.8586336548061902, + "train_dice_loss": 0.130731387571855, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7793944568067063, + "train_loss": 0.0905784551392902, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.37609222652380825, + "val_biou_gain": null, + "val_ce_loss": 0.13911858946084976, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7927161819877656, + "val_dice_gain": null, + "val_dice_loss": 0.23925510048866272, + "val_entropy": 0.0, + "val_iou": 0.6930951930227311, + "val_iou_gain": null, + "val_loss": 0.18918684124946594, + "val_refine_score": 0.5345937097732697, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6890232934596567, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 8.439044234301555e-05, + "epoch": 48, + "epoch_seconds": 0.9860899853520095, + "grad_norm": 0.5288907479156147, + "lr": 3.896527988475308e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6890232934596567, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.05235713212327524, + "train_critic_loss": 0.0, + "train_dice": 0.8638470550079043, + "train_dice_loss": 0.13381145217201926, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7837487010677574, + "train_loss": 0.09308429265564139, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.36377479387756323, + "val_biou_gain": null, + "val_ce_loss": 0.13066366314888, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7908931966206323, + "val_dice_gain": null, + "val_dice_loss": 0.2423495352268219, + "val_entropy": 0.0, + "val_iou": 0.6890232934596567, + "val_iou_gain": null, + "val_loss": 0.18650659918785095, + "val_refine_score": 0.52639904366861, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6985033578838588, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 8.192827124103668e-05, + "epoch": 49, + "epoch_seconds": 0.9385153306648135, + "grad_norm": 0.4071189517324621, + "lr": 3.7844323904854644e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6985033578838588, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.05067764121023091, + "train_critic_loss": 0.0, + "train_dice": 0.8667226726798968, + "train_dice_loss": 0.13249672001058405, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7864456431397016, + "train_loss": 0.09158718111840161, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.39221273112143035, + "val_biou_gain": null, + "val_ce_loss": 0.12072525918483734, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7962253064158166, + "val_dice_gain": null, + "val_dice_loss": 0.24142852425575256, + "val_entropy": 0.0, + "val_iou": 0.6985033578838588, + "val_iou_gain": null, + "val_loss": 0.18107688426971436, + "val_refine_score": 0.5453580445026446, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6975794744294758, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 6, + "encoder_lr": 7.94636678730888e-05, + "epoch": 50, + "epoch_seconds": 0.9316380047239363, + "grad_norm": 0.3779155761003494, + "lr": 3.6722260583926804e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6975794744294758, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0475196127187122, + "train_critic_loss": 0.0, + "train_dice": 0.8683866307818913, + "train_dice_loss": 0.12542490525679154, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7904425587211863, + "train_loss": 0.08647225864908913, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3939091148611902, + "val_biou_gain": null, + "val_ce_loss": 0.11489787325263023, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7949852214671432, + "val_dice_gain": null, + "val_dice_loss": 0.234965980052948, + "val_entropy": 0.0, + "val_iou": 0.6975794744294758, + "val_iou_gain": null, + "val_loss": 0.17493192851543427, + "val_refine_score": 0.545744294645333, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6946981944963054, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 7, + "encoder_lr": 7.699906450514093e-05, + "epoch": 51, + "epoch_seconds": 0.9971981830894947, + "grad_norm": 0.5309844585982236, + "lr": 3.560019726299896e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6946981944963054, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04701698808507486, + "train_critic_loss": 0.0, + "train_dice": 0.8698010287113713, + "train_dice_loss": 0.1236796270717274, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7913120911665025, + "train_loss": 0.08534830740906975, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.38996571256288615, + "val_biou_gain": null, + "val_ce_loss": 0.12987107783555984, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7929418146856421, + "val_dice_gain": null, + "val_dice_loss": 0.23685306310653687, + "val_entropy": 0.0, + "val_iou": 0.6946981944963054, + "val_iou_gain": null, + "val_loss": 0.18336206674575806, + "val_refine_score": 0.5423319535295958, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.675867544467725, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 8, + "encoder_lr": 7.453689340316206e-05, + "epoch": 52, + "epoch_seconds": 0.9367213528603315, + "grad_norm": 0.4754872403361581, + "lr": 3.447924128310053e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.675867544467725, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.050665303726087914, + "train_critic_loss": 0.0, + "train_dice": 0.8650319123940542, + "train_dice_loss": 0.13171966509385544, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7869108536070781, + "train_loss": 0.09119248593395407, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.34293010999898754, + "val_biou_gain": null, + "val_ce_loss": 0.1523960754275322, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7807245736031356, + "val_dice_gain": null, + "val_dice_loss": 0.24910476803779602, + "val_entropy": 0.0, + "val_iou": 0.675867544467725, + "val_iou_gain": null, + "val_loss": 0.2007504180073738, + "val_refine_score": 0.5093988272333563, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6961219539078242, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 9, + "encoder_lr": 7.20795844327683e-05, + "epoch": 53, + "epoch_seconds": 0.9869598606601357, + "grad_norm": 0.42319638349793176, + "lr": 3.3360498892449005e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6961219539078242, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.046547154133970085, + "train_critic_loss": 0.0, + "train_dice": 0.8692284489258183, + "train_dice_loss": 0.1227851618419994, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7906686238766707, + "train_loss": 0.08466615866531026, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3913486447350459, + "val_biou_gain": null, + "val_ce_loss": 0.11907127499580383, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7935317141720741, + "val_dice_gain": null, + "val_dice_loss": 0.23559483885765076, + "val_entropy": 0.0, + "val_iou": 0.6961219539078242, + "val_iou_gain": null, + "val_loss": 0.1773330569267273, + "val_refine_score": 0.543735299321435, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6889850213376915, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 10, + "encoder_lr": 6.962956266123896e-05, + "epoch": 54, + "epoch_seconds": 0.9523130338639021, + "grad_norm": 0.39551787213845685, + "lr": 3.224507415471657e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6889850213376915, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04758766293525696, + "train_critic_loss": 0.0, + "train_dice": 0.8662443881057854, + "train_dice_loss": 0.12325155735015869, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7877737517376416, + "train_loss": 0.08541961149735884, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3898530757353602, + "val_biou_gain": null, + "val_ce_loss": 0.12743904441595078, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7868474118237851, + "val_dice_gain": null, + "val_dice_loss": 0.24186646938323975, + "val_entropy": 0.0, + "val_iou": 0.6889850213376915, + "val_iou_gain": null, + "val_loss": 0.18465276062488556, + "val_refine_score": 0.5394190485365258, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998696121295981, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6941960832574532, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 11, + "encoder_lr": 6.718924596426779e-05, + "epoch": 55, + "epoch_seconds": 0.9080621539615095, + "grad_norm": 0.3757167119871486, + "lr": 3.113406785945249e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6941960832574532, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0457291112027385, + "train_critic_loss": 0.0, + "train_dice": 0.8744053614920066, + "train_dice_loss": 0.11895545504309914, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7961293110938084, + "train_loss": 0.0823422832922502, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40106707850607065, + "val_biou_gain": null, + "val_ce_loss": 0.12513170763850212, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7910215559241203, + "val_dice_gain": null, + "val_dice_loss": 0.24011358618736267, + "val_entropy": 0.0, + "val_iou": 0.6941960832574532, + "val_iou_gain": null, + "val_loss": 0.18262264877557755, + "val_refine_score": 0.5476315808817619, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998732999487323, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6998732999487323, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 6.476104263981172e-05, + "epoch": 56, + "epoch_seconds": 0.9408144252374768, + "grad_norm": 0.4740045964717865, + "lr": 3.0028576435736787e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6998732999487323, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04819135029207577, + "train_critic_loss": 0.0, + "train_dice": 0.8723444987774589, + "train_dice_loss": 0.12331000783226707, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7937000102590317, + "train_loss": 0.08575068007815968, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3963988525417334, + "val_biou_gain": null, + "val_ce_loss": 0.13385432958602905, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7967287112260998, + "val_dice_gain": null, + "val_dice_loss": 0.2387389838695526, + "val_entropy": 0.0, + "val_iou": 0.6998732999487323, + "val_iou_gain": null, + "val_loss": 0.18629665672779083, + "val_refine_score": 0.5481360762452329, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6998732999487323, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6930370386260243, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 6.234734903139147e-05, + "epoch": 57, + "epoch_seconds": 1.003545864019543, + "grad_norm": 0.436352553692731, + "lr": 2.8929690870137073e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6930370386260243, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.047376707873561165, + "train_critic_loss": 0.0, + "train_dice": 0.874378204049037, + "train_dice_loss": 0.12136885252865878, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7987194604424341, + "train_loss": 0.08437278121709824, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.37409854966891337, + "val_biou_gain": null, + "val_ce_loss": 0.12296909838914871, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7944753169297208, + "val_dice_gain": null, + "val_dice_loss": 0.23784026503562927, + "val_entropy": 0.0, + "val_iou": 0.6930370386260243, + "val_iou_gain": null, + "val_loss": 0.1804046779870987, + "val_refine_score": 0.5335677941474688, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7027021607807243, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 5.9950547163189696e-05, + "epoch": 58, + "epoch_seconds": 0.9818501737900078, + "grad_norm": 0.36405837671323255, + "lr": 2.7838495630036504e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7027021607807243, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04533475027842955, + "train_critic_loss": 0.0, + "train_dice": 0.8784760613968496, + "train_dice_loss": 0.11854872378436002, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8032263514369133, + "train_loss": 0.08194173737005754, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40478765140838846, + "val_biou_gain": null, + "val_ce_loss": 0.12058243155479431, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7974303023453136, + "val_dice_gain": null, + "val_dice_loss": 0.2350468635559082, + "val_entropy": 0.0, + "val_iou": 0.7027021607807243, + "val_iou_gain": null, + "val_loss": 0.17781464755535126, + "val_refine_score": 0.5537449060945564, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7012251402518044, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 5.757300238928102e-05, + "epoch": 59, + "epoch_seconds": 0.8763518678024411, + "grad_norm": 0.39852748675779864, + "lr": 2.6756067593395503e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7012251402518044, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04170991954478351, + "train_critic_loss": 0.0, + "train_dice": 0.8766252734373251, + "train_dice_loss": 0.11528364636681297, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.7989325518002043, + "train_loss": 0.07849678261713548, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4028760457545316, + "val_biou_gain": null, + "val_ce_loss": 0.1306658610701561, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7965749653681087, + "val_dice_gain": null, + "val_dice_loss": 0.23268279433250427, + "val_entropy": 0.0, + "val_iou": 0.7012251402518044, + "val_iou_gain": null, + "val_loss": 0.18167433142662048, + "val_refine_score": 0.552050593003168, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6957437929207207, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 5.5217061059312795e-05, + "epoch": 60, + "epoch_seconds": 0.8668818920850754, + "grad_norm": 0.35084232687950134, + "lr": 2.56834749860031e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6957437929207207, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.043963206762617286, + "train_critic_loss": 0.0, + "train_dice": 0.8777910829609027, + "train_dice_loss": 0.11410420591180975, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8015769044289442, + "train_loss": 0.07903370735320178, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.38125317885354876, + "val_biou_gain": null, + "val_ce_loss": 0.143460713326931, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7940148560055066, + "val_dice_gain": null, + "val_dice_loss": 0.23541992902755737, + "val_entropy": 0.0, + "val_iou": 0.6957437929207207, + "val_iou_gain": null, + "val_loss": 0.18944032490253448, + "val_refine_score": 0.5384984858871348, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7025171464716649, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 5.2885048202941414e-05, + "epoch": 61, + "epoch_seconds": 0.8583680372685194, + "grad_norm": 0.3352213434197686, + "lr": 2.4621776327267093e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7025171464716649, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04022434641691772, + "train_critic_loss": 0.0, + "train_dice": 0.8847202600147536, + "train_dice_loss": 0.1100785569711165, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8112744264474038, + "train_loss": 0.07515145296400244, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40000385782861203, + "val_biou_gain": null, + "val_ce_loss": 0.13837243616580963, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7981062820588802, + "val_dice_gain": null, + "val_dice_loss": 0.23652112483978271, + "val_entropy": 0.0, + "val_iou": 0.7025171464716649, + "val_iou_gain": null, + "val_loss": 0.18744678795337677, + "val_refine_score": 0.5512605021501384, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7016398691493926, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 5.0579265235308866e-05, + "epoch": 62, + "epoch_seconds": 1.0135888569056988, + "grad_norm": 0.3841277008706873, + "lr": 2.3572019385583258e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7016398691493926, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04299358481710607, + "train_critic_loss": 0.0, + "train_dice": 0.8809250639758232, + "train_dice_loss": 0.11344480514526367, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8075178383623859, + "train_loss": 0.07821919701316139, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.39693156760635234, + "val_biou_gain": null, + "val_ce_loss": 0.13777953013777733, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7969919043371505, + "val_dice_gain": null, + "val_dice_loss": 0.23569998145103455, + "val_entropy": 0.0, + "val_iou": 0.7016398691493926, + "val_iou_gain": null, + "val_loss": 0.1867397576570511, + "val_refine_score": 0.5492857183778724, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6993541112640068, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 4.830198768582357e-05, + "epoch": 63, + "epoch_seconds": 0.9430193309672177, + "grad_norm": 0.3937239416620948, + "lr": 2.2535240144314302e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6993541112640068, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04261814633553678, + "train_critic_loss": 0.0, + "train_dice": 0.8827412695625592, + "train_dice_loss": 0.11250085180455988, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8096589621118931, + "train_loss": 0.07755949890071695, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4027668857649103, + "val_biou_gain": null, + "val_ce_loss": 0.13890563696622849, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7949398799911627, + "val_dice_gain": null, + "val_dice_loss": 0.23902058601379395, + "val_entropy": 0.0, + "val_iou": 0.6993541112640068, + "val_iou_gain": null, + "val_loss": 0.1889631152153015, + "val_refine_score": 0.5510604985144586, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6960599333215054, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 6, + "encoder_lr": 4.6055462952487894e-05, + "epoch": 64, + "epoch_seconds": 0.9731144001707435, + "grad_norm": 0.37360109795223584, + "lr": 2.151246177939953e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6960599333215054, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.04160545292225751, + "train_critic_loss": 0.0, + "train_dice": 0.8825621309356554, + "train_dice_loss": 0.11081708561290395, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8095445478024818, + "train_loss": 0.07621126960624348, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3891375777099606, + "val_biou_gain": null, + "val_ce_loss": 0.1469549909234047, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7942109750034554, + "val_dice_gain": null, + "val_dice_loss": 0.24422496557235718, + "val_entropy": 0.0, + "val_iou": 0.6960599333215054, + "val_iou_gain": null, + "val_loss": 0.19558997452259064, + "val_refine_score": 0.542598755515733, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7003063543780322, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 7, + "encoder_lr": 4.3841908083987396e-05, + "epoch": 65, + "epoch_seconds": 0.9387936079874635, + "grad_norm": 0.4462184269319881, + "lr": 2.050469364960356e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7003063543780322, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.045058281922882255, + "train_critic_loss": 0.0, + "train_dice": 0.8814022231029617, + "train_dice_loss": 0.11568139358000322, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8069763147677887, + "train_loss": 0.08036983825943687, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40205453028216576, + "val_biou_gain": null, + "val_ce_loss": 0.14502401649951935, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.79638275484143, + "val_dice_gain": null, + "val_dice_loss": 0.2357931137084961, + "val_entropy": 0.0, + "val_iou": 0.7003063543780322, + "val_iou_gain": null, + "val_loss": 0.19040857255458832, + "val_refine_score": 0.551180442330099, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7013319672538695, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 8, + "encoder_lr": 4.1663507591731536e-05, + "epoch": 66, + "epoch_seconds": 0.9359182207845151, + "grad_norm": 0.3254088637503711, + "lr": 1.9512930300401176e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7013319672538695, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0386842279271646, + "train_critic_loss": 0.0, + "train_dice": 0.8901785538220557, + "train_dice_loss": 0.10635572130029852, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8176495160327816, + "train_loss": 0.07251997495239432, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3962615176380411, + "val_biou_gain": null, + "val_ce_loss": 0.146223783493042, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7976401106907782, + "val_dice_gain": null, + "val_dice_loss": 0.23654189705848694, + "val_entropy": 0.0, + "val_iou": 0.7013319672538695, + "val_iou_gain": null, + "val_loss": 0.19138284027576447, + "val_refine_score": 0.5487967424459553, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6949109219397877, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 9, + "encoder_lr": 3.9522411294004746e-05, + "epoch": 67, + "epoch_seconds": 0.9999922839924693, + "grad_norm": 0.39868357235735113, + "lr": 1.8538150482481017e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6949109219397877, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.040185989304022354, + "train_critic_loss": 0.0, + "train_dice": 0.88619175058665, + "train_dice_loss": 0.11000354181636464, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8137420181625243, + "train_loss": 0.0750947655601935, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40084466063266144, + "val_biou_gain": null, + "val_ce_loss": 0.14073555544018745, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7912106261040542, + "val_dice_gain": null, + "val_dice_loss": 0.24002638459205627, + "val_entropy": 0.0, + "val_iou": 0.6949109219397877, + "val_iou_gain": null, + "val_loss": 0.19038096815347672, + "val_refine_score": 0.5478777912862245, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6818582658691695, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 10, + "encoder_lr": 3.742073219435514e-05, + "epoch": 68, + "epoch_seconds": 0.9996213321574032, + "grad_norm": 0.39009782536463306, + "lr": 1.7581316185836756e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6818582658691695, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.041967560960487885, + "train_critic_loss": 0.0, + "train_dice": 0.8825313025494608, + "train_dice_loss": 0.11116570776159113, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8094982669121291, + "train_loss": 0.07656663453037088, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3558607178938294, + "val_biou_gain": null, + "val_ce_loss": 0.16688063740730286, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.784054183512203, + "val_dice_gain": null, + "val_dice_loss": 0.24626508355140686, + "val_entropy": 0.0, + "val_iou": 0.6818582658691695, + "val_iou_gain": null, + "val_loss": 0.20657286047935486, + "val_refine_score": 0.5188594918814995, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6977857540768337, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 11, + "encoder_lr": 3.5360544396315334e-05, + "epoch": 69, + "epoch_seconds": 1.0081771668046713, + "grad_norm": 0.39382978731935675, + "lr": 1.6643371690399203e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6977857540768337, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.039352021772753105, + "train_critic_loss": 0.0, + "train_dice": 0.8877673014529506, + "train_dice_loss": 0.10704505985433405, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.814296608796463, + "train_loss": 0.07319854199886322, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4067234218568538, + "val_biou_gain": null, + "val_ce_loss": 0.14230384677648544, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7931623565798033, + "val_dice_gain": null, + "val_dice_loss": 0.23893076181411743, + "val_entropy": 0.0, + "val_iou": 0.6977857540768337, + "val_iou_gain": null, + "val_loss": 0.19061730802059174, + "val_refine_score": 0.5522545879668438, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6980153448581264, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 12, + "encoder_lr": 3.3343881056512486e-05, + "epoch": 70, + "epoch_seconds": 0.9180875211022794, + "grad_norm": 0.3577480289069089, + "lr": 1.5725242634145925e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6980153448581264, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.040100324898958206, + "train_critic_loss": 0.0, + "train_dice": 0.8884025291160498, + "train_dice_loss": 0.10910738056356256, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8168574643785158, + "train_loss": 0.07460385323925452, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.39938740079159285, + "val_biou_gain": null, + "val_ce_loss": 0.14300721883773804, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7943431265353725, + "val_dice_gain": null, + "val_dice_loss": 0.23666095733642578, + "val_entropy": 0.0, + "val_iou": 0.6980153448581264, + "val_iou_gain": null, + "val_loss": 0.1898340880870819, + "val_refine_score": 0.5487013728248596, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.6989503610877719, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 13, + "encoder_lr": 3.137273237818822e-05, + "epoch": 71, + "epoch_seconds": 0.9666763357818127, + "grad_norm": 0.3782085722143, + "lr": 1.4827835099608369e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.6989503610877719, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.038860324431549416, + "train_critic_loss": 0.0, + "train_dice": 0.8888491724205713, + "train_dice_loss": 0.10567479241978038, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8156924827684106, + "train_loss": 0.07226755944165317, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4080036639244462, + "val_biou_gain": null, + "val_ce_loss": 0.1410525068640709, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7947717352840445, + "val_dice_gain": null, + "val_dice_loss": 0.2375558316707611, + "val_entropy": 0.0, + "val_iou": 0.6989503610877719, + "val_iou_gain": null, + "val_loss": 0.1893041729927063, + "val_refine_score": 0.553477012506109, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7027021607807243, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7016208817381991, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 14, + "encoder_lr": 2.9449043647108445e-05, + "epoch": 72, + "epoch_seconds": 0.9355268198996782, + "grad_norm": 0.3528155345808376, + "lr": 1.3952034719677823e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7016208817381991, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03735989924858917, + "train_critic_loss": 0.0, + "train_dice": 0.890102539074072, + "train_dice_loss": 0.10338196429339322, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8180010454972458, + "train_loss": 0.07037093354897066, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.39834368180209784, + "val_biou_gain": null, + "val_ce_loss": 0.15255381911993027, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7979223398264504, + "val_dice_gain": null, + "val_dice_loss": 0.23512661457061768, + "val_entropy": 0.0, + "val_iou": 0.7016208817381991, + "val_iou_gain": null, + "val_loss": 0.19384022057056427, + "val_refine_score": 0.5499822817701485, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7032976946238741, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7032976946238741, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 2.757471331180096e-05, + "epoch": 73, + "epoch_seconds": 0.9679220546968281, + "grad_norm": 0.33369749784469604, + "lr": 1.3098705803592611e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7032976946238741, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03810249675403942, + "train_critic_loss": 0.0, + "train_dice": 0.8866154216540408, + "train_dice_loss": 0.10429044745185158, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8148714337066266, + "train_loss": 0.07119647278027101, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40187097980843206, + "val_biou_gain": null, + "val_ce_loss": 0.15541184693574905, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7991673174046007, + "val_dice_gain": null, + "val_dice_loss": 0.23597756028175354, + "val_entropy": 0.0, + "val_iou": 0.7032976946238741, + "val_iou_gain": null, + "val_loss": 0.195694699883461, + "val_refine_score": 0.5525843372161531, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7044752325241393, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7044752325241393, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 2.575159111001603e-05, + "epoch": 74, + "epoch_seconds": 0.95355234015733, + "grad_norm": 0.341999121687629, + "lr": 1.2268690483969241e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7044752325241393, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03860323859209364, + "train_critic_loss": 0.0, + "train_dice": 0.8934334078432593, + "train_dice_loss": 0.10321798649701205, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8229556260079283, + "train_loss": 0.07091061296788129, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40756330557983333, + "val_biou_gain": null, + "val_ce_loss": 0.14256782457232475, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7995937443934965, + "val_dice_gain": null, + "val_dice_loss": 0.234948068857193, + "val_entropy": 0.0, + "val_iou": 0.7044752325241393, + "val_iou_gain": null, + "val_loss": 0.18875794857740402, + "val_refine_score": 0.5560192690519863, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7044752325241393, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7028126612546647, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 2.3981476243258662e-05, + "epoch": 75, + "epoch_seconds": 1.0412745708599687, + "grad_norm": 0.3284375396641818, + "lr": 1.1462807885719246e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7028126612546647, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03714521026069468, + "train_critic_loss": 0.0, + "train_dice": 0.8946247640429239, + "train_dice_loss": 0.1034363941712813, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8241937595393873, + "train_loss": 0.07029080323197624, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40237164238364476, + "val_biou_gain": null, + "val_ce_loss": 0.15147648006677628, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7979713401210143, + "val_dice_gain": null, + "val_dice_loss": 0.23635900020599365, + "val_entropy": 0.0, + "val_iou": 0.7028126612546647, + "val_iou_gain": null, + "val_loss": 0.19391773641109467, + "val_refine_score": 0.5525921518191548, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7044752325241393, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7027251249530224, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 2.2266115601193765e-05, + "epoch": 76, + "epoch_seconds": 1.105661695357412, + "grad_norm": 0.33539951660416345, + "lr": 1.06818533176717e-05, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7027251249530224, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03653784401037476, + "train_critic_loss": 0.0, + "train_dice": 0.8953038220098413, + "train_dice_loss": 0.1012609601020813, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8255338969232462, + "train_loss": 0.06889940256422217, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4048893854938437, + "val_biou_gain": null, + "val_ce_loss": 0.15552587062120438, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7975004927677833, + "val_dice_gain": null, + "val_dice_loss": 0.23880493640899658, + "val_entropy": 0.0, + "val_iou": 0.7027251249530224, + "val_iou_gain": null, + "val_loss": 0.19716540724039078, + "val_refine_score": 0.553807255223433, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7044752325241393, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7024296857046114, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 2.060720203767703e-05, + "epoch": 77, + "epoch_seconds": 1.0216461061500013, + "grad_norm": 0.3147268159822984, + "lr": 9.926597487699464e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7024296857046114, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.036359795961867676, + "train_critic_loss": 0.0, + "train_dice": 0.8987080176811173, + "train_dice_loss": 0.10069012641906738, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8290942360982001, + "train_loss": 0.0685249614444646, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40359150436234953, + "val_biou_gain": null, + "val_ce_loss": 0.15833405405282974, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7975983759734213, + "val_dice_gain": null, + "val_dice_loss": 0.23833370208740234, + "val_entropy": 0.0, + "val_iou": 0.7024296857046114, + "val_iou_gain": null, + "val_loss": 0.19833388179540634, + "val_refine_score": 0.5530105950334805, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7044752325241393, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7040960101201372, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 1.900637270011264e-05, + "epoch": 78, + "epoch_seconds": 0.966597436927259, + "grad_norm": 0.3821964751590382, + "lr": 9.19778574212361e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7040960101201372, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0373629153790799, + "train_critic_loss": 0.0, + "train_dice": 0.8980150694502541, + "train_dice_loss": 0.10161863131956621, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8278554507092915, + "train_loss": 0.0694907737726515, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40647056056231956, + "val_biou_gain": null, + "val_ce_loss": 0.154392808675766, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7986440674837207, + "val_dice_gain": null, + "val_dice_loss": 0.23588675260543823, + "val_entropy": 0.0, + "val_iou": 0.7040960101201372, + "val_iou_gain": null, + "val_loss": 0.1951397806406021, + "val_refine_score": 0.5552832853412284, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7054185958119278, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7054185958119278, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 1.7465207413786256e-05, + "epoch": 79, + "epoch_seconds": 1.0499451230280101, + "grad_norm": 0.3109376904639331, + "lr": 8.496137330146485e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7054185958119278, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03825324401259422, + "train_critic_loss": 0.0, + "train_dice": 0.8931292163502155, + "train_dice_loss": 0.10069913755763661, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8240044835856227, + "train_loss": 0.06947619095444679, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.409986981452229, + "val_biou_gain": null, + "val_ce_loss": 0.15097447484731674, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7991663103176736, + "val_dice_gain": null, + "val_dice_loss": 0.23484477400779724, + "val_entropy": 0.0, + "val_iou": 0.7054185958119278, + "val_iou_gain": null, + "val_loss": 0.1929096281528473, + "val_refine_score": 0.5577027886320784, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7054185958119278, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7025885865325565, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 1.598522712276838e-05, + "epoch": 80, + "epoch_seconds": 0.9293432696722448, + "grad_norm": 0.2989849488843571, + "lr": 7.822344694039691e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7025885865325565, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03564177453517914, + "train_critic_loss": 0.0, + "train_dice": 0.8975295429389327, + "train_dice_loss": 0.09972172433679755, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8282116503128031, + "train_loss": 0.06768174977465109, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3999932760279427, + "val_biou_gain": null, + "val_ce_loss": 0.1583472639322281, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7978219706511869, + "val_dice_gain": null, + "val_dice_loss": 0.23506850004196167, + "val_entropy": 0.0, + "val_iou": 0.7025885865325565, + "val_iou_gain": null, + "val_loss": 0.19670788198709488, + "val_refine_score": 0.5512909312802496, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7054185958119278, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7050724693467135, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 1.4567892388926035e-05, + "epoch": 81, + "epoch_seconds": 0.895705820992589, + "grad_norm": 0.3617350323633714, + "lr": 7.1770727857870835e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7050724693467135, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.038052494722333824, + "train_critic_loss": 0.0, + "train_dice": 0.8950013061948952, + "train_dice_loss": 0.10073399543762207, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8269546330929475, + "train_loss": 0.06939324634996327, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4102507421872588, + "val_biou_gain": null, + "val_ce_loss": 0.1491267867386341, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7993178828655825, + "val_dice_gain": null, + "val_dice_loss": 0.23511821031570435, + "val_entropy": 0.0, + "val_iou": 0.7050724693467135, + "val_iou_gain": null, + "val_loss": 0.19212249666452408, + "val_refine_score": 0.5576616057669862, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7054185958119278, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7039124274688245, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 1.3214601950524642e-05, + "epoch": 82, + "epoch_seconds": 0.990836454089731, + "grad_norm": 0.334355739029971, + "lr": 6.560958410857492e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7039124274688245, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.036454776640642776, + "train_critic_loss": 0.0, + "train_dice": 0.8932615296772068, + "train_dice_loss": 0.10082508217204701, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8230612083856209, + "train_loss": 0.06863992999900471, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4010352921061701, + "val_biou_gain": null, + "val_ce_loss": 0.15242505818605423, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.79923970334564, + "val_dice_gain": null, + "val_dice_loss": 0.2338169515132904, + "val_entropy": 0.0, + "val_iou": 0.7039124274688245, + "val_iou_gain": null, + "val_loss": 0.19312100112438202, + "val_refine_score": 0.5524738597874973, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7054185958119278, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7028236469571921, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 1.1926691341842126e-05, + "epoch": 83, + "epoch_seconds": 0.9468458793126047, + "grad_norm": 0.34106841818852857, + "lr": 5.974609599754563e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7028236469571921, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03756874935193495, + "train_critic_loss": 0.0, + "train_dice": 0.8954306617380148, + "train_dice_loss": 0.10349246588620273, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.82565859626183, + "train_loss": 0.07053060761906883, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.3989100498677298, + "val_biou_gain": null, + "val_ce_loss": 0.16368016600608826, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7985373054734157, + "val_dice_gain": null, + "val_dice_loss": 0.2359912395477295, + "val_entropy": 0.0, + "val_iou": 0.7028236469571921, + "val_iou_gain": null, + "val_loss": 0.19983570277690887, + "val_refine_score": 0.550866848412461, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.706254138991249, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 1.0705431575157994e-05, + "epoch": 84, + "epoch_seconds": 0.9917306778952479, + "grad_norm": 0.31488693302327936, + "lr": 5.418605007964139e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.706254138991249, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03706781870939515, + "train_critic_loss": 0.0, + "train_dice": 0.8965428677022771, + "train_dice_loss": 0.09983877702192827, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8260867543458216, + "train_loss": 0.06845329803499309, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4102958843337459, + "val_biou_gain": null, + "val_ce_loss": 0.15400882065296173, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8004683297631955, + "val_dice_gain": null, + "val_dice_loss": 0.23596560955047607, + "val_entropy": 0.0, + "val_iou": 0.706254138991249, + "val_iou_gain": null, + "val_loss": 0.1949872076511383, + "val_refine_score": 0.5582750116624975, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7055525596538014, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 9.552027886417447e-06, + "epoch": 85, + "epoch_seconds": 1.0312606352381408, + "grad_norm": 0.3436755361882123, + "lr": 4.893493344891049e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7055525596538014, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03598506934940815, + "train_critic_loss": 0.0, + "train_dice": 0.8960216040409404, + "train_dice_loss": 0.09926186366514726, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8262374449731889, + "train_loss": 0.06762346557595512, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4057623554306254, + "val_biou_gain": null, + "val_ce_loss": 0.15930674970149994, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8000616419986635, + "val_dice_gain": null, + "val_dice_loss": 0.23508980870246887, + "val_entropy": 0.0, + "val_iou": 0.7055525596538014, + "val_iou_gain": null, + "val_loss": 0.1971982792019844, + "val_refine_score": 0.5556574575422134, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7058759122153486, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 8.467618545809162e-06, + "epoch": 86, + "epoch_seconds": 1.0542714148759842, + "grad_norm": 0.325835872780193, + "lr": 4.399792832349251e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7058759122153486, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.034646501087329605, + "train_critic_loss": 0.0, + "train_dice": 0.9010119855798838, + "train_dice_loss": 0.09659646316008134, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8313841893828079, + "train_loss": 0.06562148237770254, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4069015871789843, + "val_biou_gain": null, + "val_ce_loss": 0.15765833854675293, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8003335799375004, + "val_dice_gain": null, + "val_dice_loss": 0.23441022634506226, + "val_entropy": 0.0, + "val_iou": 0.7058759122153486, + "val_iou_gain": null, + "val_loss": 0.1960342824459076, + "val_refine_score": 0.5563887496971665, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7046916064343839, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 7.453273734429989e-06, + "epoch": 87, + "epoch_seconds": 1.0013185567222536, + "grad_norm": 0.3195144385099411, + "lr": 3.9379906931394354e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7046916064343839, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03621050715446472, + "train_critic_loss": 0.0, + "train_dice": 0.8991321993866154, + "train_dice_loss": 0.09768206964839589, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8299942729840253, + "train_loss": 0.0669462877241048, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40329022734756115, + "val_biou_gain": null, + "val_ce_loss": 0.15903862565755844, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7997904005141278, + "val_dice_gain": null, + "val_dice_loss": 0.23564943671226501, + "val_entropy": 0.0, + "val_iou": 0.7046916064343839, + "val_iou_gain": null, + "val_loss": 0.19734403491020203, + "val_refine_score": 0.5539909168909725, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.705364790580095, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 6.50999448814541e-06, + "epoch": 88, + "epoch_seconds": 1.052368282340467, + "grad_norm": 0.4146017242561687, + "lr": 3.5085426702189474e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.705364790580095, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.037415626204826614, + "train_critic_loss": 0.0, + "train_dice": 0.8949582338005808, + "train_dice_loss": 0.10349872979250821, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8249485629227552, + "train_loss": 0.07045717842199585, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4066353728842649, + "val_biou_gain": null, + "val_ce_loss": 0.16064578294754028, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.7999625733478309, + "val_dice_gain": null, + "val_dice_loss": 0.2363397181034088, + "val_entropy": 0.0, + "val_iou": 0.705364790580095, + "val_iou_gain": null, + "val_loss": 0.19849275052547455, + "val_refine_score": 0.55600008173218, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7055672753520856, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 5.638711709688054e-06, + "epoch": 89, + "epoch_seconds": 1.0577031448483467, + "grad_norm": 0.3003677576780319, + "lr": 3.111872576938535e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7055672753520856, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03458656810901382, + "train_critic_loss": 0.0, + "train_dice": 0.8972724005289083, + "train_dice_loss": 0.09772702780636874, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8286309482624394, + "train_loss": 0.06615679812702266, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4077691641346652, + "val_biou_gain": null, + "val_ce_loss": 0.16048403829336166, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.800156214624526, + "val_dice_gain": null, + "val_dice_loss": 0.23586535453796387, + "val_entropy": 0.0, + "val_iou": 0.7055672753520856, + "val_iou_gain": null, + "val_loss": 0.19817470014095306, + "val_refine_score": 0.5566682197433754, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.706254138991249, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7055712544163226, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 6, + "encoder_lr": 4.840285249969007e-06, + "epoch": 90, + "epoch_seconds": 0.9947684202343225, + "grad_norm": 0.26546034487811004, + "lr": 2.748371878789702e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7055712544163226, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03381006538190625, + "train_critic_loss": 0.0, + "train_dice": 0.9025650738632288, + "train_dice_loss": 0.09365944428877397, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8344840456946078, + "train_loss": 0.06373475559733131, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40561930708308586, + "val_biou_gain": null, + "val_ce_loss": 0.16016113758087158, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8005254076239547, + "val_dice_gain": null, + "val_dice_loss": 0.23516759276390076, + "val_entropy": 0.0, + "val_iou": 0.7055712544163226, + "val_iou_gain": null, + "val_loss": 0.19766436517238617, + "val_refine_score": 0.5555952807497042, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7062849945914123, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7062849945914123, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 4.115503059508816e-06, + "epoch": 91, + "epoch_seconds": 0.943765333853662, + "grad_norm": 0.31347679414532403, + "lr": 2.41839930707555e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7062849945914123, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03593108735301278, + "train_critic_loss": 0.0, + "train_dice": 0.8961750954650392, + "train_dice_loss": 0.09719705039804633, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8292150769838086, + "train_loss": 0.0665640692141923, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40747591730659366, + "val_biou_gain": null, + "val_ce_loss": 0.15854304283857346, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8009352959286544, + "val_dice_gain": null, + "val_dice_loss": 0.23529386520385742, + "val_entropy": 0.0, + "val_iou": 0.7062849945914123, + "val_iou_gain": null, + "val_loss": 0.19691845774650574, + "val_refine_score": 0.5568804559490029, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7062849945914123, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7062651395980047, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 3.4650804108254454e-06, + "epoch": 92, + "epoch_seconds": 0.9464006349444389, + "grad_norm": 0.285667745904489, + "lr": 2.1222805048862866e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7062651395980047, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.034659177234227005, + "train_critic_loss": 0.0, + "train_dice": 0.8980960600035209, + "train_dice_loss": 0.0969332294030623, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8302040563792155, + "train_loss": 0.06579620492729274, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4071997183255698, + "val_biou_gain": null, + "val_ce_loss": 0.1593063846230507, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8007395373123262, + "val_dice_gain": null, + "val_dice_loss": 0.23557785153388977, + "val_entropy": 0.0, + "val_iou": 0.7062651395980047, + "val_iou_gain": null, + "val_loss": 0.19744212180376053, + "val_refine_score": 0.5567324289617872, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7062849945914123, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7058185396468475, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 2.8896591925466605e-06, + "epoch": 93, + "epoch_seconds": 1.0292423921637237, + "grad_norm": 0.3026790415698832, + "lr": 1.860307705728813e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7058185396468475, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03549215366894549, + "train_critic_loss": 0.0, + "train_dice": 0.8999042187756807, + "train_dice_loss": 0.09715792265805331, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8322058141504208, + "train_loss": 0.06632503833283078, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4065026074758327, + "val_biou_gain": null, + "val_ce_loss": 0.16268520057201385, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8004481556506176, + "val_dice_gain": null, + "val_dice_loss": 0.23568952083587646, + "val_entropy": 0.0, + "val_iou": 0.7058185396468475, + "val_iou_gain": null, + "val_loss": 0.19918736815452576, + "val_refine_score": 0.5561605735613401, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7069892349333782, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 0, + "encoder_lr": 2.389807275943463e-06, + "epoch": 94, + "epoch_seconds": 1.0548266167752445, + "grad_norm": 0.3058235564015128, + "lr": 1.6327394451275419e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7069892349333782, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03609582527794621, + "train_critic_loss": 0.0, + "train_dice": 0.8992456522668975, + "train_dice_loss": 0.09726671197197655, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8305590785061296, + "train_loss": 0.0666812692176212, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40786567076645236, + "val_biou_gain": null, + "val_ce_loss": 0.1614460051059723, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8012584956975002, + "val_dice_gain": null, + "val_dice_loss": 0.23496001958847046, + "val_entropy": 0.0, + "val_iou": 0.7069892349333782, + "val_iou_gain": null, + "val_loss": 0.19820301234722137, + "val_refine_score": 0.5574274528499152, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7064042644041154, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 1, + "encoder_lr": 1.9660179545097084e-06, + "epoch": 95, + "epoch_seconds": 0.9039892312139273, + "grad_norm": 0.2875202474269, + "lr": 1.4398003054810462e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7064042644041154, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03568154759705067, + "train_critic_loss": 0.0, + "train_dice": 0.9013047499340144, + "train_dice_loss": 0.09673144600608131, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8346132628287574, + "train_loss": 0.06620649756355719, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4077445336869782, + "val_biou_gain": null, + "val_ce_loss": 0.15949037671089172, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8006828365599945, + "val_dice_gain": null, + "val_dice_loss": 0.2346353530883789, + "val_entropy": 0.0, + "val_iou": 0.7064042644041154, + "val_iou_gain": null, + "val_loss": 0.19706286489963531, + "val_refine_score": 0.5570743990455468, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7059275485164238, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 2, + "encoder_lr": 1.6187094571409202e-06, + "epoch": 96, + "epoch_seconds": 0.9072170536965132, + "grad_norm": 0.3500392897562547, + "lr": 1.281680694426321e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7059275485164238, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.036078813231804154, + "train_critic_loss": 0.0, + "train_dice": 0.8988336535709746, + "train_dice_loss": 0.09792574427344582, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8301503977684732, + "train_loss": 0.06700227951461618, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4045030336502289, + "val_biou_gain": null, + "val_ce_loss": 0.16198715567588806, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.800796946670169, + "val_dice_gain": null, + "val_dice_loss": 0.23475047945976257, + "val_entropy": 0.0, + "val_iou": 0.7059275485164238, + "val_iou_gain": null, + "val_loss": 0.19836881756782532, + "val_refine_score": 0.5552152910833263, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7059140611345828, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 3, + "encoder_lr": 1.3482245353929428e-06, + "epoch": 97, + "epoch_seconds": 0.929804784245789, + "grad_norm": 0.2867604846304113, + "lr": 1.1585366569294675e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7059140611345828, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03422856330871582, + "train_critic_loss": 0.0, + "train_dice": 0.9005651508801684, + "train_dice_loss": 0.09579588066447865, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8319155015483358, + "train_loss": 0.06501222198659723, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4075068439186676, + "val_biou_gain": null, + "val_ce_loss": 0.1591881886124611, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8006356065282332, + "val_dice_gain": null, + "val_dice_loss": 0.23439031839370728, + "val_entropy": 0.0, + "val_iou": 0.7059140611345828, + "val_iou_gain": null, + "val_loss": 0.19678925722837448, + "val_refine_score": 0.5567104525266252, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7066401057698237, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 4, + "encoder_lr": 1.1548301252275082e-06, + "epoch": 98, + "epoch_seconds": 0.9890142818912864, + "grad_norm": 0.3232129893519662, + "lr": 1.0704897212881382e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7066401057698237, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03628282164308158, + "train_critic_loss": 0.0, + "train_dice": 0.8958721747039927, + "train_dice_loss": 0.0975758812644265, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8281070510373918, + "train_loss": 0.06692935221574524, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40789272334201365, + "val_biou_gain": null, + "val_ce_loss": 0.1589525192975998, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8010648991232713, + "val_dice_gain": null, + "val_dice_loss": 0.2347494661808014, + "val_entropy": 0.0, + "val_iou": 0.7066401057698237, + "val_iou_gain": null, + "val_loss": 0.1968509927392006, + "val_refine_score": 0.5572664145559187, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7060211312492137, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 5, + "encoder_lr": 1.038717083578654e-06, + "epoch": 99, + "epoch_seconds": 0.9245679657906294, + "grad_norm": 0.30327627740123053, + "lr": 1.0176267791977734e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7060211312492137, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.0352504871446978, + "train_critic_loss": 0.0, + "train_dice": 0.8983059183689626, + "train_dice_loss": 0.0968209288337014, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8306289177197612, + "train_loss": 0.0660357079045339, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.40706355474522604, + "val_biou_gain": null, + "val_ce_loss": 0.15984318405389786, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8006407543050387, + "val_dice_gain": null, + "val_dice_loss": 0.2347676157951355, + "val_entropy": 0.0, + "val_iou": 0.7060211312492137, + "val_iou_gain": null, + "val_loss": 0.19730539619922638, + "val_refine_score": 0.5565423429972198, + "val_reward": 0.0, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_monitor_value": 0.7061828459851853, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "early_stopping_wait": 6, + "encoder_lr": 1e-06, + "epoch": 100, + "epoch_seconds": 0.867781916167587, + "grad_norm": 0.30140452086925507, + "lr": 1e-06, + "selection_metric_name": "val_iou", + "selection_metric_value": 0.7061828459851853, + "train_action_distribution": null, + "train_actor_loss": 0.0, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.0, + "train_ce_loss": 0.03501432964747602, + "train_critic_loss": 0.0, + "train_dice": 0.8992373274787105, + "train_dice_loss": 0.09696769172495062, + "train_effective_steps": 0.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8319954861892346, + "train_loss": 0.06599101187153296, + "train_mask_delta_mean": 0.0, + "train_mean_reward": 0.0, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 0.0, + "train_value_pred_error": 0.0, + "val_actor_loss": 0.0, + "val_binary_flips_correct_pct": null, + "val_binary_flips_total_pct": null, + "val_binary_flips_wrong_pct": null, + "val_biou": 0.4061955886256138, + "val_biou_gain": null, + "val_ce_loss": 0.1610725000500679, + "val_critic_loss": 0.0, + "val_decoder_biou": null, + "val_decoder_dice": null, + "val_decoder_iou": null, + "val_dice": 0.8007181844053196, + "val_dice_gain": null, + "val_dice_loss": 0.235629141330719, + "val_entropy": 0.0, + "val_iou": 0.7061828459851853, + "val_iou_gain": null, + "val_loss": 0.19835082441568375, + "val_refine_score": 0.5561892173053995, + "val_reward": 0.0, + "validated_this_epoch": true + } +] \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/low_iou_samples.csv b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/low_iou_samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..6577ebad26366a2ca24898c7feba3f34b1affb55 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/low_iou_samples.csv @@ -0,0 +1,4 @@ +sample_id +BUSI_0157_M +BUSI_0243_B +BUSI_0201_B diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/run_config.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/run_config.json new file mode 100644 index 0000000000000000000000000000000000000000..ca87cc9d09ef49ba4e14e0719c10bdf2a4a5a910 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/run_config.json @@ -0,0 +1,70 @@ +{ + "backbone_family": "smp", + "base_split_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/splits/phase_002.json", + "best_checkpoint_metric_name": "val_iou", + "best_checkpoint_metrics": { + "2": "val_iou", + "3": "val_refine_score" + }, + "critic_loss_weight": 0.5, + "data_root": "/workspace/BUSI_with_classes", + "dataset_name": "BUSI_with_classes", + "dataset_percent": 1.0, + "dataset_split_policy": "stratified", + "dataset_splits_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/splits/phase_002.json", + "dropout_p": 0.24913407839085008, + "early_stopping_min_delta": 0.0, + "early_stopping_mode": "auto", + "early_stopping_monitor": "auto", + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "encoder_lr": 0.0001579273357461776, + "entropy_lr": 0.0003, + "evaluation_checkpoint_mode": "best", + "execution_mode": "train_eval", + "folds_experiment_name": "stratified_holdout_v1", + "gamma": 0.95, + "grad_clip_norm": 6.0, + "head_lr": 0.0007244452116785358, + "max_epochs": 100, + "normalization_cache_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/norm_stats_BUSI_with_classes_stratified_80_10_10_100pct_phase002_repeat01.json", + "percent_sampling_mode": "incremental", + "phase_count": 10, + "phase_index": 2, + "phase_test_fold_index": 2, + "phase_val_fold_index": 3, + "project_dir": "/workspace", + "run_name": "phase=002 | repeat=01 | strategy=2 | pct=100%", + "run_type": "final", + "save_history_incrementally": false, + "scheduler_factor": 0.5, + "scheduler_min_lr": 1e-05, + "scheduler_patience": 5, + "scheduler_threshold": 0.001, + "selected_split_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/subsets/phase_002_pct_100_repeat_01.json", + "smp_decoder_type": "UPerNet", + "smp_encoder_depth": 5, + "smp_encoder_name": "tu-pvt_v2_b2", + "smp_encoder_proj_dim": 192, + "smp_encoder_weights": "imagenet", + "split_generation_mode": "fixed_stratified_phases_8_1_1", + "split_repeat_index": 2, + "split_seed": 723450912, + "split_type": "80_10_10", + "strategy": 2, + "strategy2_checkpoint_mode": "best", + "subset_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/subsets/phase_002_pct_100_repeat_01.json", + "subset_repeat_index": 1, + "subset_sampling_source": "incremental_chain", + "subset_seed": 1072230984, + "tmax": 5, + "train_resume_mode": "off", + "train_resume_specific_checkpoint": "", + "train_subset_key": "100", + "train_subset_source": "incremental_chain", + "train_subset_variant": 1, + "vgg_feature_dilation": 1, + "vgg_feature_scales": 4, + "weight_decay": 8.416934971427066e-05, + "write_epoch_diagnostic": false +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/summary.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/summary.json new file mode 100644 index 0000000000000000000000000000000000000000..8164861969a831800484eb1a394a8fc53f2e9367 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/summary.json @@ -0,0 +1,28 @@ +{ + "best_epoch": 94, + "best_model_metric": 0.7069892349333782, + "best_model_metric_name": "val_iou", + "best_val_biou": 0.4102958843337459, + "best_val_biou_gain": 0.0, + "best_val_dice": 0.8012584956975002, + "best_val_iou": 0.7069892349333782, + "best_val_iou_gain": 0.0, + "device_used": "cuda", + "early_stopping_best_value": 0.7069892349333782, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_iou", + "early_stopping_patience": 30, + "early_stopping_start_epoch": 1, + "elapsed_seconds": 377.0015754699707, + "epochs_to_best_checkpoint": 94, + "final_epoch": 100, + "gpu_name": "NVIDIA A100 80GB PCIe", + "resumed": false, + "run_type": "final", + "seconds_per_epoch": 3.770015754699707, + "seconds_per_epoch_measured_mean": 3.4514503526501357, + "seconds_per_epoch_measured_std": 24.923594566076513, + "strategy": 2, + "time_to_best_seconds": 339.62266003200784 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/timing.csv b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/timing.csv new file mode 100644 index 0000000000000000000000000000000000000000..1c7f0c9a2b3a45b766513841af72cf79f9448d3d --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/timing.csv @@ -0,0 +1,2 @@ +scope,strategy,tmax,device,num_batches,num_samples,total_inference_ms,avg_batch_inference_ms,std_batch_inference_ms,avg_sample_inference_ms,std_sample_inference_ms,mean_per_image_inference_ms,std_per_image_inference_ms,mean_per_image_inference_seconds,std_per_image_inference_seconds +test_set_evaluation,2,5,cuda,2,65,85.153485,42.576742,17.412334,1.310054,0.101293,1.310054,0.101293,0.001310054,0.000101293 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/best.pt.meta.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/best.pt.meta.json new file mode 100644 index 0000000000000000000000000000000000000000..d371eac6cc5431d75c86fc8cf926bb3713ec45a6 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/best.pt.meta.json @@ -0,0 +1,59 @@ +{ + "backbone_family": "smp", + "checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/best.pt", + "dataset_percent": 1.0, + "epoch": 103, + "last_restore": { + "expected_run_type": null, + "restored_at_epoch": 103, + "restored_keys": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + } + }, + "run_type": "final", + "saved_keys": [ + "best_metric_name", + "best_metric_value", + "config", + "elapsed_seconds", + "epoch", + "epoch_metrics", + "history", + "model_state_dict", + "optimizer_state_dict", + "patience_counter", + "run_config", + "run_type", + "scheduler_state_dict" + ], + "state_presence": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + }, + "strategy": 3 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/latest.pt.meta.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/latest.pt.meta.json new file mode 100644 index 0000000000000000000000000000000000000000..8e5a73ea6fb77b1553f124c90a38a3491000d8f2 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/latest.pt.meta.json @@ -0,0 +1,39 @@ +{ + "backbone_family": "smp", + "checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/checkpoints/latest.pt", + "dataset_percent": 1.0, + "epoch": 120, + "run_type": "final", + "saved_keys": [ + "best_metric_name", + "best_metric_value", + "config", + "elapsed_seconds", + "epoch", + "epoch_metrics", + "history", + "model_state_dict", + "optimizer_state_dict", + "patience_counter", + "run_config", + "run_type", + "scheduler_state_dict" + ], + "state_presence": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + }, + "strategy": 3 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_results.xlsx b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_results.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..940f75610a6a0a34889126cea3ca2da36f834817 Binary files /dev/null and b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_results.xlsx differ diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_summary.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..b28dff4c48f33fae607dc8108e3b3fd16773b31f --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/evaluation_summary.json @@ -0,0 +1,4 @@ +{ + "mean_dice": 0.8018195033073425, + "mean_iou": 0.7207279205322266 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/history.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/history.json new file mode 100644 index 0000000000000000000000000000000000000000..1ce1e5ee07f493fcd0de1a565c8608ccdcf30918 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/history.json @@ -0,0 +1,9362 @@ +[ + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5565836657848875, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.000197150808455324, + "epoch": 1, + "epoch_seconds": 32.62006769934669, + "grad_norm": 1.5377312844449824, + "lr": 0.000197150808455324, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5565836657848875, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.0010548938404430044, + "mean_abs_delta": 0.000406802356585765, + "mean_delta": 0.00040070955103808296, + "near_zero_pct": 9.117921389530569, + "negative_pct": 2.1347738838564756, + "positive_pct": 88.74730664220723 + }, + "train_actor_loss": 3.687444595777058e-05, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": -3.687444595777058e-05, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.8954016919233049, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8284187499222646, + "train_loss": 0.0003687445502939888, + "train_mask_delta_mean": 0.00040693716569380325, + "train_mean_reward": -3.687444595777058e-05, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 9.090909090909092, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.0001160354486273718, + "val_binary_flips_correct_pct": 0.0006245631797640931, + "val_binary_flips_total_pct": 0.0016081566904105392, + "val_binary_flips_wrong_pct": 0.0009835935106464462, + "val_biou": 0.40827560333885693, + "val_biou_gain": -1.3984770095287757e-05, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.7990984990269602, + "val_dice_gain": -2.1885679318378592e-05, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.704891728230918, + "val_iou_gain": -3.948188745062087e-05, + "val_loss": -0.001160354486273718, + "val_refine_score": 0.5565836657848875, + "val_reward": 0.0001160354486273718, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5564556169857839, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019704999023999762, + "epoch": 2, + "epoch_seconds": 12.256178865674883, + "grad_norm": 4.8409442413936965, + "lr": 0.00019704999023999762, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5564556169857839, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.003734068437056108, + "mean_abs_delta": 0.0027086356782423204, + "mean_delta": -0.002687841468038889, + "near_zero_pct": 0.060746166282140995, + "negative_pct": 92.8651900454001, + "positive_pct": 7.074064362065903 + }, + "train_actor_loss": -0.002608152634262627, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.002608152634262627, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9004531133533943, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8330533538809403, + "train_loss": -0.02608152622865005, + "train_mask_delta_mean": 0.002709616314281117, + "train_mean_reward": 0.002608152634262627, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.04734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.002586986332971719, + "val_binary_flips_correct_pct": 0.06321177763097427, + "val_binary_flips_total_pct": 0.10638143502029718, + "val_binary_flips_wrong_pct": 0.043169657389322914, + "val_biou": 0.409579450303558, + "val_biou_gain": 0.0012898621946058064, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.7972143719078263, + "val_dice_gain": -0.0019060127984522612, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7033317836680097, + "val_iou_gain": -0.0015994264503588207, + "val_loss": -0.02586986332971719, + "val_refine_score": 0.5564556169857839, + "val_reward": 0.002586986332971719, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5558411616514065, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019688203665595106, + "epoch": 3, + "epoch_seconds": 12.244086754042655, + "grad_norm": 1.1992051222107627, + "lr": 0.00019688203665595106, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5558411616514065, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.015568126331676136, + "mean_abs_delta": 0.008335275088690898, + "mean_delta": -0.008325674052519555, + "near_zero_pct": 0.006784600175018857, + "negative_pct": 98.34220416166566, + "positive_pct": 1.6510119054993828 + }, + "train_actor_loss": -0.004235249319278141, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.004235249319278141, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.8980959596379536, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.829366053920115, + "train_loss": -0.04235249368304556, + "train_mask_delta_mean": 0.008333032781427557, + "train_mean_reward": 0.004235249319278141, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.004287574060526822, + "val_binary_flips_correct_pct": 0.10413375555300246, + "val_binary_flips_total_pct": 0.1808764887791054, + "val_binary_flips_wrong_pct": 0.07674273322610295, + "val_biou": 0.40945273267494997, + "val_biou_gain": 0.0011631445659977535, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.7961780171266798, + "val_dice_gain": -0.002942367579598759, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7022295906278632, + "val_iou_gain": -0.0027016194905054025, + "val_loss": -0.04287574060526822, + "val_refine_score": 0.5558411616514065, + "val_reward": 0.004287574060526822, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5594113669890561, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001966470628101813, + "epoch": 4, + "epoch_seconds": 12.254801527131349, + "grad_norm": 2.372483318502253, + "lr": 0.0001966470628101813, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5594113669890561, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.04713023792613636, + "mean_abs_delta": 0.011783895252103155, + "mean_delta": -0.011464091758667068, + "near_zero_pct": 0.0022804610874903697, + "negative_pct": 92.3770620064302, + "positive_pct": 7.620659796521068 + }, + "train_actor_loss": -0.006299372677693265, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.006299372677693265, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.8929024165272472, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8233019462352094, + "train_loss": -0.0629937272857536, + "train_mask_delta_mean": 0.01178464022549716, + "train_mean_reward": 0.006299372677693265, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5918560782447457, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.006593059180886485, + "val_binary_flips_correct_pct": 0.03412284103094363, + "val_binary_flips_total_pct": 0.05484188304227941, + "val_binary_flips_wrong_pct": 0.020719042011335786, + "val_biou": 0.4114887265140129, + "val_biou_gain": 0.0031991384050606975, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8010345445496324, + "val_dice_gain": 0.0019141598433538576, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7073340074640992, + "val_iou_gain": 0.0024027973457306784, + "val_loss": -0.06593059180886485, + "val_refine_score": 0.5594113669890561, + "val_reward": 0.006593059180886485, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5664754444019179, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001963452297420251, + "epoch": 5, + "epoch_seconds": 12.248972045723349, + "grad_norm": 2.386832118034363, + "lr": 0.0001963452297420251, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5664754444019179, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.08320201526988637, + "mean_abs_delta": 0.012360287660902197, + "mean_delta": -0.01119312488431619, + "near_zero_pct": 0.0005318237999641827, + "negative_pct": 91.51801250197671, + "positive_pct": 8.481457888741385 + }, + "train_actor_loss": -0.009759792446609274, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.00975979248894212, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.8986299613894148, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8299883546783186, + "train_loss": -0.09759792346845973, + "train_mask_delta_mean": 0.012363087047230114, + "train_mean_reward": 0.009759792446609274, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.009040937125973869, + "val_binary_flips_correct_pct": 0.11817707734949448, + "val_binary_flips_total_pct": 0.193936217064951, + "val_binary_flips_wrong_pct": 0.07575913971545649, + "val_biou": 0.4218233710025537, + "val_biou_gain": 0.013533782893601465, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8041597533961782, + "val_dice_gain": 0.005039368689899626, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.711127517801282, + "val_iou_gain": 0.00619630768291346, + "val_loss": -0.09040937125973869, + "val_refine_score": 0.5664754444019179, + "val_reward": 0.009040937125973869, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5691559211642088, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019597674431279043, + "epoch": 6, + "epoch_seconds": 12.25352571066469, + "grad_norm": 1.9828412532806396, + "lr": 0.00019597674431279043, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5691559211642088, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.09721790660511363, + "mean_abs_delta": 0.012004374600523575, + "mean_delta": -0.009429809330454604, + "near_zero_pct": 0.0004361829924319367, + "negative_pct": 91.27866022966124, + "positive_pct": 8.720905545421623 + }, + "train_actor_loss": -0.012271995091974863, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.01227199496497633, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9018681330273226, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8345212277718665, + "train_loss": -0.12271994623270902, + "train_mask_delta_mean": 0.01200381192294034, + "train_mean_reward": 0.012271995091974863, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4024621332064271, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.009507715283689322, + "val_binary_flips_correct_pct": 0.15179503197763483, + "val_binary_flips_total_pct": 0.2749199960746017, + "val_binary_flips_wrong_pct": 0.12312496409696691, + "val_biou": 0.42453755391307224, + "val_biou_gain": 0.016247965804120024, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8068770246133306, + "val_dice_gain": 0.007756639907051999, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7137742884153454, + "val_iou_gain": 0.008843078296976836, + "val_loss": -0.09507715283689322, + "val_refine_score": 0.5691559211642088, + "val_reward": 0.009507715283689322, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5680458903265949, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019554185906398426, + "epoch": 7, + "epoch_seconds": 12.300755520816892, + "grad_norm": 1.88376615264199, + "lr": 0.00019554185906398426, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5680458903265949, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.09899347478693182, + "mean_abs_delta": 0.01349202330774543, + "mean_delta": -0.009546178133777257, + "near_zero_pct": 0.00034518949573484036, + "negative_pct": 91.15941910581155, + "positive_pct": 8.840237837284803 + }, + "train_actor_loss": -0.01290026758021089, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.012900267664876579, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9070493966624444, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8411179902066851, + "train_loss": -0.12900267676873642, + "train_mask_delta_mean": 0.01349154385653409, + "train_mean_reward": 0.01290026758021089, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5208333488553762, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01016891104154638, + "val_binary_flips_correct_pct": 0.11307585473154105, + "val_binary_flips_total_pct": 0.22434907801011028, + "val_binary_flips_wrong_pct": 0.11127322327856924, + "val_biou": 0.4209567382313006, + "val_biou_gain": 0.01266715012234837, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8112857148576498, + "val_dice_gain": 0.012165330151371223, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7151350424218892, + "val_iou_gain": 0.010203832303520621, + "val_loss": -0.1016891104154638, + "val_refine_score": 0.5680458903265949, + "val_reward": 0.01016891104154638, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5721048330383265, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019504087204423308, + "epoch": 8, + "epoch_seconds": 12.335550110321492, + "grad_norm": 1.1277904456312007, + "lr": 0.00019504087204423308, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5721048330383265, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.09965376420454546, + "mean_abs_delta": 0.014885810436680913, + "mean_delta": -0.010080286756750535, + "near_zero_pct": 0.0005037056336153579, + "negative_pct": 91.09845371408896, + "positive_pct": 8.90104483643716 + }, + "train_actor_loss": -0.013709518810256586, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.013709518683258053, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9039217013482631, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8379753278433901, + "train_loss": -0.13709518787535754, + "train_mask_delta_mean": 0.014886335893110796, + "train_mean_reward": 0.013709518810256586, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8305180415680463, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.0106151704385411, + "val_binary_flips_correct_pct": 0.11866326425589768, + "val_binary_flips_total_pct": 0.23710213455499388, + "val_binary_flips_wrong_pct": 0.1184388702990962, + "val_biou": 0.4240583904008153, + "val_biou_gain": 0.01576880229186306, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8169585591827815, + "val_dice_gain": 0.017838174476502933, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7201512756758378, + "val_iou_gain": 0.015220065557469242, + "val_loss": -0.106151704385411, + "val_refine_score": 0.5721048330383265, + "val_reward": 0.0106151704385411, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5717842782393581, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019447412660501538, + "epoch": 9, + "epoch_seconds": 12.287543228361756, + "grad_norm": 2.0690600384365427, + "lr": 0.00019447412660501538, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5717842782393581, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.09991455078125, + "mean_abs_delta": 0.017384338414889167, + "mean_delta": -0.011900210679000751, + "near_zero_pct": 0.0001847988103391303, + "negative_pct": 90.92380275780505, + "positive_pct": 9.076014923101122 + }, + "train_actor_loss": -0.012764795624889302, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.012764795624889302, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9028545746471428, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8356307575659035, + "train_loss": -0.12764795869588852, + "train_mask_delta_mean": 0.01738184148615057, + "train_mean_reward": 0.012764795624889302, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5227528808807785, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.010782779325381853, + "val_binary_flips_correct_pct": 0.10068930831609987, + "val_binary_flips_total_pct": 0.18865173938227636, + "val_binary_flips_wrong_pct": 0.08796243106617647, + "val_biou": 0.4269173440919821, + "val_biou_gain": 0.018627755983029903, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.809337162303757, + "val_dice_gain": 0.01021677759747841, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7166512123867339, + "val_iou_gain": 0.011720002268365337, + "val_loss": -0.10782779325381853, + "val_refine_score": 0.5717842782393581, + "val_reward": 0.010782779325381853, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5731144116649685, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019384201116534564, + "epoch": 10, + "epoch_seconds": 12.3562189838849, + "grad_norm": 1.3123182979497043, + "lr": 0.00019384201116534564, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5731144116649685, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.018527232808992267, + "mean_delta": -0.01180063442073085, + "near_zero_pct": 0.0001626948121921404, + "negative_pct": 90.7392607493834, + "positive_pct": 9.26057913933288 + }, + "train_actor_loss": -0.014184845295734373, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014184845211068685, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9082612209132312, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8439096775326028, + "train_loss": -0.14184845171191476, + "train_mask_delta_mean": 0.018520008433948864, + "train_mean_reward": 0.014184845295734373, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01145244954386726, + "val_binary_flips_correct_pct": 0.13387343462775736, + "val_binary_flips_total_pct": 0.24354972091375615, + "val_binary_flips_wrong_pct": 0.10967628628599878, + "val_biou": 0.4267576003158349, + "val_biou_gain": 0.018468012206882656, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8161817699019401, + "val_dice_gain": 0.017061385195661583, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7194712230141022, + "val_iou_gain": 0.01454001289573359, + "val_loss": -0.1145244954386726, + "val_refine_score": 0.5731144116649685, + "val_reward": 0.01145244954386726, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5838825050479988, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019314495894557135, + "epoch": 11, + "epoch_seconds": 12.263047863729298, + "grad_norm": 0.7014381072737954, + "lr": 0.00019314495894557135, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5838825050479988, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.01981373158791526, + "mean_delta": -0.013267936767078936, + "near_zero_pct": 4.045891121119315e-05, + "negative_pct": 90.83423269065943, + "positive_pct": 9.165729116648436 + }, + "train_actor_loss": -0.014447221822262112, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014447221568265046, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9089089291314456, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.843819716044242, + "train_loss": -0.14447221566330304, + "train_mask_delta_mean": 0.019810069691051136, + "train_mean_reward": 0.014447221822262112, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4024621332064271, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012385716225253418, + "val_binary_flips_correct_pct": 0.12233958524816177, + "val_binary_flips_total_pct": 0.22632374482996326, + "val_binary_flips_wrong_pct": 0.10398415958180147, + "val_biou": 0.4401643351432088, + "val_biou_gain": 0.03187474703425658, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8201112019812761, + "val_dice_gain": 0.02099081727499752, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7276006749527888, + "val_iou_gain": 0.022669464834420228, + "val_loss": -0.12385716225253418, + "val_refine_score": 0.5838825050479988, + "val_reward": 0.012385716225253418, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5824405330138016, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001923834476704654, + "epoch": 12, + "epoch_seconds": 12.355446564033628, + "grad_norm": 0.7092268683693626, + "lr": 0.0001923834476704654, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5824405330138016, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.019225054039535196, + "mean_delta": -0.011867368868975476, + "near_zero_pct": 2.6009300055110625e-05, + "negative_pct": 90.77176045287739, + "positive_pct": 9.228215747597543 + }, + "train_actor_loss": -0.014560007915447799, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014560007830782111, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9111032036925549, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8463927379445261, + "train_loss": -0.14560008455406537, + "train_mask_delta_mean": 0.019230235706676136, + "train_mean_reward": 0.014560007915447799, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5413083677095446, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012699612801952753, + "val_binary_flips_correct_pct": 0.1597161386527267, + "val_binary_flips_total_pct": 0.26277654311236215, + "val_binary_flips_wrong_pct": 0.10306040445963542, + "val_biou": 0.4397028001727063, + "val_biou_gain": 0.03141321206375408, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8176774893209997, + "val_dice_gain": 0.018557104614721154, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7251782658548969, + "val_iou_gain": 0.020247055736528297, + "val_loss": -0.12699612801952753, + "val_refine_score": 0.5824405330138016, + "val_reward": 0.012699612801952753, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.578730544619311, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019155799924181743, + "epoch": 13, + "epoch_seconds": 12.374865701887757, + "grad_norm": 0.8621701273051176, + "lr": 0.00019155799924181743, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.578730544619311, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.022076532075350933, + "mean_delta": -0.015131392516195774, + "near_zero_pct": 2.151820488258884e-05, + "negative_pct": 90.83426696333018, + "positive_pct": 9.16571371595968 + }, + "train_actor_loss": -0.014758045651019942, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014758045735685631, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.910338902634984, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8458201905919135, + "train_loss": -0.14758046242323788, + "train_mask_delta_mean": 0.02208501642400568, + "train_mean_reward": 0.014758045651019942, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01224945810099598, + "val_binary_flips_correct_pct": 0.14977548636642157, + "val_binary_flips_total_pct": 0.25331833783318014, + "val_binary_flips_wrong_pct": 0.10354285146675858, + "val_biou": 0.4357726484546408, + "val_biou_gain": 0.027483060345688592, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8134818285110764, + "val_dice_gain": 0.014361443804797869, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.721688440783981, + "val_iou_gain": 0.01675723066561241, + "val_loss": -0.1224945810099598, + "val_refine_score": 0.578730544619311, + "val_reward": 0.01224945810099598, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5844913737151778, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00019066917938074832, + "epoch": 14, + "epoch_seconds": 12.320464627817273, + "grad_norm": 1.0348991318182512, + "lr": 0.00019066917938074832, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5844913737151778, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.02498265690254894, + "mean_delta": -0.017001868373799054, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.73459756645289, + "positive_pct": 9.265390267087655 + }, + "train_actor_loss": -0.014386225170193773, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014386225170193773, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9061542807715919, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8411917949556297, + "train_loss": -0.1438622542402961, + "train_mask_delta_mean": 0.024985573508522728, + "train_mean_reward": 0.014386225170193773, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.30968469271267, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012628394480998395, + "val_binary_flips_correct_pct": 0.1577003329407935, + "val_binary_flips_total_pct": 0.27818866804534315, + "val_binary_flips_wrong_pct": 0.12048833510454963, + "val_biou": 0.44063322630991414, + "val_biou_gain": 0.03234363820096192, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.82239957858207, + "val_dice_gain": 0.02327919387579147, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7283495211204415, + "val_iou_gain": 0.023418311002072922, + "val_loss": -0.12628394480998395, + "val_refine_score": 0.5844913737151778, + "val_reward": 0.012628394480998395, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5796051086673975, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018971759723999335, + "epoch": 15, + "epoch_seconds": 12.293450188823044, + "grad_norm": 0.660989146340977, + "lr": 0.00018971759723999335, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5796051086673975, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.024495323760096322, + "mean_delta": -0.01603587056425485, + "near_zero_pct": 3.178914469840906e-05, + "negative_pct": 90.71475944735788, + "positive_pct": 9.285211258313872 + }, + "train_actor_loss": -0.01496404673414211, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.014964046903473487, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9058666558973779, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8433820245572846, + "train_loss": -0.1496404680338773, + "train_mask_delta_mean": 0.024494517933238636, + "train_mean_reward": 0.01496404673414211, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.7339015370234847, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012056818430210114, + "val_binary_flips_correct_pct": 0.1332264320523131, + "val_binary_flips_total_pct": 0.21894866344975492, + "val_binary_flips_wrong_pct": 0.08572223139744178, + "val_biou": 0.4374248842486288, + "val_biou_gain": 0.02913529613967658, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8124339000749645, + "val_dice_gain": 0.013313515368685969, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7217853330861662, + "val_iou_gain": 0.016854122967797647, + "val_loss": -0.12056818430210114, + "val_refine_score": 0.5796051086673975, + "val_reward": 0.012056818430210114, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5819150850342599, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018870390498641916, + "epoch": 16, + "epoch_seconds": 12.294487729202956, + "grad_norm": 0.5387614071369171, + "lr": 0.00018870390498641916, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5819150850342599, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.025069519496438177, + "mean_delta": -0.017106473392976277, + "near_zero_pct": 4.623875598368117e-05, + "negative_pct": 90.85303314707495, + "positive_pct": 9.146922699768435 + }, + "train_actor_loss": -0.01516496935437317, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.01516496943903886, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9092770545465494, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8464018330901609, + "train_loss": -0.151649686423215, + "train_mask_delta_mean": 0.025077126242897728, + "train_mean_reward": 0.01516496935437317, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8305180415680463, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012415377037541475, + "val_binary_flips_correct_pct": 0.13079923741957722, + "val_binary_flips_total_pct": 0.21987615847120098, + "val_binary_flips_wrong_pct": 0.08907692105162376, + "val_biou": 0.44011928428814556, + "val_biou_gain": 0.031829696179193345, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8135386068305267, + "val_dice_gain": 0.014418222124248148, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7237108857803742, + "val_iou_gain": 0.018779675662005668, + "val_loss": -0.12415377037541475, + "val_refine_score": 0.5819150850342599, + "val_reward": 0.012415377037541475, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5857124304006381, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018762879735406137, + "epoch": 17, + "epoch_seconds": 12.294142845086753, + "grad_norm": 0.5478619553826072, + "lr": 0.00018762879735406137, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5857124304006381, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.023618536175821315, + "mean_delta": -0.015135581023059785, + "near_zero_pct": 2.167441692790817e-05, + "negative_pct": 90.77470079064369, + "positive_pct": 9.225279736247929 + }, + "train_actor_loss": -0.015475684394252974, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015475684309587285, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9095254124192913, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8464794603897219, + "train_loss": -0.15475684539838272, + "train_mask_delta_mean": 0.023624766956676136, + "train_mean_reward": 0.015475684394252974, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6647983396595175, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013197410880820826, + "val_binary_flips_correct_pct": 0.14179080140356923, + "val_binary_flips_total_pct": 0.2545749439912684, + "val_binary_flips_wrong_pct": 0.11278414258769914, + "val_biou": 0.44256468055571413, + "val_biou_gain": 0.03427509244676191, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8205468908462317, + "val_dice_gain": 0.021426506139953116, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7288601802455621, + "val_iou_gain": 0.023928970127193527, + "val_loss": -0.13197410880820826, + "val_refine_score": 0.5857124304006381, + "val_reward": 0.013197410880820826, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.582411319341873, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018649301116798828, + "epoch": 18, + "epoch_seconds": 12.354941512923688, + "grad_norm": 0.6229432062669233, + "lr": 0.00018649301116798828, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.582411319341873, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.028929202690381895, + "mean_delta": -0.019872610033913093, + "near_zero_pct": 4.377841740031065e-05, + "negative_pct": 90.72003520347856, + "positive_pct": 9.27992333573374 + }, + "train_actor_loss": -0.01505431775409637, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.01505431775409637, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9079647211508054, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8447176808133458, + "train_loss": -0.15054317360574548, + "train_mask_delta_mean": 0.028926502574573864, + "train_mean_reward": 0.01505431775409637, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.44981061946600676, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.012674075278482633, + "val_binary_flips_correct_pct": 0.14190673828125, + "val_binary_flips_total_pct": 0.26527853573069854, + "val_binary_flips_wrong_pct": 0.12337179744944853, + "val_biou": 0.4389363595164207, + "val_biou_gain": 0.030646771407468465, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.81726851617531, + "val_dice_gain": 0.018148131469031492, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7258862791673253, + "val_iou_gain": 0.02095506904895672, + "val_loss": -0.12674075278482633, + "val_refine_score": 0.582411319341873, + "val_reward": 0.012674075278482633, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5872003869934999, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018529732483931808, + "epoch": 19, + "epoch_seconds": 12.300396658014506, + "grad_norm": 0.5268510769714009, + "lr": 0.00018529732483931808, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5872003869934999, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03066443067721345, + "mean_delta": -0.021828525001183152, + "near_zero_pct": 1.3863816212216824e-05, + "negative_pct": 90.75452847914262, + "positive_pct": 9.245459921658039 + }, + "train_actor_loss": -0.015518060991201888, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015518061075867578, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9102034058992412, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8474303641118263, + "train_loss": -0.1551806086843664, + "train_mask_delta_mean": 0.030661843039772728, + "train_mean_reward": 0.015518060991201888, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6155303213745356, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013443741321680136, + "val_binary_flips_correct_pct": 0.15228495878331802, + "val_binary_flips_total_pct": 0.2665351418887868, + "val_binary_flips_wrong_pct": 0.11425018310546875, + "val_biou": 0.4437382640200839, + "val_biou_gain": 0.035448675911131655, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8228729848064931, + "val_dice_gain": 0.023752600100214516, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7306625099669157, + "val_iou_gain": 0.025731299848547162, + "val_loss": -0.13443741321680136, + "val_refine_score": 0.5872003869934999, + "val_reward": 0.013443741321680136, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.589747654423582, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001840425578317346, + "epoch": 20, + "epoch_seconds": 12.291272208094597, + "grad_norm": 0.44511088728904724, + "lr": 0.0001840425578317346, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.589747654423582, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.028596699280156332, + "mean_delta": -0.0198046583047306, + "near_zero_pct": 2.311937805643538e-05, + "negative_pct": 90.83110222762281, + "positive_pct": 9.16887718168172 + }, + "train_actor_loss": -0.015361744440352513, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015361744440352513, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9093289266037884, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8467464103140165, + "train_loss": -0.15361744165420532, + "train_mask_delta_mean": 0.028599132191051136, + "train_mean_reward": 0.015361744440352513, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5918560782447457, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013327751225006068, + "val_binary_flips_correct_pct": 0.15373977960324753, + "val_binary_flips_total_pct": 0.2553304036458333, + "val_binary_flips_wrong_pct": 0.10159062404258579, + "val_biou": 0.44951027298689156, + "val_biou_gain": 0.04122068487793934, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8187041463950139, + "val_dice_gain": 0.019583761688735324, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7299850358602725, + "val_iou_gain": 0.025053825741903957, + "val_loss": -0.13327751225006068, + "val_refine_score": 0.589747654423582, + "val_reward": 0.013327751225006068, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5957275314463877, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018272957009986775, + "epoch": 21, + "epoch_seconds": 12.31554041011259, + "grad_norm": 0.5345398621125654, + "lr": 0.00018272957009986775, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5957275314463877, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.030979929703541777, + "mean_delta": -0.021623308579860764, + "near_zero_pct": 1.7339533542326535e-05, + "negative_pct": 90.72038450024344, + "positive_pct": 9.279600302265449 + }, + "train_actor_loss": -0.015556861367299874, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015556861451965564, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.911162245794716, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8489543045189848, + "train_loss": -0.15556861053813587, + "train_mask_delta_mean": 0.030976728959517044, + "train_mean_reward": 0.015556861367299874, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6155303213745356, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013949136762676062, + "val_binary_flips_correct_pct": 0.15612583534390317, + "val_binary_flips_total_pct": 0.25734620935776653, + "val_binary_flips_wrong_pct": 0.10122037401386336, + "val_biou": 0.45476079625223936, + "val_biou_gain": 0.046471208143287146, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8256309228955243, + "val_dice_gain": 0.026510538189245758, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7366942666405359, + "val_iou_gain": 0.03176305652216738, + "val_loss": -0.13949136762676062, + "val_refine_score": 0.5957275314463877, + "val_reward": 0.013949136762676062, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5922031247497456, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00018135926149992384, + "epoch": 22, + "epoch_seconds": 12.380185302812606, + "grad_norm": 0.6006970757787878, + "lr": 0.00018135926149992384, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5922031247497456, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0280216359956698, + "mean_delta": -0.01880247339563952, + "near_zero_pct": 1.4879194313008073e-05, + "negative_pct": 90.667055005377, + "positive_pct": 9.332932379435409 + }, + "train_actor_loss": -0.015738682762771947, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015738682762771947, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9127154283873955, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8510882401258765, + "train_loss": -0.15738682584329086, + "train_mask_delta_mean": 0.028019298206676136, + "train_mean_reward": 0.015738682762771947, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.7812500232830644, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013630284964165185, + "val_binary_flips_correct_pct": 0.14498093548943014, + "val_binary_flips_total_pct": 0.2587037927964154, + "val_binary_flips_wrong_pct": 0.1137228573069853, + "val_biou": 0.4497809487167271, + "val_biou_gain": 0.04149136060777486, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8222506864890055, + "val_dice_gain": 0.023130301782726903, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7346253007827641, + "val_iou_gain": 0.029694090664395545, + "val_loss": -0.13630284964165185, + "val_refine_score": 0.5922031247497456, + "val_reward": 0.013630284964165185, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5943354499595148, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00017993257117296878, + "epoch": 23, + "epoch_seconds": 12.327129558194429, + "grad_norm": 0.4918499968268655, + "lr": 0.00017993257117296878, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5943354499595148, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.02953375488604334, + "mean_delta": -0.01984862930310721, + "near_zero_pct": 1.155968902821769e-05, + "negative_pct": 90.83208705891262, + "positive_pct": 9.167903229932893 + }, + "train_actor_loss": -0.015971867162906248, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015971867226405513, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9099281217138202, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8478837779234025, + "train_loss": -0.1597186719829386, + "train_mask_delta_mean": 0.029532692649147728, + "train_mean_reward": 0.015971867162906248, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8305180309848352, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014232378751330543, + "val_binary_flips_correct_pct": 0.16596177045036764, + "val_binary_flips_total_pct": 0.29617384368298105, + "val_binary_flips_wrong_pct": 0.13021207323261336, + "val_biou": 0.4526232326368691, + "val_biou_gain": 0.04433364452791688, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8231918814262804, + "val_dice_gain": 0.02407149672000186, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7360476672821606, + "val_iou_gain": 0.031116457163792077, + "val_loss": -0.14232378751330543, + "val_refine_score": 0.5943354499595148, + "val_reward": 0.014232378751330543, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5853177096910556, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001784504769012879, + "epoch": 24, + "epoch_seconds": 12.347786261234432, + "grad_norm": 0.431589584458958, + "lr": 0.0001784504769012879, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5853177096910556, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.030064319472082636, + "mean_delta": -0.020878072425892406, + "near_zero_pct": 2.3548961084171342e-05, + "negative_pct": 90.75451249426061, + "positive_pct": 9.24546630545096 + }, + "train_actor_loss": -0.01597267982279763, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.0, + "train_biou_delta_mean": 0.015972679568800562, + "train_ce_loss": 0.0, + "train_critic_loss": 0.0, + "train_dice": 0.9101966006314571, + "train_dice_loss": 0.0, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8492018072578413, + "train_loss": -0.15972679988904434, + "train_mask_delta_mean": 0.030068137428977272, + "train_mean_reward": 0.01597267982279763, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8049242537130009, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013204693746956764, + "val_binary_flips_correct_pct": 0.16590193206188725, + "val_binary_flips_total_pct": 0.3220277674057904, + "val_binary_flips_wrong_pct": 0.15612583534390317, + "val_biou": 0.4416997339271791, + "val_biou_gain": 0.03341014581822688, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8218780168423785, + "val_dice_gain": 0.022757632136099937, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7289356854549319, + "val_iou_gain": 0.024004475336563358, + "val_loss": -0.13204693746956764, + "val_refine_score": 0.5853177096910556, + "val_reward": 0.013204693746956764, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.600504273757412, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00017691399443826278, + "epoch": 25, + "epoch_seconds": 12.343883140012622, + "grad_norm": 0.455084811557423, + "lr": 0.00017691399443826278, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.600504273757412, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.028313376305794172, + "mean_delta": -0.018683311688205737, + "near_zero_pct": 3.82719432226705e-05, + "negative_pct": 90.71249074556611, + "positive_pct": 9.287473229183393 + }, + "train_actor_loss": -0.01573654086630747, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.4, + "train_biou_delta_mean": 0.01573654103563885, + "train_ce_loss": 0.14480882476676593, + "train_critic_loss": 0.0, + "train_dice": 0.911979501427957, + "train_dice_loss": 0.06231082569469105, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8489886304815188, + "train_loss": -0.11594148522073572, + "train_mask_delta_mean": 0.02831060236150568, + "train_mean_reward": 0.01573654086630747, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014739705344254617, + "val_binary_flips_correct_pct": 0.19133324716605393, + "val_binary_flips_total_pct": 0.3283070582969516, + "val_binary_flips_wrong_pct": 0.13697381113089768, + "val_biou": 0.461459938229497, + "val_biou_gain": 0.053170350120544774, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8276930395742288, + "val_dice_gain": 0.028572654867950242, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7395486092853271, + "val_iou_gain": 0.034617399166958496, + "val_loss": -0.14739705344254617, + "val_refine_score": 0.600504273757412, + "val_reward": 0.014739705344254617, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5976186111672254, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00017532417681222453, + "epoch": 26, + "epoch_seconds": 12.353887136094272, + "grad_norm": 0.4633127315477891, + "lr": 0.00017532417681222453, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5976186111672254, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0334829822267321, + "mean_delta": -0.024159972301938316, + "near_zero_pct": 1.8784494670853746e-05, + "negative_pct": 90.74110795151104, + "positive_pct": 9.258875572545962 + }, + "train_actor_loss": -0.015860728657550928, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.3733333333333334, + "train_biou_delta_mean": 0.015860728636384505, + "train_ce_loss": 0.15293611721559006, + "train_critic_loss": 0.0, + "train_dice": 0.9068381330706975, + "train_dice_loss": 0.06548911333084106, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8456287936311745, + "train_loss": -0.11783457547426224, + "train_mask_delta_mean": 0.03348194469105114, + "train_mean_reward": 0.015860728657550928, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.970643968321383, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014555271445715334, + "val_binary_flips_correct_pct": 0.17781351126876532, + "val_binary_flips_total_pct": 0.3216649971756281, + "val_binary_flips_wrong_pct": 0.14385148590686275, + "val_biou": 0.4576223754807751, + "val_biou_gain": 0.049332787371822895, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8251514862873163, + "val_dice_gain": 0.02603110158103772, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7376148468536756, + "val_iou_gain": 0.03268363673530705, + "val_loss": -0.14555271445715334, + "val_refine_score": 0.5976186111672254, + "val_reward": 0.014555271445715334, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5955636057729319, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001736821136047609, + "epoch": 27, + "epoch_seconds": 12.366395054850727, + "grad_norm": 0.5870197550816969, + "lr": 0.0001736821136047609, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5955636057729319, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03427550334229388, + "mean_delta": -0.0252756195735525, + "near_zero_pct": 1.5894572413799324e-05, + "negative_pct": 90.79993800683455, + "positive_pct": 9.200048124925656 + }, + "train_actor_loss": -0.015780665472559265, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.3466666666666667, + "train_biou_delta_mean": 0.015780665726556332, + "train_ce_loss": 0.14801026338880713, + "train_critic_loss": 0.0, + "train_dice": 0.907277495530584, + "train_dice_loss": 0.06408829580653798, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8449873906355032, + "train_loss": -0.12104290588335558, + "train_mask_delta_mean": 0.03427956321022727, + "train_mean_reward": 0.015780665472559265, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.9469697251915932, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014210383662430104, + "val_binary_flips_correct_pct": 0.17127242742800247, + "val_binary_flips_total_pct": 0.2722497079886642, + "val_binary_flips_wrong_pct": 0.10097728056066177, + "val_biou": 0.4559183148053464, + "val_biou_gain": 0.047628726696394175, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8222503767773995, + "val_dice_gain": 0.023129992071120986, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7352088967405173, + "val_iou_gain": 0.030277686622148692, + "val_loss": -0.14210383662430104, + "val_refine_score": 0.5955636057729319, + "val_reward": 0.014210383662430104, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.591220255672112, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00017198893020397134, + "epoch": 28, + "epoch_seconds": 12.375854149926454, + "grad_norm": 0.491730199618773, + "lr": 0.00017198893020397134, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.591220255672112, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0376863281073218, + "mean_delta": -0.02795872974886813, + "near_zero_pct": 1.5894572413799324e-05, + "negative_pct": 90.62911813909358, + "positive_pct": 9.370868415995078 + }, + "train_actor_loss": -0.01628781633913108, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.3200000000000001, + "train_biou_delta_mean": 0.016287816254465393, + "train_ce_loss": 0.14658421752127734, + "train_critic_loss": 0.0, + "train_dice": 0.9132627704636745, + "train_dice_loss": 0.06131699952212247, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8516853240075622, + "train_loss": -0.1296139664270661, + "train_mask_delta_mean": 0.03768504749644886, + "train_mean_reward": 0.01628781633913108, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013864192638720851, + "val_binary_flips_correct_pct": 0.1851511936561734, + "val_binary_flips_total_pct": 0.30881844314874385, + "val_binary_flips_wrong_pct": 0.12366724949257046, + "val_biou": 0.4522262229501733, + "val_biou_gain": 0.04393663484122107, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8185112744787688, + "val_dice_gain": 0.01939088977249026, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7302142883940508, + "val_iou_gain": 0.025283078275682214, + "val_loss": -0.13864192638720851, + "val_refine_score": 0.591220255672112, + "val_reward": 0.013864192638720851, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": false, + "early_stopping_best_value": null, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5943959079779391, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.0001702457870331824, + "epoch": 29, + "epoch_seconds": 12.371643285732716, + "grad_norm": 0.41372743248939514, + "lr": 0.0001702457870331824, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5943959079779391, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03251441739584235, + "mean_delta": -0.022107019067995927, + "near_zero_pct": 7.224805642636056e-06, + "negative_pct": 90.80494398420507, + "positive_pct": 9.195051012052732 + }, + "train_actor_loss": -0.016254573472245036, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.2933333333333334, + "train_biou_delta_mean": 0.016254573472245036, + "train_ce_loss": 0.13947877355597235, + "train_critic_loss": 0.0, + "train_dice": 0.9133477789191546, + "train_dice_loss": 0.05933809280395508, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8524645345312771, + "train_loss": -0.13338592851703818, + "train_mask_delta_mean": 0.03250815651633523, + "train_mean_reward": 0.016254573472245036, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6628788076341152, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014064448841963895, + "val_binary_flips_correct_pct": 0.16536712646484375, + "val_binary_flips_total_pct": 0.2944497501148897, + "val_binary_flips_wrong_pct": 0.12908262365004597, + "val_biou": 0.45500523528132664, + "val_biou_gain": 0.04671564717237442, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8212923708072942, + "val_dice_gain": 0.022171986101015673, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7337865806745515, + "val_iou_gain": 0.028855370556182924, + "val_loss": -0.14064448841963895, + "val_refine_score": 0.5943959079779391, + "val_reward": 0.014064448841963895, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5869918261743539, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5869918261743539, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00016845387875565144, + "epoch": 30, + "epoch_seconds": 12.35485183307901, + "grad_norm": 0.49312038855119184, + "lr": 0.00016845387875565144, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5869918261743539, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03618096365508708, + "mean_delta": -0.026375529335134408, + "near_zero_pct": 3.4679066826273896e-05, + "negative_pct": 90.75385873967952, + "positive_pct": 9.246108858761461 + }, + "train_actor_loss": -0.01634708608079646, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.26666666666666666, + "train_biou_delta_mean": 0.016347085890298662, + "train_ce_loss": 0.14694700728763233, + "train_critic_loss": 0.0, + "train_dice": 0.9100862788760524, + "train_dice_loss": 0.061836773698980156, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8488902995524901, + "train_loss": -0.1356330236250704, + "train_mask_delta_mean": 0.03618552468039773, + "train_mean_reward": 0.01634708608079646, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013731196406297386, + "val_binary_flips_correct_pct": 0.16384124755859375, + "val_binary_flips_total_pct": 0.2959905886182598, + "val_binary_flips_wrong_pct": 0.13214934105966608, + "val_biou": 0.44422873913812827, + "val_biou_gain": 0.03593915102917605, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.81893626429914, + "val_dice_gain": 0.019815879592861463, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7297549132105795, + "val_iou_gain": 0.024823703092210936, + "val_loss": -0.13731196406297386, + "val_refine_score": 0.5869918261743539, + "val_reward": 0.013731196406297386, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.5959816748197169, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5959816748197169, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00016661443345580398, + "epoch": 31, + "epoch_seconds": 12.308424912858754, + "grad_norm": 0.4113001227378845, + "lr": 0.00016661443345580398, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5959816748197169, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03402983458628031, + "mean_delta": -0.022726662308824332, + "near_zero_pct": 1.8198699597798456e-05, + "negative_pct": 90.78226611018181, + "positive_pct": 9.217718116600405 + }, + "train_actor_loss": -0.01650263509170393, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.24000000000000005, + "train_biou_delta_mean": 0.016502634922372552, + "train_ce_loss": 0.14222306487235156, + "train_critic_loss": 0.0, + "train_dice": 0.9131019878544364, + "train_dice_loss": 0.06089617989280007, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.85203426429521, + "train_loss": -0.14065204560756683, + "train_mask_delta_mean": 0.03403542258522727, + "train_mean_reward": 0.01650263509170393, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.7102272938936949, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014229315471311565, + "val_binary_flips_correct_pct": 0.19129584817325368, + "val_binary_flips_total_pct": 0.30464097565295645, + "val_binary_flips_wrong_pct": 0.11334512747970282, + "val_biou": 0.45665670116429946, + "val_biou_gain": 0.048367113055347244, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.822301712655765, + "val_dice_gain": 0.023181327949486463, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7353066484751342, + "val_iou_gain": 0.030375438356765594, + "val_loss": -0.14229315471311565, + "val_refine_score": 0.5959816748197169, + "val_reward": 0.014229315471311565, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.598504974843916, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.598504974843916, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00016472871179756623, + "epoch": 32, + "epoch_seconds": 12.334934842772782, + "grad_norm": 0.5679527656598524, + "lr": 0.00016472871179756623, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.598504974843916, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03198968530209227, + "mean_delta": -0.021654557235623626, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.81609371033582, + "positive_pct": 9.183893860741096 + }, + "train_actor_loss": -0.01624892132167588, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.21333333333333335, + "train_biou_delta_mean": 0.01624892132167588, + "train_ce_loss": 0.14684515581889587, + "train_critic_loss": 0.0, + "train_dice": 0.9128353757517998, + "train_dice_loss": 0.062498087232763115, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8499859156902108, + "train_loss": -0.14015926827083935, + "train_mask_delta_mean": 0.03198658336292614, + "train_mean_reward": 0.01624892132167588, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014555954723618925, + "val_binary_flips_correct_pct": 0.19989013671875, + "val_binary_flips_total_pct": 0.41927262848498775, + "val_binary_flips_wrong_pct": 0.21938249176623775, + "val_biou": 0.4592979939152695, + "val_biou_gain": 0.05100840580631727, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.826957086123519, + "val_dice_gain": 0.027836701417240484, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7377119557725625, + "val_iou_gain": 0.03278074565419398, + "val_loss": -0.14555954723618925, + "val_refine_score": 0.598504974843916, + "val_reward": 0.014555954723618925, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.599820668222111, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.599820668222111, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00016279800616036884, + "epoch": 33, + "epoch_seconds": 12.336511398199946, + "grad_norm": 0.46660937097939575, + "lr": 0.00016279800616036884, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.599820668222111, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.040483646518127483, + "mean_delta": -0.029961137312718412, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.80035063353452, + "positive_pct": 9.199639858508652 + }, + "train_actor_loss": -0.016516369277145383, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.1866666666666667, + "train_biou_delta_mean": 0.01651636893848263, + "train_ce_loss": 0.14260601387782532, + "train_critic_loss": 0.0, + "train_dice": 0.9144654543581662, + "train_dice_loss": 0.06033308397639881, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8537538744312345, + "train_loss": -0.14622271128676154, + "train_mask_delta_mean": 0.040496826171875, + "train_mean_reward": 0.016516369277145383, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.7121468259190972, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014414355617191177, + "val_binary_flips_correct_pct": 0.1844967112821691, + "val_binary_flips_total_pct": 0.3117093852922028, + "val_binary_flips_wrong_pct": 0.12721267401003372, + "val_biou": 0.4621231923107739, + "val_biou_gain": 0.053833604201821705, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8241457480861494, + "val_dice_gain": 0.025025363379870824, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7375181441334482, + "val_iou_gain": 0.032586934015079616, + "val_loss": -0.14414355617191177, + "val_refine_score": 0.599820668222111, + "val_reward": 0.014414355617191177, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6101079619991863, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00016082363975341467, + "epoch": 34, + "epoch_seconds": 12.320580966304988, + "grad_norm": 0.46328868107362225, + "lr": 0.00016082363975341467, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6101079619991863, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.034333592619408264, + "mean_delta": -0.023888880217617207, + "near_zero_pct": 6.209427541844806e-06, + "negative_pct": 90.76226990331303, + "positive_pct": 9.237726185132157 + }, + "train_actor_loss": -0.016903833335163654, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.16000000000000006, + "train_biou_delta_mean": 0.016903833081166587, + "train_ce_loss": 0.142258075827902, + "train_critic_loss": 0.0, + "train_dice": 0.9153624800372301, + "train_dice_loss": 0.06043355031446977, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8544924256557322, + "train_loss": -0.15282300927422263, + "train_mask_delta_mean": 0.03434059836647727, + "train_mean_reward": 0.016903833335163654, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015374443115433678, + "val_binary_flips_correct_pct": 0.1969730152803309, + "val_binary_flips_total_pct": 0.33716687969132964, + "val_binary_flips_wrong_pct": 0.1401938644109988, + "val_biou": 0.473322624630115, + "val_biou_gain": 0.06503303652116277, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8352081681072757, + "val_dice_gain": 0.036087783400997164, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7468932993682577, + "val_iou_gain": 0.04196208924988909, + "val_loss": -0.15374443115433678, + "val_refine_score": 0.6101079619991863, + "val_reward": 0.015374443115433678, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5969832020754372, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 0.00015880696570881722, + "epoch": 35, + "epoch_seconds": 12.301791550125927, + "grad_norm": 0.4907486005262895, + "lr": 0.00015880696570881722, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5969832020754372, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.031044194517149168, + "mean_delta": -0.0199288327077573, + "near_zero_pct": 6.209427541844806e-06, + "negative_pct": 90.69299244067885, + "positive_pct": 9.307003707032312 + }, + "train_actor_loss": -0.016231913507107783, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.13333333333333333, + "train_biou_delta_mean": 0.016231913422442092, + "train_ce_loss": 0.14511008967052808, + "train_critic_loss": 0.0, + "train_dice": 0.9098029026157458, + "train_dice_loss": 0.061396560885689476, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8486914008554262, + "train_loss": -0.14855202355168082, + "train_mask_delta_mean": 0.031039151278409092, + "train_mean_reward": 0.016231913507107783, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.828598509542644, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014233024288841989, + "val_binary_flips_correct_pct": 0.1760445389093137, + "val_binary_flips_total_pct": 0.3287932452033548, + "val_binary_flips_wrong_pct": 0.15274870629404105, + "val_biou": 0.4564493553400006, + "val_biou_gain": 0.04815976723104837, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8255445743321156, + "val_dice_gain": 0.026424189625837036, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7375170488108739, + "val_iou_gain": 0.03258583869250531, + "val_loss": -0.1423302428884199, + "val_refine_score": 0.5969832020754372, + "val_reward": 0.014233024288841989, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5907879198478351, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 0.00015674936615423155, + "epoch": 36, + "epoch_seconds": 12.319367107003927, + "grad_norm": 0.4752627069299871, + "lr": 0.00015674936615423155, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5907879198478351, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.035144786392761904, + "mean_delta": -0.02495381917635148, + "near_zero_pct": 1.3004650156744901e-05, + "negative_pct": 90.75763002038002, + "positive_pct": 9.242359616539694 + }, + "train_actor_loss": -0.016684114925489914, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.10666666666666669, + "train_biou_delta_mean": 0.0166841150101556, + "train_ce_loss": 0.141919652169401, + "train_critic_loss": 0.0, + "train_dice": 0.9131716682045538, + "train_dice_loss": 0.05960016358982433, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8525598711221988, + "train_loss": -0.15609342943538318, + "train_mask_delta_mean": 0.035139604048295456, + "train_mean_reward": 0.016684114925489914, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8708282395011999, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.013711452091229148, + "val_binary_flips_correct_pct": 0.1697540283203125, + "val_binary_flips_total_pct": 0.3154305850758272, + "val_binary_flips_wrong_pct": 0.14567655675551472, + "val_biou": 0.4492708324211911, + "val_biou_gain": 0.040981244312238874, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8204401853177711, + "val_dice_gain": 0.021319800611492523, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.732305007274479, + "val_iou_gain": 0.027373797156110435, + "val_loss": -0.13711452091229148, + "val_refine_score": 0.5907879198478351, + "val_reward": 0.013711452091229148, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6086467789646048, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 0.00015465225126561297, + "epoch": 37, + "epoch_seconds": 12.317498518154025, + "grad_norm": 0.4805647920478474, + "lr": 0.00015465225126561297, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6086467789646048, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03567467627792873, + "mean_delta": -0.025389260083267636, + "near_zero_pct": 1.5894572413799324e-05, + "negative_pct": 90.75660908764058, + "positive_pct": 9.243377509780906 + }, + "train_actor_loss": -0.016817390181875617, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.07999999999999997, + "train_biou_delta_mean": 0.016817390181875617, + "train_ce_loss": 0.14534888890656558, + "train_critic_loss": 0.0, + "train_dice": 0.9143934826772774, + "train_dice_loss": 0.061306655406951904, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8539838166472348, + "train_loss": -0.1599076877940785, + "train_mask_delta_mean": 0.03567088734019886, + "train_mean_reward": 0.016817390181875617, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5342700793831185, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015321318503993098, + "val_binary_flips_correct_pct": 0.20917256673177081, + "val_binary_flips_total_pct": 0.36015978046492036, + "val_binary_flips_wrong_pct": 0.15098721373314952, + "val_biou": 0.47275929566324343, + "val_biou_gain": 0.06446970755429121, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8332696801730208, + "val_dice_gain": 0.03414929546674228, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7445342622659662, + "val_iou_gain": 0.03960305214759763, + "val_loss": -0.15321318503993098, + "val_refine_score": 0.6086467789646048, + "val_reward": 0.015321318503993098, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6023673356179295, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 0.00015251705830075291, + "epoch": 38, + "epoch_seconds": 12.342918733600527, + "grad_norm": 0.5005798394029791, + "lr": 0.00015251705830075291, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6023673356179295, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03918909361924638, + "mean_delta": -0.028117157667028634, + "near_zero_pct": 1.6167943396215957e-05, + "negative_pct": 90.76591594652696, + "positive_pct": 9.234070109034127 + }, + "train_actor_loss": -0.016924706113121083, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.05333333333333332, + "train_biou_delta_mean": 0.01692470645178384, + "train_ce_loss": 0.14645918594165283, + "train_critic_loss": 0.0, + "train_dice": 0.9135734576798061, + "train_dice_loss": 0.06126933206211437, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8536441827781449, + "train_loss": -0.16370763291012158, + "train_mask_delta_mean": 0.0391845703125, + "train_mean_reward": 0.016924706113121083, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.44981061946600676, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014934406150132418, + "val_binary_flips_correct_pct": 0.1942017499138327, + "val_binary_flips_total_pct": 0.4050123925302543, + "val_binary_flips_wrong_pct": 0.21081064261642157, + "val_biou": 0.46053408517934796, + "val_biou_gain": 0.052244497070395746, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.833668311672746, + "val_dice_gain": 0.03454792696646747, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7442005860565111, + "val_iou_gain": 0.0392693759381425, + "val_loss": -0.14934406150132418, + "val_refine_score": 0.6023673356179295, + "val_reward": 0.014934406150132418, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6069362035649606, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 0.00015034525061425423, + "epoch": 39, + "epoch_seconds": 12.347751365043223, + "grad_norm": 0.47522361982952466, + "lr": 0.00015034525061425423, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6069362035649606, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03149757381867279, + "mean_delta": -0.020844428313218734, + "near_zero_pct": 3.2218727855334606e-05, + "negative_pct": 90.6756653027101, + "positive_pct": 9.324304607104171 + }, + "train_actor_loss": -0.017288119338693585, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01728811891536514, + "train_ce_loss": 0.14033024419437756, + "train_critic_loss": 0.0, + "train_dice": 0.9152534035243787, + "train_dice_loss": 0.059189189564098015, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8551601189055702, + "train_loss": -0.168890810825608, + "train_mask_delta_mean": 0.031495527787642044, + "train_mean_reward": 0.017288119338693585, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015072960981342476, + "val_binary_flips_correct_pct": 0.21874296898935353, + "val_binary_flips_total_pct": 0.40987052169500615, + "val_binary_flips_wrong_pct": 0.19112755270565257, + "val_biou": 0.4704770442832526, + "val_biou_gain": 0.06218745617430038, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8320128632802235, + "val_dice_gain": 0.03289247857394495, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7433953628466685, + "val_iou_gain": 0.03846415272829995, + "val_loss": -0.15072960981342476, + "val_refine_score": 0.6069362035649606, + "val_reward": 0.015072960981342476, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6037900979420112, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 6, + "encoder_lr": 0.00014813831665462106, + "epoch": 40, + "epoch_seconds": 12.336239942815155, + "grad_norm": 0.45244984193281695, + "lr": 0.00014813831665462106, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6037900979420112, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03381734199567952, + "mean_delta": -0.022799374027685684, + "near_zero_pct": 1.0544310927426439e-05, + "negative_pct": 90.70403853600675, + "positive_pct": 9.295952938158404 + }, + "train_actor_loss": -0.01730946538373246, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01730946521440108, + "train_ce_loss": 0.1424767551097003, + "train_critic_loss": 0.0, + "train_dice": 0.9152533217832279, + "train_dice_loss": 0.060359212485226715, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8551989190352528, + "train_loss": -0.1690379326993769, + "train_mask_delta_mean": 0.03381763805042614, + "train_mean_reward": 0.01730946538373246, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4261363763362169, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.0152172374073416, + "val_binary_flips_correct_pct": 0.1906114466050092, + "val_binary_flips_total_pct": 0.3505781585094976, + "val_binary_flips_wrong_pct": 0.15996671190448836, + "val_biou": 0.46567619558909523, + "val_biou_gain": 0.057386607480143015, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8299865605040548, + "val_dice_gain": 0.030866175797776285, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7419040002949272, + "val_iou_gain": 0.036972790176558634, + "val_loss": -0.152172374073416, + "val_refine_score": 0.6037900979420112, + "val_reward": 0.0152172374073416, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6101079619991863, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6074297995777657, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 7, + "encoder_lr": 0.00014589776894415052, + "epoch": 41, + "epoch_seconds": 12.372812669724226, + "grad_norm": 0.5120623382655057, + "lr": 0.00014589776894415052, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6074297995777657, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03572821299630133, + "mean_delta": -0.025522005786611277, + "near_zero_pct": 2.8899222570544225e-06, + "negative_pct": 90.77919721603394, + "positive_pct": 9.22080221670595 + }, + "train_actor_loss": -0.01738082642259542, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017380826168598353, + "train_ce_loss": 0.14453922821716828, + "train_critic_loss": 0.0, + "train_dice": 0.9142966970811834, + "train_dice_loss": 0.0618596998128024, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8544629491683816, + "train_loss": -0.16968028382821518, + "train_mask_delta_mean": 0.035737471147017044, + "train_mean_reward": 0.01738082642259542, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015843769542698283, + "val_binary_flips_correct_pct": 0.22516437605315565, + "val_binary_flips_total_pct": 0.40633631687538296, + "val_binary_flips_wrong_pct": 0.18117194082222732, + "val_biou": 0.46997433075989153, + "val_biou_gain": 0.06168474265093932, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8326320542060004, + "val_dice_gain": 0.03351166949972184, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7448852683956398, + "val_iou_gain": 0.039954058277271276, + "val_loss": -0.15843769542698283, + "val_refine_score": 0.6074297995777657, + "val_reward": 0.015843769542698283, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.612727776597498, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00014362514304232544, + "epoch": 42, + "epoch_seconds": 12.324893224053085, + "grad_norm": 0.5107278309085153, + "lr": 0.00014362514304232544, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.612727776597498, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.034485008313574574, + "mean_delta": -0.02381106612103229, + "near_zero_pct": 1.6324155441535286e-05, + "negative_pct": 90.62878740104762, + "positive_pct": 9.371198756112294 + }, + "train_actor_loss": -0.01762920199946, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017629202253457068, + "train_ce_loss": 0.1450822881676934, + "train_critic_loss": 0.0, + "train_dice": 0.9166335881528263, + "train_dice_loss": 0.0601680495522239, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.857458795935033, + "train_loss": -0.17218701405958695, + "train_mask_delta_mean": 0.03448763760653409, + "train_mean_reward": 0.01762920199946, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015697484122938477, + "val_binary_flips_correct_pct": 0.21292742560891545, + "val_binary_flips_total_pct": 0.34240647858264395, + "val_binary_flips_wrong_pct": 0.12947905297372855, + "val_biou": 0.47706262228354324, + "val_biou_gain": 0.06877303417459102, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8355417154709593, + "val_dice_gain": 0.03642133076468079, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7483929309114528, + "val_iou_gain": 0.04346172079308419, + "val_loss": -0.15697484122938477, + "val_refine_score": 0.612727776597498, + "val_reward": 0.015697484122938477, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.5998783068485712, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 0.00014132199649341884, + "epoch": 43, + "epoch_seconds": 12.33313642628491, + "grad_norm": 0.4238262284885753, + "lr": 0.00014132199649341884, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.5998783068485712, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03634868583387949, + "mean_delta": -0.0253588081210513, + "near_zero_pct": 1.7769116570062497e-05, + "negative_pct": 90.69507751952519, + "positive_pct": 9.304907037453217 + }, + "train_actor_loss": -0.017242006885598214, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.0172420069702639, + "train_ce_loss": 0.14515314928509973, + "train_critic_loss": 0.0, + "train_dice": 0.9165191559583582, + "train_dice_loss": 0.060355538671666924, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8568078175285798, + "train_loss": -0.16830989041111685, + "train_mask_delta_mean": 0.03634366122159091, + "train_mean_reward": 0.017242006885598214, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3570331789722497, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014693455530505162, + "val_binary_flips_correct_pct": 0.22217245662913604, + "val_binary_flips_total_pct": 0.43429580389284617, + "val_binary_flips_wrong_pct": 0.21212334726371018, + "val_biou": 0.4629615425353721, + "val_biou_gain": 0.054671954426419866, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8272296233177786, + "val_dice_gain": 0.028109238611500054, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7367950711617703, + "val_iou_gain": 0.031863861043401775, + "val_loss": -0.14693455530505162, + "val_refine_score": 0.5998783068485712, + "val_reward": 0.014693455530505162, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6065131225146352, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 0.00013898990775903052, + "epoch": 44, + "epoch_seconds": 12.407830741722137, + "grad_norm": 0.5657463046637449, + "lr": 0.00013898990775903052, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6065131225146352, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03636166912672872, + "mean_delta": -0.02564781796271828, + "near_zero_pct": 8.669766771163268e-06, + "negative_pct": 90.6607493080876, + "positive_pct": 9.339244367385453 + }, + "train_actor_loss": -0.017574826758143237, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017574826842808925, + "train_ce_loss": 0.1398263627832586, + "train_critic_loss": 0.0, + "train_dice": 0.91598559100682, + "train_dice_loss": 0.05891184915195812, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8572048430564547, + "train_loss": -0.17177349735390057, + "train_mask_delta_mean": 0.03636585582386364, + "train_mean_reward": 0.017574826758143237, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.44981061946600676, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015397166156617459, + "val_binary_flips_correct_pct": 0.2076130287320006, + "val_binary_flips_total_pct": 0.4128175623276654, + "val_binary_flips_wrong_pct": 0.20520453359566482, + "val_biou": 0.46981303329131674, + "val_biou_gain": 0.06152344518236452, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8316331113116466, + "val_dice_gain": 0.03251272660536808, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7432132117379537, + "val_iou_gain": 0.03828200161958517, + "val_loss": -0.1539716615661746, + "val_refine_score": 0.6065131225146352, + "val_reward": 0.015397166156617459, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6078095608960202, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 0.00013663047513628863, + "epoch": 45, + "epoch_seconds": 12.380516561679542, + "grad_norm": 0.6056401296095415, + "lr": 0.00013663047513628863, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6078095608960202, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.043554200917821036, + "mean_delta": -0.031921464717015624, + "near_zero_pct": 2.065903882711692e-05, + "negative_pct": 90.68267690864477, + "positive_pct": 9.317304320972074 + }, + "train_actor_loss": -0.017612502648841077, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01761250256417539, + "train_ce_loss": 0.14004916900938208, + "train_critic_loss": 0.0, + "train_dice": 0.9164246777904321, + "train_dice_loss": 0.06039595062082464, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8568286246153083, + "train_loss": -0.17211612517183478, + "train_mask_delta_mean": 0.043543035333806816, + "train_mean_reward": 0.017612502648841077, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.42357699818570504, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015463410236407071, + "val_binary_flips_correct_pct": 0.21163342045802697, + "val_binary_flips_total_pct": 0.38067312801585473, + "val_binary_flips_wrong_pct": 0.16903970755782782, + "val_biou": 0.4716806024544537, + "val_biou_gain": 0.06339101434550148, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8307603500687587, + "val_dice_gain": 0.03163996536248015, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7439385193375868, + "val_iou_gain": 0.039007309219218245, + "val_loss": -0.1546341023640707, + "val_refine_score": 0.6078095608960202, + "val_reward": 0.015463410236407071, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6036358726086566, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 0.00013424531566245653, + "epoch": 46, + "epoch_seconds": 12.338296278845519, + "grad_norm": 0.49090605161406775, + "lr": 0.00013424531566245653, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6036358726086566, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03730139585042542, + "mean_delta": -0.026882611617276616, + "near_zero_pct": 7.224805642636056e-06, + "negative_pct": 90.66211466084827, + "positive_pct": 9.337880326942964 + }, + "train_actor_loss": -0.01790934981148563, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017909349726819943, + "train_ce_loss": 0.13474515690044922, + "train_critic_loss": 0.0, + "train_dice": 0.919413735029697, + "train_dice_loss": 0.05697766759178855, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.861061681691327, + "train_loss": -0.17525904151526364, + "train_mask_delta_mean": 0.03729525479403409, + "train_mean_reward": 0.01790934981148563, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4261363763362169, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014715698431245983, + "val_binary_flips_correct_pct": 0.21796506993910847, + "val_binary_flips_total_pct": 0.3707511752259498, + "val_binary_flips_wrong_pct": 0.15278610528684128, + "val_biou": 0.4662263352675795, + "val_biou_gain": 0.05793674715862729, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8305904855451125, + "val_dice_gain": 0.03147010083883395, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7410454099497337, + "val_iou_gain": 0.0361141998313651, + "val_loss": -0.14715698431245983, + "val_refine_score": 0.6036358726086566, + "val_reward": 0.014715698431245983, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6087020078829497, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 0.00013183606400669613, + "epoch": 47, + "epoch_seconds": 12.34867600677535, + "grad_norm": 0.5127352421933954, + "lr": 0.00013183606400669613, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6087020078829497, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.035491730382835325, + "mean_delta": -0.0259311746340245, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.67103463140401, + "positive_pct": 9.328953265635805 + }, + "train_actor_loss": -0.017674391676833198, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01767439140166971, + "train_ce_loss": 0.14277474175799976, + "train_critic_loss": 0.0, + "train_dice": 0.9182384037470039, + "train_dice_loss": 0.06053385409441861, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.858624048638568, + "train_loss": -0.1726777431639758, + "train_mask_delta_mean": 0.035491943359375, + "train_mean_reward": 0.017674391676833198, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.37878789007663727, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015672531648306176, + "val_binary_flips_correct_pct": 0.23411769492953433, + "val_binary_flips_total_pct": 0.4450255749272365, + "val_binary_flips_wrong_pct": 0.21090787999770222, + "val_biou": 0.47173754722857375, + "val_biou_gain": 0.06344795911962153, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8327931880304581, + "val_dice_gain": 0.033672803324179545, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7456664685373258, + "val_iou_gain": 0.0407352584189572, + "val_loss": -0.15672531648306176, + "val_refine_score": 0.6087020078829497, + "val_reward": 0.015672531648306176, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6055707679924356, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 6, + "encoder_lr": 0.0001294043713497476, + "epoch": 48, + "epoch_seconds": 12.31556015694514, + "grad_norm": 0.4948542985049161, + "lr": 0.0001294043713497476, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6055707679924356, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03852155173874714, + "mean_delta": -0.027538684450767258, + "near_zero_pct": 8.669766771163268e-06, + "negative_pct": 90.74179895899512, + "positive_pct": 9.258194597945971 + }, + "train_actor_loss": -0.01778282977136314, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017782830025360206, + "train_ce_loss": 0.14486262608658185, + "train_critic_loss": 0.0, + "train_dice": 0.9144903228213107, + "train_dice_loss": 0.06112849712371826, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8550857089279974, + "train_loss": -0.1737084768035195, + "train_mask_delta_mean": 0.03853676535866477, + "train_mean_reward": 0.01778282977136314, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6411240965297277, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015188802441116422, + "val_binary_flips_correct_pct": 0.24805255964690565, + "val_binary_flips_total_pct": 0.4935507680855545, + "val_binary_flips_wrong_pct": 0.2454982084386489, + "val_biou": 0.46893495178722755, + "val_biou_gain": 0.06064536367827533, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8305874837645141, + "val_dice_gain": 0.031467099058235526, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7422065841976435, + "val_iou_gain": 0.03727537407927495, + "val_loss": -0.15188802441116422, + "val_refine_score": 0.6055707679924356, + "val_reward": 0.015188802441116422, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6007200180348845, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 7, + "encoder_lr": 0.00012695190425229217, + "epoch": 49, + "epoch_seconds": 12.370983947068453, + "grad_norm": 0.5421376607634805, + "lr": 0.00012695190425229217, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6007200180348845, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03486418146216734, + "mean_delta": -0.023214450942098418, + "near_zero_pct": 6.209427541844806e-06, + "negative_pct": 90.68701592358676, + "positive_pct": 9.312979961660774 + }, + "train_actor_loss": -0.017871508554724806, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017871508470059118, + "train_ce_loss": 0.13622108914635397, + "train_critic_loss": 0.0, + "train_dice": 0.9201706250543183, + "train_dice_loss": 0.05777861855246804, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8614648098483662, + "train_loss": -0.17483509128743951, + "train_mask_delta_mean": 0.03485939719460227, + "train_mean_reward": 0.017871508554724806, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.44981061946600676, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.014875139422656503, + "val_binary_flips_correct_pct": 0.2425249885110294, + "val_binary_flips_total_pct": 0.576168883080576, + "val_binary_flips_wrong_pct": 0.3336438945695466, + "val_biou": 0.46051303407500216, + "val_biou_gain": 0.05222344596604994, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8284155079267678, + "val_dice_gain": 0.029295123220489216, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7409270019947668, + "val_iou_gain": 0.03599579187639823, + "val_loss": -0.14875139422656503, + "val_refine_score": 0.6007200180348845, + "val_reward": 0.014875139422656503, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6087005916579069, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 8, + "encoder_lr": 0.00012448034351277498, + "epoch": 50, + "epoch_seconds": 12.39592730998993, + "grad_norm": 0.6852670013904572, + "lr": 0.00012448034351277498, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6087005916579069, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04236202756874263, + "mean_delta": -0.030853246867826038, + "near_zero_pct": 2.8899222570544225e-06, + "negative_pct": 90.69443771784955, + "positive_pct": 9.305561545558952 + }, + "train_actor_loss": -0.017746937242918648, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01774693707358727, + "train_ce_loss": 0.13818190314553, + "train_critic_loss": 0.0, + "train_dice": 0.9168370909478744, + "train_dice_loss": 0.058995474468577995, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.85766851801937, + "train_loss": -0.17352582243355838, + "train_mask_delta_mean": 0.042359785600142044, + "train_mean_reward": 0.017746937242918648, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6577600513330915, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015634930234227795, + "val_binary_flips_correct_pct": 0.23160822251263785, + "val_binary_flips_total_pct": 0.47770855473537066, + "val_binary_flips_wrong_pct": 0.24610033222273284, + "val_biou": 0.47008258624727906, + "val_biou_gain": 0.06179299813832684, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8352379479539628, + "val_dice_gain": 0.036117563247684226, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7473185970685349, + "val_iou_gain": 0.042387386950166306, + "val_loss": -0.15634930234227795, + "val_refine_score": 0.6087005916579069, + "val_reward": 0.015634930234227795, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.612727776597498, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6085563554023734, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 9, + "encoder_lr": 0.00012199138301546971, + "epoch": 51, + "epoch_seconds": 12.307875172235072, + "grad_norm": 0.5937244133515791, + "lr": 0.00012199138301546971, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6085563554023734, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03950767718594183, + "mean_delta": -0.029128689467060296, + "near_zero_pct": 3.612402795480111e-05, + "negative_pct": 90.62539914792234, + "positive_pct": 9.374567129733888 + }, + "train_actor_loss": -0.017665177830250203, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.017665177745584515, + "train_ce_loss": 0.1380420117215677, + "train_critic_loss": 0.0, + "train_dice": 0.9158570784472321, + "train_dice_loss": 0.05933468450199474, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8570076967508857, + "train_loss": -0.17270424420183356, + "train_mask_delta_mean": 0.039503617720170456, + "train_mean_reward": 0.017665177830250203, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01591012821882032, + "val_binary_flips_correct_pct": 0.22381427241306678, + "val_binary_flips_total_pct": 0.4235174141678155, + "val_binary_flips_wrong_pct": 0.1997031417547488, + "val_biou": 0.4713102147282403, + "val_biou_gain": 0.06302062661928809, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8329053089489896, + "val_dice_gain": 0.03378492424271107, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7458024960765064, + "val_iou_gain": 0.040871285958137826, + "val_loss": -0.15910128218820319, + "val_refine_score": 0.6085563554023734, + "val_reward": 0.01591012821882032, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6179552571792237, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 0.00011948672856957482, + "epoch": 52, + "epoch_seconds": 12.348047857172787, + "grad_norm": 0.556316690011458, + "lr": 0.00011948672856957482, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6179552571792237, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03439725112085315, + "mean_delta": -0.023676969449628483, + "near_zero_pct": 9.099349798899228e-06, + "negative_pct": 90.73038229888135, + "positive_pct": 9.26961074159904 + }, + "train_actor_loss": -0.018237098221685632, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018237098221685632, + "train_ce_loss": 0.13863087039102207, + "train_critic_loss": 0.0, + "train_dice": 0.9191920359958331, + "train_dice_loss": 0.058832374486056244, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8598786596787765, + "train_loss": -0.17842171544378455, + "train_mask_delta_mean": 0.03438914905894886, + "train_mean_reward": 0.018237098221685632, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016346173331839964, + "val_binary_flips_correct_pct": 0.222624984442019, + "val_binary_flips_total_pct": 0.36674948299632354, + "val_binary_flips_wrong_pct": 0.14412449855430454, + "val_biou": 0.4822347775945605, + "val_biou_gain": 0.0739451894856083, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.839368724297603, + "val_dice_gain": 0.040248339591324456, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7536757367638869, + "val_iou_gain": 0.048744526645518316, + "val_loss": -0.16346173331839964, + "val_refine_score": 0.6179552571792237, + "val_reward": 0.016346173331839964, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6161264338350805, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 0.00011696809674013731, + "epoch": 53, + "epoch_seconds": 12.350413787178695, + "grad_norm": 0.5345750749111176, + "lr": 0.00011696809674013731, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6161264338350805, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.035631802483377134, + "mean_delta": -0.024414144075390967, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.69705429402265, + "positive_pct": 9.302933226254853 + }, + "train_actor_loss": -0.01835139863529052, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01835139863529052, + "train_ce_loss": 0.13684626871889288, + "train_critic_loss": 0.0, + "train_dice": 0.919623800376411, + "train_dice_loss": 0.05845674601468173, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8618817758360214, + "train_loss": -0.17960792508992282, + "train_mask_delta_mean": 0.03564730557528409, + "train_mean_reward": 0.01835139863529052, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016559684110688977, + "val_binary_flips_correct_pct": 0.24442111744600184, + "val_binary_flips_total_pct": 0.42763130337584254, + "val_binary_flips_wrong_pct": 0.18321018592984067, + "val_biou": 0.4798774479537936, + "val_biou_gain": 0.0715878598448414, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8385263937516304, + "val_dice_gain": 0.03940600904535185, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7523754197163673, + "val_iou_gain": 0.04744420959799878, + "val_loss": -0.16559684110688977, + "val_refine_score": 0.6161264338350805, + "val_reward": 0.016559684110688977, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6098811945362733, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 0.00011443721367160455, + "epoch": 54, + "epoch_seconds": 12.315979892853647, + "grad_norm": 0.5436740517616272, + "lr": 0.00011443721367160455, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6098811945362733, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.039799680721692064, + "mean_delta": -0.02935557651587508, + "near_zero_pct": 5.779844514108845e-06, + "negative_pct": 90.70308987389912, + "positive_pct": 9.296906637874516 + }, + "train_actor_loss": -0.018766925198592202, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01876692545258927, + "train_ce_loss": 0.13741165535016495, + "train_critic_loss": 0.0, + "train_dice": 0.9208243939969879, + "train_dice_loss": 0.05824016982858831, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.863558812466298, + "train_loss": -0.1837562160058455, + "train_mask_delta_mean": 0.039778275923295456, + "train_mean_reward": 0.018766925198592202, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016151541596627794, + "val_binary_flips_correct_pct": 0.24101780910117954, + "val_binary_flips_total_pct": 0.4720126881318934, + "val_binary_flips_wrong_pct": 0.23099487903071386, + "val_biou": 0.4713654746290654, + "val_biou_gain": 0.0630758865201132, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8360658129159004, + "val_dice_gain": 0.03694542820962188, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7483969144434812, + "val_iou_gain": 0.04346570432511265, + "val_loss": -0.16151541596627794, + "val_refine_score": 0.6098811945362733, + "val_reward": 0.016151541596627794, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6119462781473497, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 0.00011189581390481132, + "epoch": 55, + "epoch_seconds": 12.300644266884774, + "grad_norm": 0.6083403798666868, + "lr": 0.00011189581390481132, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6119462781473497, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.033440835075452924, + "mean_delta": -0.02201393278400329, + "near_zero_pct": 5.779844514108845e-06, + "negative_pct": 90.78847339207476, + "positive_pct": 9.211522992700338 + }, + "train_actor_loss": -0.018909487024674574, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018909487172839527, + "train_ce_loss": 0.1300485764037479, + "train_critic_loss": 0.0, + "train_dice": 0.9239614623614716, + "train_dice_loss": 0.0559622970494357, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8668460437627816, + "train_loss": -0.18537465144287457, + "train_mask_delta_mean": 0.03345003995028409, + "train_mean_reward": 0.018909487024674574, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01609536622709129, + "val_binary_flips_correct_pct": 0.23250953823912376, + "val_binary_flips_total_pct": 0.4127427643420649, + "val_binary_flips_wrong_pct": 0.18023322610294118, + "val_biou": 0.47555024635404275, + "val_biou_gain": 0.06726065824509053, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8359544299454572, + "val_dice_gain": 0.03683404523917866, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7483423099406566, + "val_iou_gain": 0.04341109982228808, + "val_loss": -0.1609536622709129, + "val_refine_score": 0.6119462781473497, + "val_reward": 0.01609536622709129, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6098127148105044, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 0.00010934563918821202, + "epoch": 56, + "epoch_seconds": 12.36097556212917, + "grad_norm": 0.6575006896799261, + "lr": 0.00010934563918821202, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6098127148105044, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037344826639375904, + "mean_delta": -0.026496270248158413, + "near_zero_pct": 1.4879194313008073e-05, + "negative_pct": 90.73405807668513, + "positive_pct": 9.265929130329328 + }, + "train_actor_loss": -0.018061450647192858, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018061450647192858, + "train_ce_loss": 0.14349709451198578, + "train_critic_loss": 0.0, + "train_dice": 0.9148743094972369, + "train_dice_loss": 0.06096295876936479, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8562428900606811, + "train_loss": -0.17652530561793933, + "train_mask_delta_mean": 0.03735074129971591, + "train_mean_reward": 0.018061450647192858, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6392045645043254, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015601644154230598, + "val_binary_flips_correct_pct": 0.2756754557291667, + "val_binary_flips_total_pct": 0.5501541436887254, + "val_binary_flips_wrong_pct": 0.2744786879595588, + "val_biou": 0.47438099899486064, + "val_biou_gain": 0.06609141088590842, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8317154895129328, + "val_dice_gain": 0.032595104806654285, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.745244430626148, + "val_iou_gain": 0.04031322050777941, + "val_loss": -0.15601644154230598, + "val_refine_score": 0.6098127148105044, + "val_reward": 0.015601644154230598, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6065281539481966, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 0.00010678843728417333, + "epoch": 57, + "epoch_seconds": 12.265169208869338, + "grad_norm": 0.7914729497649453, + "lr": 0.00010678843728417333, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6065281539481966, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03496332326903939, + "mean_delta": -0.023867265532978556, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.70480276237835, + "positive_pct": 9.295185071162201 + }, + "train_actor_loss": -0.018456254594473812, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018456254594473812, + "train_ce_loss": 0.14186858453533865, + "train_critic_loss": 0.0, + "train_dice": 0.9177009927648757, + "train_dice_loss": 0.06133136966011741, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8599184779118294, + "train_loss": -0.1804985444654118, + "train_mask_delta_mean": 0.03496066006747159, + "train_mean_reward": 0.018456254594473812, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5208333488553762, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015683870027714875, + "val_binary_flips_correct_pct": 0.22568422205307903, + "val_binary_flips_total_pct": 0.41492312562231926, + "val_binary_flips_wrong_pct": 0.1892389035692402, + "val_biou": 0.46749897856077083, + "val_biou_gain": 0.05920939045181861, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8338876888633202, + "val_dice_gain": 0.034767304157041656, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7455573293356222, + "val_iou_gain": 0.040626119217253676, + "val_loss": -0.15683870027714875, + "val_refine_score": 0.6065281539481966, + "val_reward": 0.015683870027714875, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6034722802858443, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 6, + "encoder_lr": 0.00010422596077114516, + "epoch": 58, + "epoch_seconds": 12.32869984395802, + "grad_norm": 0.624755011363463, + "lr": 0.00010422596077114516, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6034722802858443, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03565853241492401, + "mean_delta": -0.024064670020545072, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.76441912488504, + "positive_pct": 9.235571036961945 + }, + "train_actor_loss": -0.018415026443190898, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018415026612522277, + "train_ce_loss": 0.14108053527095102, + "train_critic_loss": 0.0, + "train_dice": 0.917454247872385, + "train_dice_loss": 0.06024809859015725, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8588315115110677, + "train_loss": -0.18012368814511734, + "train_mask_delta_mean": 0.035658402876420456, + "train_mean_reward": 0.018415026443190898, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015186834156338591, + "val_binary_flips_correct_pct": 0.22457347196691177, + "val_binary_flips_total_pct": 0.44332392075482535, + "val_binary_flips_wrong_pct": 0.2187504487879136, + "val_biou": 0.46372738444385725, + "val_biou_gain": 0.05543779633490503, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8322326517310816, + "val_dice_gain": 0.03311226702480308, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7432171761278313, + "val_iou_gain": 0.03828596600946277, + "val_loss": -0.1518683415633859, + "val_refine_score": 0.6034722802858443, + "val_reward": 0.015186834156338591, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6052854654491685, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 7, + "encoder_lr": 0.00010165996584253105, + "epoch": 59, + "epoch_seconds": 12.363262321799994, + "grad_norm": 0.6573047583753412, + "lr": 0.00010165996584253105, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6052854654491685, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03798416887663982, + "mean_delta": -0.026487415423616767, + "near_zero_pct": 2.065903882711692e-05, + "negative_pct": 90.62703841111876, + "positive_pct": 9.37294304709543 + }, + "train_actor_loss": -0.01868700123304734, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01868700140237872, + "train_ce_loss": 0.14027165960181842, + "train_critic_loss": 0.0, + "train_dice": 0.917428368592232, + "train_dice_loss": 0.06068694591522217, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8604515678473941, + "train_loss": -0.1828508431261236, + "train_mask_delta_mean": 0.03800270774147727, + "train_mean_reward": 0.01868700123304734, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.2367424312978983, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015505777759244666, + "val_binary_flips_correct_pct": 0.24447347603592218, + "val_binary_flips_total_pct": 0.48817653282015927, + "val_binary_flips_wrong_pct": 0.24370305678423715, + "val_biou": 0.4677293862146079, + "val_biou_gain": 0.059439798105655695, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8305347107287713, + "val_dice_gain": 0.03141432602249272, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7428415446837291, + "val_iou_gain": 0.037910334565360526, + "val_loss": -0.15505777759244666, + "val_refine_score": 0.6052854654491685, + "val_reward": 0.015505777759244666, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6070992459139621, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 8, + "encoder_lr": 9.909221110308074e-05, + "epoch": 60, + "epoch_seconds": 12.345779440831393, + "grad_norm": 0.6206594163721258, + "lr": 9.909221110308074e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6070992459139621, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03681208100169897, + "mean_delta": -0.026084496555003254, + "near_zero_pct": 4.334883385581634e-06, + "negative_pct": 90.72030173106627, + "positive_pct": 9.279696313156323 + }, + "train_actor_loss": -0.018590604578176597, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018590604578176597, + "train_ce_loss": 0.13481572541323575, + "train_critic_loss": 0.0, + "train_dice": 0.9209666054595084, + "train_dice_loss": 0.058143572373823685, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8632326262032216, + "train_loss": -0.18204685910181564, + "train_mask_delta_mean": 0.036820845170454544, + "train_mean_reward": 0.018590604578176597, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01534955388342496, + "val_binary_flips_correct_pct": 0.25252921908509496, + "val_binary_flips_total_pct": 0.5022871728036918, + "val_binary_flips_wrong_pct": 0.24975795371859683, + "val_biou": 0.46917051317402575, + "val_biou_gain": 0.06088092506507353, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8321257822144857, + "val_dice_gain": 0.03300539750820719, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7450279786538986, + "val_iou_gain": 0.040096768535530014, + "val_loss": -0.1534955388342496, + "val_refine_score": 0.6070992459139621, + "val_reward": 0.01534955388342496, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6142749276131241, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 9, + "encoder_lr": 9.652445636363041e-05, + "epoch": 61, + "epoch_seconds": 12.348791033960879, + "grad_norm": 0.5925727865912698, + "lr": 9.652445636363041e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6142749276131241, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04036146050996401, + "mean_delta": -0.02921303945847533, + "near_zero_pct": 1.3004650156744901e-05, + "negative_pct": 90.73422097346999, + "positive_pct": 9.26576851951805 + }, + "train_actor_loss": -0.018980272626239723, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018980272732071833, + "train_ce_loss": 0.14014612612399188, + "train_critic_loss": 0.0, + "train_dice": 0.9179883380477802, + "train_dice_loss": 0.06094266067851673, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8608618870595162, + "train_loss": -0.18578095056793906, + "train_mask_delta_mean": 0.04035672274502841, + "train_mean_reward": 0.018980272626239723, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01608840739936568, + "val_binary_flips_correct_pct": 0.2307891845703125, + "val_binary_flips_total_pct": 0.41788512585209864, + "val_binary_flips_wrong_pct": 0.18709594128178614, + "val_biou": 0.4774610116260543, + "val_biou_gain": 0.06917142351710209, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8378663800565953, + "val_dice_gain": 0.03874599535031675, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7510888436001938, + "val_iou_gain": 0.04615763348182522, + "val_loss": -0.16088407399365678, + "val_refine_score": 0.6142749276131241, + "val_reward": 0.01608840739936568, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.615516209872145, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 10, + "encoder_lr": 9.395846143501629e-05, + "epoch": 62, + "epoch_seconds": 12.418412092141807, + "grad_norm": 0.636552786285227, + "lr": 9.395846143501629e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.615516209872145, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.040005015547979965, + "mean_delta": -0.028455266115170987, + "near_zero_pct": 1.921407769858971e-05, + "negative_pct": 90.69115356965499, + "positive_pct": 9.30882930247621 + }, + "train_actor_loss": -0.01889217275137608, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.018892172836041773, + "train_ce_loss": 0.1345395723527128, + "train_critic_loss": 0.0, + "train_dice": 0.9185060673015936, + "train_dice_loss": 0.057601652362129906, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8621074945915409, + "train_loss": -0.18507890132340518, + "train_mask_delta_mean": 0.040002996271306816, + "train_mean_reward": 0.01889217275137608, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971590909090909, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016334631625795737, + "val_binary_flips_correct_pct": 0.2485537061504289, + "val_binary_flips_total_pct": 0.44886645148782167, + "val_binary_flips_wrong_pct": 0.20031274533739274, + "val_biou": 0.4791406113696343, + "val_biou_gain": 0.0708510232606821, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8384269949817598, + "val_dice_gain": 0.03930661027548121, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7518918083746556, + "val_iou_gain": 0.04696059825628707, + "val_loss": -0.16334631625795737, + "val_refine_score": 0.615516209872145, + "val_reward": 0.016334631625795737, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6116193091204765, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 11, + "encoder_lr": 9.139598492198814e-05, + "epoch": 63, + "epoch_seconds": 12.370155649259686, + "grad_norm": 0.620172768831253, + "lr": 9.139598492198814e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6116193091204765, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04236639506945556, + "mean_delta": -0.030643203062936664, + "near_zero_pct": 5.779844514108845e-06, + "negative_pct": 90.63631072640419, + "positive_pct": 9.363686208697883 + }, + "train_actor_loss": -0.019036843248035108, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019036843502032174, + "train_ce_loss": 0.13499926233833487, + "train_critic_loss": 0.0, + "train_dice": 0.920519889015138, + "train_dice_loss": 0.057843701405958695, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8636398230928928, + "train_loss": -0.18651156669313257, + "train_mask_delta_mean": 0.04236672141335227, + "train_mean_reward": 0.019036843248035108, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01593889519426739, + "val_binary_flips_correct_pct": 0.2397312837488511, + "val_binary_flips_total_pct": 0.4694396374272365, + "val_binary_flips_wrong_pct": 0.22970835367838544, + "val_biou": 0.4733439206882831, + "val_biou_gain": 0.06505433257933091, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.837268745143806, + "val_dice_gain": 0.03814836043752745, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7498946975526699, + "val_iou_gain": 0.04496348743430134, + "val_loss": -0.15938895194267388, + "val_refine_score": 0.6116193091204765, + "val_reward": 0.01593889519426739, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6066379188843906, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 12, + "encoder_lr": 8.883878301794945e-05, + "epoch": 64, + "epoch_seconds": 12.383578690234572, + "grad_norm": 0.5809974291107871, + "lr": 8.883878301794945e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6066379188843906, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03541198648004369, + "mean_delta": -0.024154589934782547, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.72237028317018, + "positive_pct": 9.277617948299104 + }, + "train_actor_loss": -0.01899703643985876, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01899703654569087, + "train_ce_loss": 0.14744106138294394, + "train_critic_loss": 0.0, + "train_dice": 0.917841265257199, + "train_dice_loss": 0.06256875666705045, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8609564289885896, + "train_loss": -0.1857701621272347, + "train_mask_delta_mean": 0.035414262251420456, + "train_mean_reward": 0.01899703643985876, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015390934255265165, + "val_binary_flips_correct_pct": 0.24489608465456492, + "val_binary_flips_total_pct": 0.4630219702627144, + "val_binary_flips_wrong_pct": 0.2181258856081495, + "val_biou": 0.4679960361441764, + "val_biou_gain": 0.05970644803522418, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8332154440641902, + "val_dice_gain": 0.03409505935791168, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7452798016246047, + "val_iou_gain": 0.04034859150623615, + "val_loss": -0.15390934255265165, + "val_refine_score": 0.6066379188843906, + "val_reward": 0.015390934255265165, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6148004352070544, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 13, + "encoder_lr": 8.628860830135015e-05, + "epoch": 65, + "epoch_seconds": 12.309775501023978, + "grad_norm": 0.6731807670810006, + "lr": 8.628860830135015e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6148004352070544, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03952033652670004, + "mean_delta": -0.02842036651616747, + "near_zero_pct": 1.0114727899690479e-05, + "negative_pct": 90.69967500188135, + "positive_pct": 9.300317196175456 + }, + "train_actor_loss": -0.019262711325692097, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01926271107169503, + "train_ce_loss": 0.13206370242617346, + "train_critic_loss": 0.0, + "train_dice": 0.9216632305819122, + "train_dice_loss": 0.058458398688923226, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8654302456017339, + "train_loss": -0.1888166611844843, + "train_mask_delta_mean": 0.039520263671875, + "train_mean_reward": 0.019262711325692097, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.2149877201935107, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015936906034767162, + "val_binary_flips_correct_pct": 0.2504386153875613, + "val_binary_flips_total_pct": 0.4715452007218903, + "val_binary_flips_wrong_pct": 0.22110658533432903, + "val_biou": 0.4784916257500011, + "val_biou_gain": 0.07020203764104888, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8378714829006818, + "val_dice_gain": 0.038751098194403255, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7511092446641078, + "val_iou_gain": 0.04617803454573921, + "val_loss": -0.15936906034767162, + "val_refine_score": 0.6148004352070544, + "val_reward": 0.015936906034767162, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.617724835341937, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 14, + "encoder_lr": 8.374720853455689e-05, + "epoch": 66, + "epoch_seconds": 12.340721111278981, + "grad_norm": 0.6639719984748147, + "lr": 8.374720853455689e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.617724835341937, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03673366579989141, + "mean_delta": -0.024781393755057998, + "near_zero_pct": 7.224805642636056e-06, + "negative_pct": 90.60972332954407, + "positive_pct": 9.390271590514617 + }, + "train_actor_loss": -0.0196138678273366, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01961386784850302, + "train_ce_loss": 0.12908935072747144, + "train_critic_loss": 0.0, + "train_dice": 0.9256470681248172, + "train_dice_loss": 0.055393034761602226, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8701000763959802, + "train_loss": -0.19244902377778833, + "train_mask_delta_mean": 0.036726518110795456, + "train_mean_reward": 0.0196138678273366, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3807074221020395, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016376719511754345, + "val_binary_flips_correct_pct": 0.2827999638576134, + "val_binary_flips_total_pct": 0.4851546942018995, + "val_binary_flips_wrong_pct": 0.20235473034428614, + "val_biou": 0.4841712046501461, + "val_biou_gain": 0.07588161654119391, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8374660805342505, + "val_dice_gain": 0.03834569582797198, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7512784660337279, + "val_iou_gain": 0.046347255915359375, + "val_loss": -0.16376719511754345, + "val_refine_score": 0.617724835341937, + "val_reward": 0.016376719511754345, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6104264108778761, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 15, + "encoder_lr": 8.121632546602416e-05, + "epoch": 67, + "epoch_seconds": 12.344149574171752, + "grad_norm": 0.6588450724428351, + "lr": 8.121632546602416e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6104264108778761, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.039706933820112186, + "mean_delta": -0.028484537774188953, + "near_zero_pct": 1.3004650156744901e-05, + "negative_pct": 90.70407639850269, + "positive_pct": 9.295912747356025 + }, + "train_actor_loss": -0.01928838563253521, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01928838525153961, + "train_ce_loss": 0.13624204966154965, + "train_critic_loss": 0.0, + "train_dice": 0.9204285166118062, + "train_dice_loss": 0.05859593911604448, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8645170711151844, + "train_loss": -0.1889870979569175, + "train_mask_delta_mean": 0.039703369140625, + "train_mean_reward": 0.01928838563253521, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015852006785280537, + "val_binary_flips_correct_pct": 0.27715645584405635, + "val_binary_flips_total_pct": 0.5375619028128831, + "val_binary_flips_wrong_pct": 0.2604054469688266, + "val_biou": 0.47443605957969576, + "val_biou_gain": 0.06614647147074354, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8338040101327725, + "val_dice_gain": 0.03468362542649395, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7464167621760565, + "val_iou_gain": 0.04148555205768789, + "val_loss": -0.15852006785280537, + "val_refine_score": 0.6104264108778761, + "val_reward": 0.015852006785280537, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.606518786668063, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 16, + "encoder_lr": 7.869769363658661e-05, + "epoch": 68, + "epoch_seconds": 12.346118221990764, + "grad_norm": 0.6514944109049711, + "lr": 7.869769363658661e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.606518786668063, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0377959153953601, + "mean_delta": -0.026885804910720748, + "near_zero_pct": 1.0114727899690479e-05, + "negative_pct": 90.80832769924945, + "positive_pct": 9.19166442684152 + }, + "train_actor_loss": -0.019524584348387594, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019524584263721903, + "train_ce_loss": 0.13940022343939001, + "train_critic_loss": 0.0, + "train_dice": 0.9188382075189454, + "train_dice_loss": 0.06098462776704268, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8629342425781771, + "train_loss": -0.19123814864592117, + "train_mask_delta_mean": 0.037797407670454544, + "train_mean_reward": 0.019524584348387594, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.877866527827626, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01530246210313635, + "val_binary_flips_correct_pct": 0.2594779519473805, + "val_binary_flips_total_pct": 0.4540836109834559, + "val_binary_flips_wrong_pct": 0.19460565903607535, + "val_biou": 0.47228375585318033, + "val_biou_gain": 0.06399416774422811, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8252235957455976, + "val_dice_gain": 0.026103211039319008, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7407538174829457, + "val_iou_gain": 0.0358226073645771, + "val_loss": -0.1530246210313635, + "val_refine_score": 0.606518786668063, + "val_reward": 0.01530246210313635, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6153197543583999, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 17, + "encoder_lr": 7.619303919069176e-05, + "epoch": 69, + "epoch_seconds": 12.32828638004139, + "grad_norm": 0.6867987188425931, + "lr": 7.619303919069176e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6153197543583999, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037863273808563296, + "mean_delta": -0.026603725484826347, + "near_zero_pct": 3.6124027825611513e-05, + "negative_pct": 90.69803350351073, + "positive_pct": 9.301932935010303 + }, + "train_actor_loss": -0.019669989965967197, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019669989796635822, + "train_ce_loss": 0.13246401128443805, + "train_critic_loss": 0.0, + "train_dice": 0.9212594922081131, + "train_dice_loss": 0.05658578872680664, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8666531743035388, + "train_loss": -0.19291890886696902, + "train_mask_delta_mean": 0.03786399147727273, + "train_mean_reward": 0.019669989965967197, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016150036208273377, + "val_binary_flips_correct_pct": 0.2623464546951593, + "val_binary_flips_total_pct": 0.4403357412300858, + "val_binary_flips_wrong_pct": 0.17798928653492646, + "val_biou": 0.4793972096320068, + "val_biou_gain": 0.07110762152305461, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8379372373730781, + "val_dice_gain": 0.03881685266679957, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7512422990847929, + "val_iou_gain": 0.04631108896642433, + "val_loss": -0.16150036208273377, + "val_refine_score": 0.6153197543583999, + "val_reward": 0.016150036208273377, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6142963031959754, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 18, + "encoder_lr": 7.370407869338648e-05, + "epoch": 70, + "epoch_seconds": 12.35185300419107, + "grad_norm": 0.6876213225451383, + "lr": 7.370407869338648e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6142963031959754, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03874802602116357, + "mean_delta": -0.027334136570888488, + "near_zero_pct": 1.5308777340744033e-05, + "negative_pct": 90.72112691673365, + "positive_pct": 9.278859833086079 + }, + "train_actor_loss": -0.019703135399719362, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01970313537855294, + "train_ce_loss": 0.13042822818864475, + "train_critic_loss": 0.0, + "train_dice": 0.9242065818287606, + "train_dice_loss": 0.05583938685330478, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.868066862158061, + "train_loss": -0.1933059976859526, + "train_mask_delta_mean": 0.038743452592329544, + "train_mean_reward": 0.019703135399719362, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016144271969096735, + "val_binary_flips_correct_pct": 0.27820362764246326, + "val_binary_flips_total_pct": 0.5426070269416361, + "val_binary_flips_wrong_pct": 0.2644033992991728, + "val_biou": 0.477811877657117, + "val_biou_gain": 0.0695222895481648, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.837662757062372, + "val_dice_gain": 0.03854237235609348, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7507807287348337, + "val_iou_gain": 0.045849518616465135, + "val_loss": -0.16144271969096735, + "val_refine_score": 0.6142963031959754, + "val_reward": 0.016144271969096735, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6151943326289807, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 19, + "encoder_lr": 7.123251795386929e-05, + "epoch": 71, + "epoch_seconds": 12.309240648988634, + "grad_norm": 0.8244967460632324, + "lr": 7.123251795386929e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6151943326289807, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04075585754418915, + "mean_delta": -0.029308468971232123, + "near_zero_pct": 7.224805642636056e-06, + "negative_pct": 90.63186774199659, + "positive_pct": 9.368127364326607 + }, + "train_actor_loss": -0.01947866574581977, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019478665491822703, + "train_ce_loss": 0.13332330909642306, + "train_critic_loss": 0.0, + "train_dice": 0.9217265347754643, + "train_dice_loss": 0.05798537080938166, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8648536104576441, + "train_loss": -0.19096047634428198, + "train_mask_delta_mean": 0.040757612748579544, + "train_mean_reward": 0.01947866574581977, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016714107609004714, + "val_binary_flips_correct_pct": 0.2713857912549785, + "val_binary_flips_total_pct": 0.48467224719477636, + "val_binary_flips_wrong_pct": 0.21328645593979778, + "val_biou": 0.47886703588914875, + "val_biou_gain": 0.07057744778019653, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8380811481966544, + "val_dice_gain": 0.038960763490375805, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7515216293688126, + "val_iou_gain": 0.04659041925044405, + "val_loss": -0.16714107609004714, + "val_refine_score": 0.6151943326289807, + "val_reward": 0.016714107609004714, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6068344620098365, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 20, + "encoder_lr": 6.878005085641386e-05, + "epoch": 72, + "epoch_seconds": 12.33079385990277, + "grad_norm": 0.734797634861686, + "lr": 6.878005085641386e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6068344620098365, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03910648395222696, + "mean_delta": -0.027775880626656792, + "near_zero_pct": 2.050282678179759e-05, + "negative_pct": 90.60484326698564, + "positive_pct": 9.39513851295818 + }, + "train_actor_loss": -0.019639251377983866, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.0196392511239868, + "train_ce_loss": 0.13776381720196118, + "train_critic_loss": 0.0, + "train_dice": 0.9216511459495998, + "train_dice_loss": 0.05901595679196445, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8665593151734458, + "train_loss": -0.19245692545717413, + "train_mask_delta_mean": 0.03910411487926136, + "train_mean_reward": 0.019639251377983866, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015362495432782453, + "val_binary_flips_correct_pct": 0.2678179273418352, + "val_binary_flips_total_pct": 0.5727057363472732, + "val_binary_flips_wrong_pct": 0.3048878090054381, + "val_biou": 0.4700086593397753, + "val_biou_gain": 0.0617190712308231, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8306761353519035, + "val_dice_gain": 0.03155575064562499, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7436602646798977, + "val_iou_gain": 0.038729054561529086, + "val_loss": -0.15362495432782453, + "val_refine_score": 0.6068344620098365, + "val_reward": 0.015362495432782453, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6119208491800738, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 21, + "encoder_lr": 6.634835819946531e-05, + "epoch": 73, + "epoch_seconds": 12.32071080384776, + "grad_norm": 0.8503118699247186, + "lr": 6.634835819946531e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6119208491800738, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04085132310336286, + "mean_delta": -0.029652984961020677, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.77565785158764, + "positive_pct": 9.224329998886043 + }, + "train_actor_loss": -0.019533183358858383, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019533183612855446, + "train_ce_loss": 0.13790796426209537, + "train_critic_loss": 0.0, + "train_dice": 0.9214931451064754, + "train_dice_loss": 0.06069853630932895, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8658586382382661, + "train_loss": -0.1913597136735916, + "train_mask_delta_mean": 0.040838068181818184, + "train_mean_reward": 0.019533183358858383, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5956951422955502, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015910196059849113, + "val_binary_flips_correct_pct": 0.2511080573586857, + "val_binary_flips_total_pct": 0.4856782801011029, + "val_binary_flips_wrong_pct": 0.2345702227424173, + "val_biou": 0.47400885621807654, + "val_biou_gain": 0.06571926810912432, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8372864270881901, + "val_dice_gain": 0.03816604238191157, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7498328421420712, + "val_iou_gain": 0.044901632023702676, + "val_loss": -0.15910196059849113, + "val_refine_score": 0.6119208491800738, + "val_reward": 0.015910196059849113, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6126470013371297, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 22, + "encoder_lr": 6.393910654370494e-05, + "epoch": 74, + "epoch_seconds": 12.371501197107136, + "grad_norm": 0.6999097032980486, + "lr": 6.393910654370494e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6126470013371297, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03991864960302006, + "mean_delta": -0.028471701841970735, + "near_zero_pct": 1.3004650156744901e-05, + "negative_pct": 90.62204279682852, + "positive_pct": 9.377946560694413 + }, + "train_actor_loss": -0.019906744666513987, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.019906744772346097, + "train_ce_loss": 0.13166198269887405, + "train_critic_loss": 0.0, + "train_dice": 0.9247026659941108, + "train_dice_loss": 0.056162086400118744, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.86923548942415, + "train_loss": -0.19531096111644397, + "train_mask_delta_mean": 0.03993641246448864, + "train_mean_reward": 0.019906744666513987, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016057746885053348, + "val_binary_flips_correct_pct": 0.26251101026348034, + "val_binary_flips_total_pct": 0.4758984434838389, + "val_binary_flips_wrong_pct": 0.21338743322035847, + "val_biou": 0.47664445681300194, + "val_biou_gain": 0.06835486870404972, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8357827034583957, + "val_dice_gain": 0.03666231875211712, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7486495458612574, + "val_iou_gain": 0.04371833574288886, + "val_loss": -0.16057746885053348, + "val_refine_score": 0.6126470013371297, + "val_reward": 0.016057746885053348, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6162105673455562, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 23, + "encoder_lr": 6.155394706987283e-05, + "epoch": 75, + "epoch_seconds": 12.360095776151866, + "grad_norm": 0.6485401121052828, + "lr": 6.155394706987283e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6162105673455562, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.041946065315807406, + "mean_delta": -0.03083719541742043, + "near_zero_pct": 6.209427541844806e-06, + "negative_pct": 90.67804298617624, + "positive_pct": 9.321953034536405 + }, + "train_actor_loss": -0.01994787872668398, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.01994787864201829, + "train_ce_loss": 0.13030748746611856, + "train_critic_loss": 0.0, + "train_dice": 0.9240107878627669, + "train_dice_loss": 0.05647835406390103, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8683875820936624, + "train_loss": -0.1957430663433942, + "train_mask_delta_mean": 0.04195057262073864, + "train_mean_reward": 0.01994787872668398, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01627546700910898, + "val_binary_flips_correct_pct": 0.2878301283892463, + "val_binary_flips_total_pct": 0.5245919321097581, + "val_binary_flips_wrong_pct": 0.23676180372051164, + "val_biou": 0.4811187101124201, + "val_biou_gain": 0.07282912200346786, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8377170231949622, + "val_dice_gain": 0.038596638488683666, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7513024245786923, + "val_iou_gain": 0.04637121446032377, + "val_loss": -0.1627546700910898, + "val_refine_score": 0.6162105673455562, + "val_reward": 0.01627546700910898, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6179552571792237, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6144103831763753, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 24, + "encoder_lr": 5.919451444713095e-05, + "epoch": 76, + "epoch_seconds": 12.364288566168398, + "grad_norm": 0.7458387504924427, + "lr": 5.919451444713095e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6144103831763753, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038073826750571076, + "mean_delta": -0.027658617166294294, + "near_zero_pct": 2.3548961084171342e-05, + "negative_pct": 90.75461314483123, + "positive_pct": 9.24536548131569 + }, + "train_actor_loss": -0.020058848240296356, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02005884815563067, + "train_ce_loss": 0.13375684957612644, + "train_critic_loss": 0.0, + "train_dice": 0.9225211833356535, + "train_dice_loss": 0.057829488407481804, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8671959560963997, + "train_loss": -0.19675675982778723, + "train_mask_delta_mean": 0.0380859375, + "train_mean_reward": 0.020058848240296356, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016138681865413673, + "val_binary_flips_correct_pct": 0.2698935714422488, + "val_binary_flips_total_pct": 0.503244587019378, + "val_binary_flips_wrong_pct": 0.23335101557712928, + "val_biou": 0.47756947820380136, + "val_biou_gain": 0.06927989009484914, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8379040935185832, + "val_dice_gain": 0.03878370881230464, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7512512881489493, + "val_iou_gain": 0.04632007803058069, + "val_loss": -0.16138681865413673, + "val_refine_score": 0.6144103831763753, + "val_reward": 0.016138681865413673, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6186344780252565, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 5.686242571274264e-05, + "epoch": 77, + "epoch_seconds": 12.339129115920514, + "grad_norm": 0.8376146717505022, + "lr": 5.686242571274264e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6186344780252565, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03931430930441076, + "mean_delta": -0.02815043219280514, + "near_zero_pct": 1.5894572413799324e-05, + "negative_pct": 90.70207876237956, + "positive_pct": 9.297907555645162 + }, + "train_actor_loss": -0.020280701921861197, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02028070166786413, + "train_ce_loss": 0.12540075927972794, + "train_critic_loss": 0.0, + "train_dice": 0.9273971361810561, + "train_dice_loss": 0.054617984728379684, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8729619237205097, + "train_loss": -0.1992066434838555, + "train_mask_delta_mean": 0.03931773792613636, + "train_mean_reward": 0.020280701921861197, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.28409091755747795, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016741985760745592, + "val_binary_flips_correct_pct": 0.2853655347637102, + "val_binary_flips_total_pct": 0.5137200449027268, + "val_binary_flips_wrong_pct": 0.22835451013901653, + "val_biou": 0.4847460216019157, + "val_biou_gain": 0.0764564334929635, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8383520659830637, + "val_dice_gain": 0.03923168127678511, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7525229344485973, + "val_iou_gain": 0.047591724330228735, + "val_loss": -0.16741985760745592, + "val_refine_score": 0.6186344780252565, + "val_reward": 0.016741985760745592, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6177062913866174, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 5.4559279163835986e-05, + "epoch": 78, + "epoch_seconds": 12.335720237810165, + "grad_norm": 0.7837451046163385, + "lr": 5.4559279163835986e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6177062913866174, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038647487039931795, + "mean_delta": -0.026744888396933675, + "near_zero_pct": 1.0114727899690479e-05, + "negative_pct": 90.65983586690642, + "positive_pct": 9.340156216851689 + }, + "train_actor_loss": -0.02038936521884435, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020389365007180128, + "train_ce_loss": 0.13066139004447244, + "train_critic_loss": 0.0, + "train_dice": 0.9240430571888897, + "train_dice_loss": 0.057624182917855, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8698009231775157, + "train_loss": -0.20012794435024261, + "train_mask_delta_mean": 0.038649125532670456, + "train_mean_reward": 0.02038936521884435, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.21306818816810846, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01652055812155595, + "val_binary_flips_correct_pct": 0.27794557459214153, + "val_binary_flips_total_pct": 0.4992503745883119, + "val_binary_flips_wrong_pct": 0.22130479999617036, + "val_biou": 0.4840844486457553, + "val_biou_gain": 0.07579486053680307, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8374511963392129, + "val_dice_gain": 0.03833081163293439, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7513281341274793, + "val_iou_gain": 0.046396924009110774, + "val_loss": -0.1652055812155595, + "val_refine_score": 0.6177062913866174, + "val_reward": 0.01652055812155595, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6170799252857897, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 5.228665326201092e-05, + "epoch": 79, + "epoch_seconds": 12.331462685018778, + "grad_norm": 0.8021938042207197, + "lr": 5.228665326201092e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6170799252857897, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0376858416182751, + "mean_delta": -0.026458486385474152, + "near_zero_pct": 1.0114727899690479e-05, + "negative_pct": 90.73594002561136, + "positive_pct": 9.264052155512301 + }, + "train_actor_loss": -0.02068091423478274, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02068091415011705, + "train_ce_loss": 0.12683628702705557, + "train_critic_loss": 0.0, + "train_dice": 0.9288101879530427, + "train_dice_loss": 0.05614560842514038, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8741432755645179, + "train_loss": -0.20314950834621082, + "train_mask_delta_mean": 0.037683660333806816, + "train_mean_reward": 0.02068091423478274, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.14204545877873898, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016411185468314216, + "val_binary_flips_correct_pct": 0.29175328273399204, + "val_binary_flips_total_pct": 0.4960901596966912, + "val_binary_flips_wrong_pct": 0.20433687696269914, + "val_biou": 0.48316135545609373, + "val_biou_gain": 0.07487176734714152, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8374921880637538, + "val_dice_gain": 0.038371803357475254, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7509984951154858, + "val_iou_gain": 0.04606728499711721, + "val_loss": -0.16411185468314216, + "val_refine_score": 0.6170799252857897, + "val_reward": 0.016411185468314216, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6108647898618509, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 5.0046105551540376e-05, + "epoch": 80, + "epoch_seconds": 12.34832909097895, + "grad_norm": 0.8214269009503451, + "lr": 5.0046105551540376e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6108647898618509, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03884729781103405, + "mean_delta": -0.027230576167560437, + "near_zero_pct": 2.3119377927245793e-05, + "negative_pct": 90.70604734800078, + "positive_pct": 9.293931917372076 + }, + "train_actor_loss": -0.020606802979521242, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020606802725524176, + "train_ce_loss": 0.125814905220812, + "train_critic_loss": 0.0, + "train_dice": 0.9263304872793363, + "train_dice_loss": 0.054229118607260964, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8721723194702613, + "train_loss": -0.20246714489026504, + "train_mask_delta_mean": 0.03883777965198864, + "train_mean_reward": 0.020606802979521242, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5208333488553762, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.015559934312477708, + "val_binary_flips_correct_pct": 0.2635095633712469, + "val_binary_flips_total_pct": 0.49015493953929223, + "val_binary_flips_wrong_pct": 0.22664537616804536, + "val_biou": 0.4759289200408685, + "val_biou_gain": 0.06763933193191629, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8342104033128023, + "val_dice_gain": 0.03509001860652372, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7458006596828332, + "val_iou_gain": 0.04086944956446459, + "val_loss": -0.15559934312477708, + "val_refine_score": 0.6108647898618509, + "val_reward": 0.015559934312477708, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6174735075712807, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 4.783917159190718e-05, + "epoch": 81, + "epoch_seconds": 12.387441426049918, + "grad_norm": 0.7236001166430387, + "lr": 4.783917159190718e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6174735075712807, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.04125610159032724, + "mean_delta": -0.029689652062105863, + "near_zero_pct": 1.0973893955162401e-05, + "negative_pct": 90.61960313807835, + "positive_pct": 9.380388285287403 + }, + "train_actor_loss": -0.020577181766963226, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020577181639964692, + "train_ce_loss": 0.13058528913692993, + "train_critic_loss": 0.0, + "train_dice": 0.9260896008342933, + "train_dice_loss": 0.05710945346138694, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.871982262089384, + "train_loss": -0.20201792906631122, + "train_mask_delta_mean": 0.04126253995028409, + "train_mean_reward": 0.020577181766963226, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016664628346916288, + "val_binary_flips_correct_pct": 0.2948087804457721, + "val_binary_flips_total_pct": 0.5305009729721967, + "val_binary_flips_wrong_pct": 0.23569219252642465, + "val_biou": 0.4832310171997476, + "val_biou_gain": 0.07494142909079538, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8379996991425657, + "val_dice_gain": 0.038879314436287116, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.751715997942814, + "val_iou_gain": 0.046784787824445395, + "val_loss": -0.16664628346916288, + "val_refine_score": 0.6174735075712807, + "val_reward": 0.016664628346916288, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6186344780252565, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6154892618853953, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 4.5667363905408535e-05, + "epoch": 82, + "epoch_seconds": 12.368223979137838, + "grad_norm": 0.6864613023671237, + "lr": 4.5667363905408535e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6154892618853953, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03844412640583786, + "mean_delta": -0.026846404462544757, + "near_zero_pct": 1.4449611285272113e-06, + "negative_pct": 90.82012494856662, + "positive_pct": 9.179875432428988 + }, + "train_actor_loss": -0.020792826065603134, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020792825980937447, + "train_ce_loss": 0.12822821871800857, + "train_critic_loss": 0.0, + "train_dice": 0.92830181326113, + "train_dice_loss": 0.05557318709113381, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8745320922924712, + "train_loss": -0.2042522362687371, + "train_mask_delta_mean": 0.038457697088068184, + "train_mean_reward": 0.020792826065603134, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016369573073461652, + "val_binary_flips_correct_pct": 0.28441186044730393, + "val_binary_flips_total_pct": 0.527512793447457, + "val_binary_flips_wrong_pct": 0.24310093300015317, + "val_biou": 0.4802216256574256, + "val_biou_gain": 0.07193203754847338, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8374187372546605, + "val_dice_gain": 0.038298352548381986, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.750756898113365, + "val_iou_gain": 0.04582568799499642, + "val_loss": -0.16369573073461652, + "val_refine_score": 0.6154892618853953, + "val_reward": 0.016369573073461652, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.620316622280739, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 4.3532170940548435e-05, + "epoch": 83, + "epoch_seconds": 12.434038217179477, + "grad_norm": 0.7424441521817987, + "lr": 4.3532170940548435e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.620316622280739, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03825307815251025, + "mean_delta": -0.02649868366477842, + "near_zero_pct": 8.669766771163268e-06, + "negative_pct": 90.56679592891173, + "positive_pct": 9.433197611096231 + }, + "train_actor_loss": -0.02101261092254638, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021012610795547847, + "train_ce_loss": 0.12894479320807892, + "train_critic_loss": 0.0, + "train_dice": 0.9279535210399289, + "train_dice_loss": 0.05527793819254095, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8745320876733964, + "train_loss": -0.20644165169108997, + "train_mask_delta_mean": 0.03824129971590909, + "train_mean_reward": 0.02101261092254638, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016637478416669182, + "val_binary_flips_correct_pct": 0.2930136287913603, + "val_binary_flips_total_pct": 0.5030501122568168, + "val_binary_flips_wrong_pct": 0.2100364834654565, + "val_biou": 0.4867418493631939, + "val_biou_gain": 0.0784522612542417, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8395736418603873, + "val_dice_gain": 0.040453257154108746, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7538913951982842, + "val_iou_gain": 0.04896018507991562, + "val_loss": -0.16637478416669182, + "val_refine_score": 0.620316622280739, + "val_reward": 0.016637478416669182, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6175445742220145, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 4.143505605192989e-05, + "epoch": 84, + "epoch_seconds": 12.319783667102456, + "grad_norm": 0.7442594062198292, + "lr": 4.143505605192989e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6175445742220145, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038724959743293846, + "mean_delta": -0.027429347053508867, + "near_zero_pct": 2.167441692790817e-05, + "negative_pct": 90.70971079848029, + "positive_pct": 9.290270016274668 + }, + "train_actor_loss": -0.0205681504177681, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02056815054476663, + "train_ce_loss": 0.13037393174388193, + "train_critic_loss": 0.0, + "train_dice": 0.9263869273830307, + "train_dice_loss": 0.05623616413636641, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.871809032312156, + "train_loss": -0.20194930380040949, + "train_mask_delta_mean": 0.038726806640625, + "train_mean_reward": 0.0205681504177681, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016375309060094878, + "val_binary_flips_correct_pct": 0.2845838958141851, + "val_binary_flips_total_pct": 0.5061991074505974, + "val_binary_flips_wrong_pct": 0.22161521163641237, + "val_biou": 0.4831325327402219, + "val_biou_gain": 0.07484294463126967, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8383750385311609, + "val_dice_gain": 0.03925465382488236, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7519566157038071, + "val_iou_gain": 0.04702540558543855, + "val_loss": -0.16375309060094878, + "val_refine_score": 0.6175445742220145, + "val_reward": 0.016375309060094878, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6181413832298093, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 3.93774564973442e-05, + "epoch": 85, + "epoch_seconds": 12.361965486314148, + "grad_norm": 0.7204070037061517, + "lr": 3.93774564973442e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6181413832298093, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.040219978810372675, + "mean_delta": -0.029208601240746, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.71623594923453, + "positive_pct": 9.283752045170827 + }, + "train_actor_loss": -0.020761771671294064, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020761771417297, + "train_ce_loss": 0.12652837891470303, + "train_critic_loss": 0.0, + "train_dice": 0.9254242269227585, + "train_dice_loss": 0.055217390710657295, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8715517598383435, + "train_loss": -0.2039828043092381, + "train_mask_delta_mean": 0.04022216796875, + "train_mean_reward": 0.020761771671294064, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.40438166523182933, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016509045686689205, + "val_binary_flips_correct_pct": 0.28486064836090685, + "val_binary_flips_total_pct": 0.5048265644148284, + "val_binary_flips_wrong_pct": 0.21996591605392157, + "val_biou": 0.4837096655319948, + "val_biou_gain": 0.07542007742304258, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8386174348028032, + "val_dice_gain": 0.0394970500965246, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7525731009276239, + "val_iou_gain": 0.047641890809255294, + "val_loss": -0.16509045686689205, + "val_refine_score": 0.6181413832298093, + "val_reward": 0.016509045686689205, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6143421685079071, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 3.736078245274676e-05, + "epoch": 86, + "epoch_seconds": 12.34552408894524, + "grad_norm": 0.760752569545399, + "lr": 3.736078245274676e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6143421685079071, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.039019608150490305, + "mean_delta": -0.02834562184712426, + "near_zero_pct": 1.4293399239952784e-05, + "negative_pct": 90.73975431648168, + "positive_pct": 9.260233593257992 + }, + "train_actor_loss": -0.020467231405994178, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02046723132132849, + "train_ce_loss": 0.13304570926861328, + "train_critic_loss": 0.0, + "train_dice": 0.9212927472843083, + "train_dice_loss": 0.05767083168029785, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8669852532672127, + "train_loss": -0.2008579969406128, + "train_mask_delta_mean": 0.039018110795454544, + "train_mean_reward": 0.020467231405994178, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.8068437984382565, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016290277082589455, + "val_binary_flips_correct_pct": 0.29318566415824143, + "val_binary_flips_total_pct": 0.5515865251129749, + "val_binary_flips_wrong_pct": 0.25840086095473347, + "val_biou": 0.47871605202720197, + "val_biou_gain": 0.07042646391824975, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8368052598845298, + "val_dice_gain": 0.037684875178251254, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7499682849886123, + "val_iou_gain": 0.045037074870243776, + "val_loss": -0.16290277082589455, + "val_refine_score": 0.6143421685079071, + "val_reward": 0.016290277082589455, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6169723367020672, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 3.5386416045792574e-05, + "epoch": 87, + "epoch_seconds": 12.338594441767782, + "grad_norm": 0.7000052820552479, + "lr": 3.5386416045792574e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6169723367020672, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038721794304861265, + "mean_delta": -0.028093051631003618, + "near_zero_pct": 2.8899222570544225e-06, + "negative_pct": 90.67116779359904, + "positive_pct": 9.328831207345832 + }, + "train_actor_loss": -0.02111287983213763, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02111287983213763, + "train_ce_loss": 0.1341911947185343, + "train_critic_loss": 0.0, + "train_dice": 0.9266517224165813, + "train_dice_loss": 0.05773800611495972, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8726449338900223, + "train_loss": -0.20729020508852872, + "train_mask_delta_mean": 0.038712935014204544, + "train_mean_reward": 0.02111287983213763, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.2149877201935107, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016406598631874658, + "val_binary_flips_correct_pct": 0.30086367738013176, + "val_binary_flips_total_pct": 0.5397983625823376, + "val_binary_flips_wrong_pct": 0.2389346852022059, + "val_biou": 0.48247710246340547, + "val_biou_gain": 0.07418751435445325, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8380537335032826, + "val_dice_gain": 0.03893334879700405, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7514675709407289, + "val_iou_gain": 0.046536360822360345, + "val_loss": -0.16406598631874658, + "val_refine_score": 0.6169723367020672, + "val_reward": 0.016406598631874658, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.61667462939977, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 3.3455710408595215e-05, + "epoch": 88, + "epoch_seconds": 12.317939504981041, + "grad_norm": 0.8164774721319025, + "lr": 3.3455710408595215e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.61667462939977, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03593371355567466, + "mean_delta": -0.02469325853003697, + "near_zero_pct": 2.456433918496259e-05, + "negative_pct": 90.71461179039694, + "positive_pct": 9.285366094925187 + }, + "train_actor_loss": -0.02132539565024093, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021325395311578177, + "train_ce_loss": 0.13079174133864316, + "train_critic_loss": 0.0, + "train_dice": 0.9260853928234231, + "train_dice_loss": 0.056487202644348145, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8734841764156601, + "train_loss": -0.20950837568803268, + "train_mask_delta_mean": 0.03592751242897727, + "train_mean_reward": 0.02132539565024093, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.686553050763905, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01635080884443596, + "val_binary_flips_correct_pct": 0.29704898011450676, + "val_binary_flips_total_pct": 0.5325840968711704, + "val_binary_flips_wrong_pct": 0.2355351167566636, + "val_biou": 0.48112587196511303, + "val_biou_gain": 0.07283628385616081, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8383812323682381, + "val_dice_gain": 0.039260847661959586, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7522233868344269, + "val_iou_gain": 0.04729217671605834, + "val_loss": -0.1635080884443596, + "val_refine_score": 0.61667462939977, + "val_reward": 0.01635080884443596, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6145984029299063, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 6, + "encoder_lr": 3.156998875035742e-05, + "epoch": 89, + "epoch_seconds": 12.358571399003267, + "grad_norm": 0.7857756181196733, + "lr": 3.156998875035742e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6145984029299063, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0403267853808674, + "mean_delta": -0.029239803658459674, + "near_zero_pct": 9.099349798899228e-06, + "negative_pct": 90.7014858993617, + "positive_pct": 9.298507327383215 + }, + "train_actor_loss": -0.021168413762511176, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021168413529680533, + "train_ce_loss": 0.1290915378115394, + "train_critic_loss": 0.0, + "train_dice": 0.9250767928232904, + "train_dice_loss": 0.056289141828363594, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8720271267187799, + "train_loss": -0.20797652548009699, + "train_mask_delta_mean": 0.040319269353693184, + "train_mean_reward": 0.021168413762511176, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01600441037589917, + "val_binary_flips_correct_pct": 0.28097863290824143, + "val_binary_flips_total_pct": 0.5137499640969669, + "val_binary_flips_wrong_pct": 0.2327713311887255, + "val_biou": 0.4784072300758304, + "val_biou_gain": 0.0701176419668782, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8374814910851585, + "val_dice_gain": 0.038361106378879906, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7507895757839822, + "val_iou_gain": 0.04585836566561363, + "val_loss": -0.1600441037589917, + "val_refine_score": 0.6145984029299063, + "val_reward": 0.01600441037589917, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6175790845096195, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 7, + "encoder_lr": 2.973054345050999e-05, + "epoch": 90, + "epoch_seconds": 12.368225872982293, + "grad_norm": 0.8796306577595797, + "lr": 2.973054345050999e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6175790845096195, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03814556644382802, + "mean_delta": -0.026663756887005133, + "near_zero_pct": 2.108862172566329e-05, + "negative_pct": 90.7274598425085, + "positive_pct": 9.272521327842366 + }, + "train_actor_loss": -0.021254531036406246, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021254531036406246, + "train_ce_loss": 0.12222348966381767, + "train_critic_loss": 0.0, + "train_dice": 0.9282215169615566, + "train_dice_loss": 0.05340692130002109, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.874987459219211, + "train_loss": -0.20903270623900674, + "train_mask_delta_mean": 0.03813587535511364, + "train_mean_reward": 0.021254531036406246, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016597937617916614, + "val_binary_flips_correct_pct": 0.3022100411209406, + "val_binary_flips_total_pct": 0.5533966363645066, + "val_binary_flips_wrong_pct": 0.2511865952435662, + "val_biou": 0.4825504264464485, + "val_biou_gain": 0.0742608383374963, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8387508222021017, + "val_dice_gain": 0.03963043749582318, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7526077425727905, + "val_iou_gain": 0.04767653245442194, + "val_loss": -0.16597937617916614, + "val_refine_score": 0.6175790845096195, + "val_reward": 0.016597937617916614, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.620316622280739, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6188113519629206, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 8, + "encoder_lr": 2.7938635172978998e-05, + "epoch": 91, + "epoch_seconds": 12.306539231911302, + "grad_norm": 0.7785593596371737, + "lr": 2.7938635172978998e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6188113519629206, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03950302620333704, + "mean_delta": -0.02812342580661855, + "near_zero_pct": 1.3004650156744901e-05, + "negative_pct": 90.58789123188366, + "positive_pct": 9.41209780390967 + }, + "train_actor_loss": -0.020944214787133122, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.020944214702467434, + "train_ce_loss": 0.1307950412685221, + "train_critic_loss": 0.0, + "train_dice": 0.926181536373261, + "train_dice_loss": 0.05639778483997692, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8731370365206564, + "train_loss": -0.20569829778237778, + "train_mask_delta_mean": 0.03950084339488636, + "train_mean_reward": 0.020944214787133122, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4971591057255864, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01658816206327174, + "val_binary_flips_correct_pct": 0.29725467457490806, + "val_binary_flips_total_pct": 0.5129384059532016, + "val_binary_flips_wrong_pct": 0.2156837313782935, + "val_biou": 0.4851565449653826, + "val_biou_gain": 0.07686695685643036, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8383505077793476, + "val_dice_gain": 0.039230123073069056, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7524661589604585, + "val_iou_gain": 0.047534948842089975, + "val_loss": -0.16588162063271739, + "val_refine_score": 0.6188113519629206, + "val_reward": 0.01658816206327174, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6204769856270771, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6204769856270771, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 2.6195492002190097e-05, + "epoch": 92, + "epoch_seconds": 12.312104221433401, + "grad_norm": 0.7725747336040844, + "lr": 2.6195492002190097e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6204769856270771, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03879138416695324, + "mean_delta": -0.027389361628923903, + "near_zero_pct": 1.155968902821769e-05, + "negative_pct": 90.69852212613279, + "positive_pct": 9.301468552174894 + }, + "train_actor_loss": -0.021441850704088047, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021441850407758135, + "train_ce_loss": 0.12850249897349963, + "train_critic_loss": 0.0, + "train_dice": 0.9257369045402367, + "train_dice_loss": 0.05636531656438654, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8726748845300425, + "train_loss": -0.2107211473313245, + "train_mask_delta_mean": 0.03879616477272727, + "train_mean_reward": 0.021441850704088047, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.28856982773339207, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016995596059132367, + "val_binary_flips_correct_pct": 0.311578488817402, + "val_binary_flips_total_pct": 0.5413392010857077, + "val_binary_flips_wrong_pct": 0.22976071226830574, + "val_biou": 0.4872013598569102, + "val_biou_gain": 0.07891177174795799, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8392319492912435, + "val_dice_gain": 0.0401115645849649, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7537526113972439, + "val_iou_gain": 0.048821401278875354, + "val_loss": -0.16995596059132367, + "val_refine_score": 0.6204769856270771, + "val_reward": 0.016995596059132367, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6204769856270771, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6203106182662208, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 2.450230860140054e-05, + "epoch": 93, + "epoch_seconds": 12.324069243855774, + "grad_norm": 0.8930463249033148, + "lr": 2.450230860140054e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6203106182662208, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.043872837908566, + "mean_delta": -0.03223375808870928, + "near_zero_pct": 1.155968902821769e-05, + "negative_pct": 90.67251160740852, + "positive_pct": 9.32747907089916 + }, + "train_actor_loss": -0.02124310057843104, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021243100663096728, + "train_ce_loss": 0.1275412623177875, + "train_critic_loss": 0.0, + "train_dice": 0.9271270379868911, + "train_dice_loss": 0.055408271876248444, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8730347118952779, + "train_loss": -0.2087720199064775, + "train_mask_delta_mean": 0.043878728693181816, + "train_mean_reward": 0.02124310057843104, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01673724429565482, + "val_binary_flips_correct_pct": 0.3010057935527727, + "val_binary_flips_total_pct": 0.5130917418236827, + "val_binary_flips_wrong_pct": 0.21208594827090993, + "val_biou": 0.4873598881067971, + "val_biou_gain": 0.07907029999784487, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8389855517141998, + "val_dice_gain": 0.0398651670079212, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7532613484256446, + "val_iou_gain": 0.04833013830727606, + "val_loss": -0.16737244295654818, + "val_refine_score": 0.6203106182662208, + "val_reward": 0.01673724429565482, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6204769856270771, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.619319978599113, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 2.286024539393689e-05, + "epoch": 94, + "epoch_seconds": 12.337438463699073, + "grad_norm": 0.7621191252361644, + "lr": 2.286024539393689e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.619319978599113, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03977200829169967, + "mean_delta": -0.028198921904814513, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.72341336445375, + "positive_pct": 9.276576670394702 + }, + "train_actor_loss": -0.021590824115264695, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02159082386126763, + "train_ce_loss": 0.13136035271666266, + "train_critic_loss": 0.0, + "train_dice": 0.9275658367318717, + "train_dice_loss": 0.0571596080606634, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8750672000051348, + "train_loss": -0.21213784272020514, + "train_mask_delta_mean": 0.039778275923295456, + "train_mean_reward": 0.021590824115264695, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016740986160584725, + "val_binary_flips_correct_pct": 0.3036686018401501, + "val_binary_flips_total_pct": 0.5556854547238816, + "val_binary_flips_wrong_pct": 0.2520168528837316, + "val_biou": 0.4855521335990647, + "val_biou_gain": 0.07726254549011247, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8389005628246955, + "val_dice_gain": 0.03978017811841694, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7530878235991613, + "val_iou_gain": 0.0481566134807927, + "val_loss": -0.16740986160584725, + "val_refine_score": 0.619319978599113, + "val_reward": 0.016740986160584725, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6213497507968575, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6213497507968575, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 2.1270427767898626e-05, + "epoch": 95, + "epoch_seconds": 12.297704639844596, + "grad_norm": 0.9016645117239519, + "lr": 2.1270427767898626e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6213497507968575, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037418574475767935, + "mean_delta": -0.02574881430799988, + "near_zero_pct": 1.8784494670853746e-05, + "negative_pct": 90.74269451878287, + "positive_pct": 9.257288950241424 + }, + "train_actor_loss": -0.021450253216740253, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021450253110908143, + "train_ce_loss": 0.12696013870564374, + "train_critic_loss": 0.0, + "train_dice": 0.9276385439502431, + "train_dice_loss": 0.05571463975039395, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8747029602999843, + "train_loss": -0.21084903857924722, + "train_mask_delta_mean": 0.037409002130681816, + "train_mean_reward": 0.021450253216740253, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01690453290939331, + "val_binary_flips_correct_pct": 0.3044390210918352, + "val_binary_flips_total_pct": 0.5321689680510876, + "val_binary_flips_wrong_pct": 0.22772994695925244, + "val_biou": 0.4880102026312071, + "val_biou_gain": 0.07972061452225487, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8399946163964889, + "val_dice_gain": 0.040874231690210316, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.754689298962508, + "val_iou_gain": 0.04975808884413946, + "val_loss": -0.1690453290939331, + "val_refine_score": 0.6213497507968575, + "val_reward": 0.01690453290939331, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6213497507968575, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6208828200145066, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 1.973394530487351e-05, + "epoch": 96, + "epoch_seconds": 12.378536198753864, + "grad_norm": 0.7914921641349792, + "lr": 1.973394530487351e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6208828200145066, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.039162508296695625, + "mean_delta": -0.027443895455111156, + "near_zero_pct": 1.2418855083689612e-05, + "negative_pct": 90.67664986306971, + "positive_pct": 9.323339926248247 + }, + "train_actor_loss": -0.02184443116394422, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021844431333275596, + "train_ce_loss": 0.12921016866510565, + "train_critic_loss": 0.0, + "train_dice": 0.9297465805332988, + "train_dice_loss": 0.05582451278513128, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.878170213478105, + "train_loss": -0.21474361555142837, + "train_mask_delta_mean": 0.03916515003551136, + "train_mean_reward": 0.02184443116394422, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016705179572454654, + "val_binary_flips_correct_pct": 0.3078011905445772, + "val_binary_flips_total_pct": 0.5417730294021905, + "val_binary_flips_wrong_pct": 0.23397183885761336, + "val_biou": 0.48755080252011035, + "val_biou_gain": 0.07926121441115813, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8397326544422046, + "val_dice_gain": 0.04061226973592602, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7542148375089027, + "val_iou_gain": 0.04928362739053416, + "val_loss": -0.16705179572454654, + "val_refine_score": 0.6208828200145066, + "val_reward": 0.016705179572454654, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6213497507968575, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6210168622462812, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 1.8251851033192653e-05, + "epoch": 97, + "epoch_seconds": 12.359559831675142, + "grad_norm": 0.7541547092524442, + "lr": 1.8251851033192653e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6210168622462812, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03804121416231448, + "mean_delta": -0.027201272758909247, + "near_zero_pct": 3.0344183699071436e-05, + "negative_pct": 90.70525629953904, + "positive_pct": 9.294715489853512 + }, + "train_actor_loss": -0.02151460003700446, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021514599952338773, + "train_ce_loss": 0.12570774893869052, + "train_critic_loss": 0.0, + "train_dice": 0.9268246368133267, + "train_dice_loss": 0.055051359263333405, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8746178379622114, + "train_loss": -0.21153081276200034, + "train_mask_delta_mean": 0.03804432262073864, + "train_mean_reward": 0.02151460003700446, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.6392045645043254, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016764260668423958, + "val_binary_flips_correct_pct": 0.30650344549440867, + "val_binary_flips_total_pct": 0.5339641197054994, + "val_binary_flips_wrong_pct": 0.22746067421109067, + "val_biou": 0.48778414068523646, + "val_biou_gain": 0.07949455257628424, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.839751473004052, + "val_dice_gain": 0.0406310882977734, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7542495838073259, + "val_iou_gain": 0.04931837368895731, + "val_loss": -0.16764260668423958, + "val_refine_score": 0.6210168622462812, + "val_reward": 0.016764260668423958, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6220454716938264, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6220454716938264, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 1.682516070623759e-05, + "epoch": 98, + "epoch_seconds": 12.32860478432849, + "grad_norm": 0.8426002697511152, + "lr": 1.682516070623759e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6220454716938264, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03978384324264797, + "mean_delta": -0.02897723063572564, + "near_zero_pct": 1.3434233184480862e-05, + "negative_pct": 90.78912850130688, + "positive_pct": 9.210860111158002 + }, + "train_actor_loss": -0.021695262998533013, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021695262829201634, + "train_ce_loss": 0.1275546889413487, + "train_critic_loss": 0.0, + "train_dice": 0.9270972172897454, + "train_dice_loss": 0.05574807253750888, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8747992380009046, + "train_loss": -0.21328657865524292, + "train_mask_delta_mean": 0.039778275923295456, + "train_mean_reward": 0.021695262998533013, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016998441904434003, + "val_binary_flips_correct_pct": 0.31165702670228246, + "val_binary_flips_total_pct": 0.5382500442804075, + "val_binary_flips_wrong_pct": 0.226593017578125, + "val_biou": 0.48926744353631596, + "val_biou_gain": 0.08097785542736374, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8401049404669908, + "val_dice_gain": 0.04098455576071225, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7548234998513369, + "val_iou_gain": 0.04989228973296833, + "val_loss": -0.16998441904434003, + "val_refine_score": 0.6220454716938264, + "val_reward": 0.016998441904434003, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6220454716938264, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6198926642484122, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 1.5454852106293665e-05, + "epoch": 99, + "epoch_seconds": 12.353585476055741, + "grad_norm": 0.7860453453930941, + "lr": 1.5454852106293665e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6198926642484122, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03709692359817299, + "mean_delta": -0.025800924367186697, + "near_zero_pct": 2.456433918496259e-05, + "negative_pct": 90.72211107069796, + "positive_pct": 9.277866687625647 + }, + "train_actor_loss": -0.021733195667779495, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021733195413782432, + "train_ce_loss": 0.1264658963138407, + "train_critic_loss": 0.0, + "train_dice": 0.9287363628585525, + "train_dice_loss": 0.05569311705502597, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8758780112062025, + "train_loss": -0.21368878131563013, + "train_mask_delta_mean": 0.03708163174715909, + "train_mean_reward": 0.021733195667779495, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3807074221020395, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01674832182470709, + "val_binary_flips_correct_pct": 0.3131791657092524, + "val_binary_flips_total_pct": 0.5642273846794577, + "val_binary_flips_wrong_pct": 0.2510482189702053, + "val_biou": 0.4860768315300528, + "val_biou_gain": 0.0777872434211006, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8392280765928183, + "val_dice_gain": 0.04010769188653973, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7537084969667716, + "val_iou_gain": 0.04877728684840299, + "val_loss": -0.1674832182470709, + "val_refine_score": 0.6198926642484122, + "val_reward": 0.01674832182470709, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6220454716938264, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6185777706011313, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 1.4141864374426834e-05, + "epoch": 100, + "epoch_seconds": 12.331408322788775, + "grad_norm": 0.7757869037714872, + "lr": 1.4141864374426834e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6185777706011313, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03978460083122958, + "mean_delta": -0.028464386239647865, + "near_zero_pct": 8.669766771163268e-06, + "negative_pct": 90.67793833938512, + "positive_pct": 9.322055403820492 + }, + "train_actor_loss": -0.021708240424314598, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02170824055131313, + "train_ce_loss": 0.13003888726234436, + "train_critic_loss": 0.0, + "train_dice": 0.9286428490524768, + "train_dice_loss": 0.05645065957849676, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8760742079377346, + "train_loss": -0.213352616537701, + "train_mask_delta_mean": 0.03978382457386364, + "train_mean_reward": 0.021708240424314598, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016488855457282625, + "val_binary_flips_correct_pct": 0.30273362702014395, + "val_binary_flips_total_pct": 0.5403369080786611, + "val_binary_flips_wrong_pct": 0.23760328105851714, + "val_biou": 0.4843442237784591, + "val_biou_gain": 0.07605463566950688, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8385848769115863, + "val_dice_gain": 0.03946449220530779, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7528113174238034, + "val_iou_gain": 0.047880107305434794, + "val_loss": -0.16488855457282625, + "val_refine_score": 0.6185777706011313, + "val_reward": 0.016488855457282625, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6220454716938264, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6206538749267603, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 1.2887097366843346e-05, + "epoch": 101, + "epoch_seconds": 12.362513654865324, + "grad_norm": 0.8472232493487272, + "lr": 1.2887097366843346e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6206538749267603, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.040563217787580055, + "mean_delta": -0.02909491532905535, + "near_zero_pct": 1.4879194313008073e-05, + "negative_pct": 90.71092382073402, + "positive_pct": 9.289063530212099 + }, + "train_actor_loss": -0.02184587003615558, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02184587003615558, + "train_ce_loss": 0.12467538768594916, + "train_critic_loss": 0.0, + "train_dice": 0.9293389093428637, + "train_dice_loss": 0.05423813516443426, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8777716701856279, + "train_loss": -0.21488042717630212, + "train_mask_delta_mean": 0.04054953835227273, + "train_mean_reward": 0.02184587003615558, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016670802666340023, + "val_binary_flips_correct_pct": 0.30687369552313115, + "val_binary_flips_total_pct": 0.5437102972292434, + "val_binary_flips_wrong_pct": 0.23683660170611215, + "val_biou": 0.4873234100398022, + "val_biou_gain": 0.07903382193084996, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8394568979086233, + "val_dice_gain": 0.04033651320234477, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7539843398137184, + "val_iou_gain": 0.049053129695349806, + "val_loss": -0.16670802666340023, + "val_refine_score": 0.6206538749267603, + "val_reward": 0.016670802666340023, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6220454716938264, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6205137949734718, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 1.1691411038173145e-05, + "epoch": 102, + "epoch_seconds": 12.368855305947363, + "grad_norm": 0.7311998443170027, + "lr": 1.1691411038173145e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6205137949734718, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038177369204773146, + "mean_delta": -0.02695128863508051, + "near_zero_pct": 2.253358298338009e-05, + "negative_pct": 90.70868431167169, + "positive_pct": 9.29129547862844 + }, + "train_actor_loss": -0.021846965823153205, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021846965950151735, + "train_ce_loss": 0.13125095584175803, + "train_critic_loss": 0.0, + "train_dice": 0.9274380175814653, + "train_dice_loss": 0.05774885416030884, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8746879770332151, + "train_loss": -0.2146896557374434, + "train_mask_delta_mean": 0.03818026455965909, + "train_mean_reward": 0.021846965823153205, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.35511364694684744, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01684001243847888, + "val_binary_flips_correct_pct": 0.3124424055510876, + "val_binary_flips_total_pct": 0.5604089475145526, + "val_binary_flips_wrong_pct": 0.24796654196346507, + "val_biou": 0.48776953318981753, + "val_biou_gain": 0.07947994508086531, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8389254495978783, + "val_dice_gain": 0.03980506489159974, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7532580567571261, + "val_iou_gain": 0.048326846638757526, + "val_loss": -0.1684001243847888, + "val_refine_score": 0.6205137949734718, + "val_reward": 0.01684001243847888, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": true, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6222497408569307, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 0, + "encoder_lr": 1.0555624852100071e-05, + "epoch": 103, + "epoch_seconds": 12.362702250946313, + "grad_norm": 0.8135370449586348, + "lr": 1.0555624852100071e-05, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6222497408569307, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0374672467905012, + "mean_delta": -0.0261618071870709, + "near_zero_pct": 8.669766771163268e-06, + "negative_pct": 90.66936488855968, + "positive_pct": 9.330628837712787 + }, + "train_actor_loss": -0.02191791507621846, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021917914737555708, + "train_ce_loss": 0.12844116376204925, + "train_critic_loss": 0.0, + "train_dice": 0.9288579039170684, + "train_dice_loss": 0.05613429979844527, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8764019270018126, + "train_loss": -0.21548764272169632, + "train_mask_delta_mean": 0.037461714311079544, + "train_mean_reward": 0.02191791507621846, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.35511364694684744, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01704225441790186, + "val_binary_flips_correct_pct": 0.31479106229894305, + "val_binary_flips_total_pct": 0.5680570415422028, + "val_binary_flips_wrong_pct": 0.2532659792432598, + "val_biou": 0.489678026989837, + "val_biou_gain": 0.08138843888088476, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8398065075755548, + "val_dice_gain": 0.0406861228692762, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7548214547240245, + "val_iou_gain": 0.04989024460565594, + "val_loss": -0.1704225441790186, + "val_refine_score": 0.6222497408569307, + "val_reward": 0.01704225441790186, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6204137699458314, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 1, + "encoder_lr": 9.480517219742217e-06, + "epoch": 104, + "epoch_seconds": 12.396004824899137, + "grad_norm": 0.8026019659909335, + "lr": 9.480517219742217e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6204137699458314, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03820391922173175, + "mean_delta": -0.026933450484648347, + "near_zero_pct": 1.4449611285272113e-05, + "negative_pct": 90.71129343726419, + "positive_pct": 9.288694243878126 + }, + "train_actor_loss": -0.022324600426310844, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022324600553309374, + "train_ce_loss": 0.12544941902160645, + "train_critic_loss": 0.0, + "train_dice": 0.9292990291693464, + "train_dice_loss": 0.05521126768805764, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8776982168600923, + "train_loss": -0.21963279220190915, + "train_mask_delta_mean": 0.03821078213778409, + "train_mean_reward": 0.022324600426310844, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01681099447887391, + "val_binary_flips_correct_pct": 0.31271541819852944, + "val_binary_flips_total_pct": 0.5610335106943168, + "val_binary_flips_wrong_pct": 0.2483180924957874, + "val_biou": 0.48755928076771404, + "val_biou_gain": 0.07926969265876183, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8389670552449227, + "val_dice_gain": 0.0398466705386441, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7532682591239489, + "val_iou_gain": 0.048337049005580335, + "val_loss": -0.16810994478873909, + "val_refine_score": 0.6204137699458314, + "val_reward": 0.01681099447887391, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6194035294891669, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 2, + "encoder_lr": 8.466824966168052e-06, + "epoch": 105, + "epoch_seconds": 12.326854449696839, + "grad_norm": 0.7858515110882845, + "lr": 8.466824966168052e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6194035294891669, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03741268847476353, + "mean_delta": -0.026115027150477876, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.71392295035449, + "positive_pct": 9.286067431623286 + }, + "train_actor_loss": -0.021533648266499353, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021533648245332934, + "train_ce_loss": 0.13310579684647647, + "train_critic_loss": 0.0, + "train_dice": 0.9266597906451044, + "train_dice_loss": 0.05781936103647405, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8736745780199793, + "train_loss": -0.21151798150756143, + "train_mask_delta_mean": 0.037420099431818184, + "train_mean_reward": 0.021533648266499353, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016624928219243884, + "val_binary_flips_correct_pct": 0.3102732639686734, + "val_binary_flips_total_pct": 0.5653830135569853, + "val_binary_flips_wrong_pct": 0.2551097495883119, + "val_biou": 0.4862522820098852, + "val_biou_gain": 0.07796269390093297, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8384493976162458, + "val_dice_gain": 0.039329012909967265, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7525547769684486, + "val_iou_gain": 0.04762356685008007, + "val_loss": -0.16624928219243884, + "val_refine_score": 0.6194035294891669, + "val_reward": 0.016624928219243884, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6184197354464811, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 3, + "encoder_lr": 7.515242825413071e-06, + "epoch": 106, + "epoch_seconds": 12.324791169725358, + "grad_norm": 0.780386670069261, + "lr": 7.515242825413071e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6184197354464811, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03713098155673255, + "mean_delta": -0.02575069200247526, + "near_zero_pct": 2.0229455799380958e-05, + "negative_pct": 90.71204628456722, + "positive_pct": 9.287935715507377 + }, + "train_actor_loss": -0.022096217320226555, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022096217277893713, + "train_ce_loss": 0.12264466353438118, + "train_critic_loss": 0.0, + "train_dice": 0.9315994970967798, + "train_dice_loss": 0.05437477610327981, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.879141951805486, + "train_loss": -0.21742178093303333, + "train_mask_delta_mean": 0.03712047230113636, + "train_mean_reward": 0.022096217320226555, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016539778414880857, + "val_binary_flips_correct_pct": 0.30599107929304536, + "val_binary_flips_total_pct": 0.5570168588675706, + "val_binary_flips_wrong_pct": 0.2510257795745251, + "val_biou": 0.4851306444222936, + "val_biou_gain": 0.07684105631334137, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8378875027962098, + "val_dice_gain": 0.038767118089931274, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7517088264706685, + "val_iou_gain": 0.04677761635229993, + "val_loss": -0.16539778414880857, + "val_refine_score": 0.6184197354464811, + "val_reward": 0.016539778414880857, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6182313313773651, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 4, + "encoder_lr": 6.626422964343979e-06, + "epoch": 107, + "epoch_seconds": 12.352198167238384, + "grad_norm": 0.7531130042943087, + "lr": 6.626422964343979e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6182313313773651, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037209427703849295, + "mean_delta": -0.02600584384477274, + "near_zero_pct": 1.2418855083689612e-05, + "negative_pct": 90.7252006910064, + "positive_pct": 9.274788962846452 + }, + "train_actor_loss": -0.022110511720794337, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022110511720794337, + "train_ce_loss": 0.12281317602504384, + "train_critic_loss": 0.0, + "train_dice": 0.9296505200412013, + "train_dice_loss": 0.05393739180131392, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8777059607416935, + "train_loss": -0.21757010167295282, + "train_mask_delta_mean": 0.037214799360795456, + "train_mean_reward": 0.022110511720794337, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3077651606872678, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01662052886968013, + "val_binary_flips_correct_pct": 0.31257330202588846, + "val_binary_flips_total_pct": 0.5690892537434896, + "val_binary_flips_wrong_pct": 0.2565159517176011, + "val_biou": 0.4849580240300422, + "val_biou_gain": 0.07666843592108996, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8377264065720424, + "val_dice_gain": 0.038606021865763895, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7515046387246879, + "val_iou_gain": 0.0465734286063193, + "val_loss": -0.1662052886968013, + "val_refine_score": 0.6182313313773651, + "val_reward": 0.01662052886968013, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6185301695730886, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 5, + "encoder_lr": 5.80097453569599e-06, + "epoch": 108, + "epoch_seconds": 12.408369511831552, + "grad_norm": 0.7708127444440668, + "lr": 5.80097453569599e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6185301695730886, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03857835407622836, + "mean_delta": -0.027330335864627905, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.66371267492121, + "positive_pct": 9.336277630857445 + }, + "train_actor_loss": -0.021973111252670853, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.0219731112950037, + "train_ce_loss": 0.12566176598722284, + "train_critic_loss": 0.0, + "train_dice": 0.9287440604680346, + "train_dice_loss": 0.0556935342875394, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8769926160545692, + "train_loss": -0.21610400487076153, + "train_mask_delta_mean": 0.03858531605113636, + "train_mean_reward": 0.021973111252670853, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016643285678583197, + "val_binary_flips_correct_pct": 0.31050139782475494, + "val_binary_flips_total_pct": 0.5633859073414522, + "val_binary_flips_wrong_pct": 0.2528845095166973, + "val_biou": 0.4852067472065138, + "val_biou_gain": 0.07691715909756158, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8379297264975708, + "val_dice_gain": 0.03880934179129225, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7518535919396634, + "val_iou_gain": 0.04692238182129482, + "val_loss": -0.16643285678583197, + "val_refine_score": 0.6185301695730886, + "val_reward": 0.016643285678583197, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6186608043295159, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 6, + "encoder_lr": 5.039463260590051e-06, + "epoch": 109, + "epoch_seconds": 12.388295252807438, + "grad_norm": 0.7412605719132856, + "lr": 5.039463260590051e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6186608043295159, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.039051464293152094, + "mean_delta": -0.027736548715355722, + "near_zero_pct": 1.0973893955162401e-05, + "negative_pct": 90.68164825439453, + "positive_pct": 9.318342847241597 + }, + "train_actor_loss": -0.022036218670440245, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022036218755105932, + "train_ce_loss": 0.1230550699613311, + "train_critic_loss": 0.0, + "train_dice": 0.9297884224029493, + "train_dice_loss": 0.054859616539695046, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8776899489266061, + "train_loss": -0.21680389209227127, + "train_mask_delta_mean": 0.039045854048295456, + "train_mean_reward": 0.022036218670440245, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.2367424312978983, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016676406710757874, + "val_binary_flips_correct_pct": 0.31083424886067706, + "val_binary_flips_total_pct": 0.5634420058306526, + "val_binary_flips_wrong_pct": 0.2526077569699755, + "val_biou": 0.4854820505188578, + "val_biou_gain": 0.07719246240990557, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8379363577430493, + "val_dice_gain": 0.03881597303677076, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7518395581401739, + "val_iou_gain": 0.046908348021805324, + "val_loss": -0.16676406710757874, + "val_refine_score": 0.6186608043295159, + "val_reward": 0.016676406710757874, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6191938983044711, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 7, + "encoder_lr": 4.342411040815753e-06, + "epoch": 110, + "epoch_seconds": 12.354709594044834, + "grad_norm": 0.7762014649131082, + "lr": 4.342411040815753e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6191938983044711, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038396379868076605, + "mean_delta": -0.02721949821253392, + "near_zero_pct": 2.210399995564413e-05, + "negative_pct": 90.75422571464019, + "positive_pct": 9.24575456672094 + }, + "train_actor_loss": -0.022310864037453113, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022310863995120268, + "train_ce_loss": 0.12847193262793802, + "train_critic_loss": 0.0, + "train_dice": 0.9296534684503104, + "train_dice_loss": 0.05632238496433605, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8781677749609811, + "train_loss": -0.21941275894641876, + "train_mask_delta_mean": 0.038416082208806816, + "train_mean_reward": 0.022310864037453113, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3807074221020395, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01675008179154247, + "val_binary_flips_correct_pct": 0.313407299565334, + "val_binary_flips_total_pct": 0.5652483771829044, + "val_binary_flips_wrong_pct": 0.25184107761757046, + "val_biou": 0.4862181085149866, + "val_biou_gain": 0.07792852040603437, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.83809077710126, + "val_dice_gain": 0.03897039239498146, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7521696880939557, + "val_iou_gain": 0.04723847797558711, + "val_loss": -0.1675008179154247, + "val_refine_score": 0.6191938983044711, + "val_reward": 0.01675008179154247, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6197862712387763, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 8, + "encoder_lr": 3.7102956011460347e-06, + "epoch": 111, + "epoch_seconds": 12.407163830008358, + "grad_norm": 0.7869118885560469, + "lr": 3.7102956011460347e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6197862712387763, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03814963369884274, + "mean_delta": -0.027051616079089316, + "near_zero_pct": 1.8198699597798456e-05, + "negative_pct": 90.7575897872448, + "positive_pct": 9.24239418554035 + }, + "train_actor_loss": -0.02196707401228857, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021967073969955727, + "train_ce_loss": 0.12764740125699478, + "train_critic_loss": 0.0, + "train_dice": 0.9264196422364653, + "train_dice_loss": 0.05622318116101352, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8745231324950198, + "train_loss": -0.2159933258186687, + "train_mask_delta_mean": 0.038152521306818184, + "train_mean_reward": 0.02196707401228857, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.7121468259190972, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016803963648271747, + "val_binary_flips_correct_pct": 0.3126256606158088, + "val_binary_flips_total_pct": 0.5622714173560048, + "val_binary_flips_wrong_pct": 0.24964575674019607, + "val_biou": 0.4865431722357755, + "val_biou_gain": 0.07825358412682326, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8386794078147112, + "val_dice_gain": 0.03955902310843262, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7530293702417771, + "val_iou_gain": 0.04809816012340851, + "val_loss": -0.16803963648271747, + "val_refine_score": 0.6197862712387763, + "val_reward": 0.016803963648271747, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.619851447566121, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 9, + "encoder_lr": 3.1435501619283377e-06, + "epoch": 112, + "epoch_seconds": 12.390039958059788, + "grad_norm": 0.765212514183738, + "lr": 3.1435501619283377e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.619851447566121, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037821982225233856, + "mean_delta": -0.026621870802376758, + "near_zero_pct": 1.3434233184480862e-05, + "negative_pct": 90.73560312390327, + "positive_pct": 9.264385759491812 + }, + "train_actor_loss": -0.022006240400845523, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022006240252680567, + "train_ce_loss": 0.12289212779565291, + "train_critic_loss": 0.0, + "train_dice": 0.9303274981699051, + "train_dice_loss": 0.054895205931230026, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8781351594798299, + "train_loss": -0.21650666269389066, + "train_mask_delta_mean": 0.03783069957386364, + "train_mean_reward": 0.022006240400845523, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016856698173796758, + "val_binary_flips_correct_pct": 0.31345965815525423, + "val_binary_flips_total_pct": 0.5593692555147058, + "val_binary_flips_wrong_pct": 0.24590959735945161, + "val_biou": 0.4866699670662935, + "val_biou_gain": 0.07838037895734129, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8387157909483793, + "val_dice_gain": 0.039595406242100784, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7530329280659486, + "val_iou_gain": 0.04810171794758, + "val_loss": -0.16856698173796758, + "val_refine_score": 0.619851447566121, + "val_reward": 0.016856698173796758, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6197477629689336, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 10, + "encoder_lr": 2.642563142177174e-06, + "epoch": 113, + "epoch_seconds": 12.335088413208723, + "grad_norm": 0.7795337221839211, + "lr": 2.642563142177174e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6197477629689336, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037869633810425345, + "mean_delta": -0.026697472457519987, + "near_zero_pct": 1.8198699597798456e-05, + "negative_pct": 90.77406850728121, + "positive_pct": 9.225915186107159 + }, + "train_actor_loss": -0.022119006988677112, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022119007200341333, + "train_ce_loss": 0.13039713081988422, + "train_critic_loss": 0.0, + "train_dice": 0.9268801758646317, + "train_dice_loss": 0.05754899978637695, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8752512943504439, + "train_loss": -0.2174311469901692, + "train_mask_delta_mean": 0.037866765802556816, + "train_mean_reward": 0.022119006988677112, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5681818351149559, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016845372039824724, + "val_binary_flips_correct_pct": 0.3131941253063726, + "val_binary_flips_total_pct": 0.5612429450539982, + "val_binary_flips_wrong_pct": 0.2480488197476256, + "val_biou": 0.48669595383881675, + "val_biou_gain": 0.07840636572986454, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8386234081047015, + "val_dice_gain": 0.03950302339842293, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7527995720990505, + "val_iou_gain": 0.047868361980681895, + "val_loss": -0.16845372039824724, + "val_refine_score": 0.6197477629689336, + "val_reward": 0.016845372039824724, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6203411166306545, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 11, + "encoder_lr": 2.2076778933709854e-06, + "epoch": 114, + "epoch_seconds": 12.331840894185007, + "grad_norm": 0.7451378323815085, + "lr": 2.2076778933709854e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6203411166306545, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03789205912669951, + "mean_delta": -0.026671088618141683, + "near_zero_pct": 2.0229455799380958e-05, + "negative_pct": 90.69822193546729, + "positive_pct": 9.301759963008491 + }, + "train_actor_loss": -0.022297663446145387, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022297663276814008, + "train_ce_loss": 0.11767559837211262, + "train_critic_loss": 0.0, + "train_dice": 0.9318903066532176, + "train_dice_loss": 0.05206996202468872, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8811203872425526, + "train_loss": -0.21958172863179987, + "train_mask_delta_mean": 0.037886186079545456, + "train_mean_reward": 0.022297663446145387, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.5445075919851661, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016906767705222592, + "val_binary_flips_correct_pct": 0.3147611431047028, + "val_binary_flips_total_pct": 0.5596908868527879, + "val_binary_flips_wrong_pct": 0.24492974374808518, + "val_biou": 0.4874455474049415, + "val_biou_gain": 0.07915595929598929, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8389401366416007, + "val_dice_gain": 0.03981975193532217, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7532366858563674, + "val_iou_gain": 0.048305475737998815, + "val_loss": -0.16906767705222592, + "val_refine_score": 0.6203411166306545, + "val_reward": 0.016906767705222592, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6199513237505204, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 12, + "encoder_lr": 1.8391924641363116e-06, + "epoch": 115, + "epoch_seconds": 12.31389290932566, + "grad_norm": 0.8020537007938732, + "lr": 1.8391924641363116e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6199513237505204, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.038047272838990794, + "mean_delta": -0.026762956351211124, + "near_zero_pct": 1.4879194313008073e-05, + "negative_pct": 90.6339054080573, + "positive_pct": 9.36608212915334 + }, + "train_actor_loss": -0.021896221278108318, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.021896221066444097, + "train_ce_loss": 0.1277384947646748, + "train_critic_loss": 0.0, + "train_dice": 0.9270307450390418, + "train_dice_loss": 0.05625994097102772, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.876056317278818, + "train_loss": -0.21528224511580032, + "train_mask_delta_mean": 0.038038773970170456, + "train_mean_reward": 0.021896221278108318, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.35511364694684744, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016894263288122602, + "val_binary_flips_correct_pct": 0.3173080145143995, + "val_binary_flips_total_pct": 0.564421859442019, + "val_binary_flips_wrong_pct": 0.24711384492761948, + "val_biou": 0.4871345408085916, + "val_biou_gain": 0.07884495269963937, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8386286821987696, + "val_dice_gain": 0.039508297492491073, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7527681066924492, + "val_iou_gain": 0.047836896574080634, + "val_loss": -0.16894263288122602, + "val_refine_score": 0.6199513237505204, + "val_reward": 0.016894263288122602, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6195518868943994, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 13, + "encoder_lr": 1.5373593959800896e-06, + "epoch": 116, + "epoch_seconds": 12.335723866708577, + "grad_norm": 0.7525642730972983, + "lr": 1.5373593959800896e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6195518868943994, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03793502099473368, + "mean_delta": -0.026665999003770677, + "near_zero_pct": 1.6324155441535286e-05, + "negative_pct": 90.64345955848694, + "positive_pct": 9.356526615606112 + }, + "train_actor_loss": -0.022353354023917662, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022353354256748306, + "train_ce_loss": 0.12318500740961595, + "train_critic_loss": 0.0, + "train_dice": 0.9298881686887929, + "train_dice_loss": 0.05394337394020774, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8788008954850629, + "train_loss": -0.2199909673495726, + "train_mask_delta_mean": 0.03794167258522727, + "train_mean_reward": 0.022353354023917662, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016835371454362758, + "val_binary_flips_correct_pct": 0.3158195346009498, + "val_binary_flips_total_pct": 0.5639468922334558, + "val_binary_flips_wrong_pct": 0.24812735763250615, + "val_biou": 0.48702375182708485, + "val_biou_gain": 0.07873416371813263, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8381815792761099, + "val_dice_gain": 0.03906119456983137, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.752080021961714, + "val_iou_gain": 0.047148811843345406, + "val_loss": -0.16835371454362758, + "val_refine_score": 0.6195518868943994, + "val_reward": 0.016835371454362758, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6194481805575691, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 14, + "encoder_lr": 1.3023855502103574e-06, + "epoch": 117, + "epoch_seconds": 12.355961726047099, + "grad_norm": 0.7476530454375527, + "lr": 1.3023855502103574e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6194481805575691, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037838863166557116, + "mean_delta": -0.02670602388256653, + "near_zero_pct": 2.1674416798718582e-05, + "negative_pct": 90.68485633893447, + "positive_pct": 9.315124264156276 + }, + "train_actor_loss": -0.02200758677050048, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022007586707001214, + "train_ce_loss": 0.12359001284295862, + "train_critic_loss": 0.0, + "train_dice": 0.9281656176544653, + "train_dice_loss": 0.05547327345067805, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8760765442420423, + "train_loss": -0.2164946049451828, + "train_mask_delta_mean": 0.037847345525568184, + "train_mean_reward": 0.02200758677050048, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.3314394038170576, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01682901309686713, + "val_binary_flips_correct_pct": 0.313874786975337, + "val_binary_flips_total_pct": 0.5630193972120099, + "val_binary_flips_wrong_pct": 0.2491446102366728, + "val_biou": 0.48673819597450946, + "val_biou_gain": 0.07844860786555724, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8382267893986702, + "val_dice_gain": 0.03910640469239168, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7521581651406288, + "val_iou_gain": 0.047226955022260264, + "val_loss": -0.1682901309686713, + "val_refine_score": 0.6194481805575691, + "val_reward": 0.01682901309686713, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6195518961627513, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 15, + "encoder_lr": 1.1344319661637787e-06, + "epoch": 118, + "epoch_seconds": 12.343136664945632, + "grad_norm": 0.7215881239284169, + "lr": 1.1344319661637787e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6195518961627513, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.03771737154403871, + "mean_delta": -0.02646601752547378, + "near_zero_pct": 2.39785441119073e-05, + "negative_pct": 90.70813737132333, + "positive_pct": 9.291840869594704 + }, + "train_actor_loss": -0.02216621325417443, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.022166213338840116, + "train_ce_loss": 0.1236544671383771, + "train_critic_loss": 0.0, + "train_dice": 0.9290586316708701, + "train_dice_loss": 0.05519626357338645, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8778653142688384, + "train_loss": -0.21808511154218155, + "train_mask_delta_mean": 0.03770030628551136, + "train_mean_reward": 0.02216621325417443, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.4734848625957966, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.016851976979523897, + "val_binary_flips_correct_pct": 0.314031862745098, + "val_binary_flips_total_pct": 0.5653044756721048, + "val_binary_flips_wrong_pct": 0.25127261292700676, + "val_biou": 0.4863994354375018, + "val_biou_gain": 0.07810984732854959, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8385305853323937, + "val_dice_gain": 0.03941020062611511, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7527043568880007, + "val_iou_gain": 0.04777314676963218, + "val_loss": -0.16851976979523897, + "val_refine_score": 0.6195518961627513, + "val_reward": 0.016851976979523897, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6195388725908654, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 16, + "encoder_lr": 1.0336137508373906e-06, + "epoch": 119, + "epoch_seconds": 12.304920736700296, + "grad_norm": 0.7602376992052252, + "lr": 1.0336137508373906e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6195388725908654, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.037861114240844145, + "mean_delta": -0.026476248421452263, + "near_zero_pct": 1.198927205595365e-05, + "negative_pct": 90.64213877374476, + "positive_pct": 9.357851489701055 + }, + "train_actor_loss": -0.022413170257509177, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02241317038450771, + "train_ce_loss": 0.12090325423262337, + "train_critic_loss": 0.0, + "train_dice": 0.9334967789066603, + "train_dice_loss": 0.05344223434274847, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.8822930794880518, + "train_loss": -0.22064479101787915, + "train_mask_delta_mean": 0.037872314453125, + "train_mean_reward": 0.022413170257509177, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.1657197019085288, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01681605863268487, + "val_binary_flips_correct_pct": 0.3138560874789369, + "val_binary_flips_total_pct": 0.5649267458448224, + "val_binary_flips_wrong_pct": 0.25107065836588544, + "val_biou": 0.4864609878646645, + "val_biou_gain": 0.0781713997557123, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.838479611898679, + "val_dice_gain": 0.03935922719240048, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7526167573170662, + "val_iou_gain": 0.047685547198697664, + "val_loss": -0.16816058632684872, + "val_refine_score": 0.6195388725908654, + "val_reward": 0.01681605863268487, + "validated_this_epoch": true + }, + { + "alpha": null, + "early_stopping_active": true, + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_improved": false, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_monitor_value": 0.6195191799624437, + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "early_stopping_wait": 17, + "encoder_lr": 1e-06, + "epoch": 120, + "epoch_seconds": 12.358446802012622, + "grad_norm": 0.771189732985063, + "lr": 1e-06, + "selection_metric_name": "val_refine_score", + "selection_metric_value": 0.6195191799624437, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "train_action_distribution": { + "max_abs_delta": 0.10009765625, + "mean_abs_delta": 0.0378557424145666, + "mean_delta": -0.02660661379129372, + "near_zero_pct": 2.0229455799380958e-05, + "negative_pct": 90.72423272512175, + "positive_pct": 9.275749215686863 + }, + "train_actor_loss": -0.02247603365950371, + "train_advantage_mean": 0.0, + "train_advantage_std": 0.0, + "train_alpha": 0.0, + "train_annealed_aux_ce_weight": 0.040000000000000015, + "train_biou_delta_mean": 0.02247603344783949, + "train_ce_loss": 0.1248048875819553, + "train_critic_loss": 0.0, + "train_dice": 0.933376490396071, + "train_dice_loss": 0.05512202327901667, + "train_effective_steps": 8.0, + "train_entropy": 0.0, + "train_entropy_bonus_used": 0.0, + "train_entropy_loss": 0.0, + "train_iou": 0.881784960202426, + "train_loss": -0.2211617949334058, + "train_mask_delta_mean": 0.03785289417613636, + "train_mean_reward": 0.02247603365950371, + "train_mean_value_pred": 0.0, + "train_reinforce_loss": 0.0, + "train_reward_zeros_pct": 0.0, + "train_rl_loss_scale": 10.0, + "train_value_pred_error": 0.0, + "val_actor_loss": -0.01679371192585677, + "val_binary_flips_correct_pct": 0.3128425747740502, + "val_binary_flips_total_pct": 0.5611644071691176, + "val_binary_flips_wrong_pct": 0.2483218323950674, + "val_biou": 0.48668000479007595, + "val_biou_gain": 0.07839041668112373, + "val_ce_loss": 0.0, + "val_critic_loss": 0.0, + "val_decoder_biou": 0.4082895881089522, + "val_decoder_dice": 0.7991203847062786, + "val_decoder_iou": 0.7049312101183686, + "val_dice": 0.8383322325372636, + "val_dice_gain": 0.03921184783098508, + "val_dice_loss": 0.0, + "val_entropy": 0.0, + "val_iou": 0.7523583551348113, + "val_iou_gain": 0.04742714501644274, + "val_loss": -0.1679371192585677, + "val_refine_score": 0.6195191799624437, + "val_reward": 0.01679371192585677, + "validated_this_epoch": true + } +] \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/low_iou_samples.csv b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/low_iou_samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..6577ebad26366a2ca24898c7feba3f34b1affb55 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/low_iou_samples.csv @@ -0,0 +1,4 @@ +sample_id +BUSI_0157_M +BUSI_0243_B +BUSI_0201_B diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/run_config.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/run_config.json new file mode 100644 index 0000000000000000000000000000000000000000..e52be7fe8d2e2694ecf1b58f6b56462a40690d86 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/run_config.json @@ -0,0 +1,112 @@ +{ + "a3c_entropy_coeff": 0.0, + "aux_action_ce_mix": 0.8726103361457451, + "backbone_family": "smp", + "base_split_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/splits/phase_002.json", + "best_checkpoint_metric_name": "val_refine_score", + "best_checkpoint_metrics": { + "2": "val_iou", + "3": "val_refine_score" + }, + "biou_reward_weight": 1.0, + "boundary_reward_weight": 0.5, + "critic_loss_weight": 1.4015767132796022, + "data_root": "/workspace/BUSI_with_classes", + "dataset_name": "BUSI_with_classes", + "dataset_percent": 1.0, + "dataset_split_policy": "stratified", + "dataset_splits_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/splits/phase_002.json", + "decoder_lr": 0.0, + "dropout_p": 0.015714592843367126, + "early_stopping_min_delta": 0.0, + "early_stopping_mode": "auto", + "early_stopping_monitor": "val_refine_score", + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "elastic_aug_prob": 0.4303652916281717, + "encoder_lr": 0.0, + "entropy_alpha_init": 0.005, + "entropy_lr": 6.618595597183474e-05, + "entropy_target_ratio": 0.2, + "epoch_probe_mode": "rolling_random", + "evaluation_checkpoint_mode": "best", + "execution_mode": "train_eval", + "folds_experiment_name": "stratified_holdout_v1", + "gae_lambda": 0.8306320445782609, + "gamma": 0.95, + "grad_clip_norm": 6.0, + "head_lr": 0.0001971844222061614, + "iou_reward_weight": 1.0, + "keep_correct_reward_weight": 0.05, + "max_epochs": 120, + "min_alpha": 0.00017019223026554014, + "normalization_cache_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/norm_stats_BUSI_with_classes_stratified_80_10_10_100pct_phase002_repeat01.json", + "num_actions": 3, + "percent_sampling_mode": "incremental", + "phase_count": 10, + "phase_index": 2, + "phase_test_fold_index": 2, + "phase_val_fold_index": 3, + "project_dir": "/workspace", + "refine_delta_large": 0.08, + "refine_delta_small": 0.03, + "rl_lr": 0.0001971844222061614, + "run_name": "phase=002 | repeat=01 | strategy=3 | pct=100%", + "run_type": "final", + "save_history_incrementally": false, + "scheduler_factor": 0.5, + "scheduler_min_lr": 1e-05, + "scheduler_patience": 5, + "scheduler_threshold": 0.001, + "selected_split_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/subsets/phase_002_pct_100_repeat_01.json", + "smp_decoder_type": "UPerNet", + "smp_encoder_depth": 5, + "smp_encoder_name": "tu-pvt_v2_b2", + "smp_encoder_proj_dim": 192, + "smp_encoder_weights": "imagenet", + "split_generation_mode": "fixed_stratified_phases_8_1_1", + "split_repeat_index": 2, + "split_seed": 723450912, + "split_type": "80_10_10", + "strategy": 3, + "strategy2_checkpoint_mode": "best", + "strategy2_checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt", + "strategy3_advantage_normalize": false, + "strategy3_aux_boundary_dice_weight": 0.6979509040767587, + "strategy3_aux_ce_anneal_epochs": 15, + "strategy3_aux_ce_anneal_start_epoch": 25, + "strategy3_aux_ce_floor_fraction": 0.1, + "strategy3_aux_ce_weight": 0.4, + "strategy3_decoder_ce_weight": 0.0, + "strategy3_decoder_dice_weight": 0.0, + "strategy3_delta_max": 0.1, + "strategy3_exploration_eps": 0.1, + "strategy3_exploration_eps_epochs": 20, + "strategy3_freeze_bootstrapped_segmentation": true, + "strategy3_mc_disk_cache_enabled": true, + "strategy3_mc_disk_cache_read": true, + "strategy3_mc_disk_cache_write": true, + "strategy3_mc_dropout_enabled": true, + "strategy3_mc_dropout_p": 0.2, + "strategy3_mc_dropout_samples": 5, + "strategy3_r1_progress_weight": 1.0, + "strategy3_rl_grad_clip_norm": 0.25, + "strategy3_rl_loss_scale": 10.0, + "strategy3_sam_attention_grid": 64, + "strategy3_variant": "lite", + "subset_manifest_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/manifests/subsets/phase_002_pct_100_repeat_01.json", + "subset_repeat_index": 1, + "subset_sampling_source": "incremental_chain", + "subset_seed": 1072230984, + "threshold": 0.5922320465492188, + "tmax": 8, + "train_resume_mode": "off", + "train_resume_specific_checkpoint": "", + "train_subset_key": "100", + "train_subset_source": "incremental_chain", + "train_subset_variant": 1, + "vgg_feature_dilation": 1, + "vgg_feature_scales": 4, + "weight_decay": 2.7012557725439094e-06, + "write_epoch_diagnostic": false +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/summary.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/summary.json new file mode 100644 index 0000000000000000000000000000000000000000..164c24c60a856b936441360b8a8337aeaf12dcb2 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/summary.json @@ -0,0 +1,34 @@ +{ + "best_epoch": 103, + "best_model_metric": 0.6222497408569307, + "best_model_metric_name": "val_refine_score", + "best_val_biou": 0.489678026989837, + "best_val_biou_gain": 0.08138843888088476, + "best_val_dice": 0.8401049404669908, + "best_val_iou": 0.7548234998513369, + "best_val_iou_gain": 0.04989228973296833, + "device_used": "cuda", + "early_stopping_best_value": 0.6222497408569307, + "early_stopping_min_delta": 0.0, + "early_stopping_monitor_mode": "max", + "early_stopping_monitor_name": "val_refine_score", + "early_stopping_patience": 30, + "early_stopping_start_epoch": 30, + "elapsed_seconds": 1512.7809295654297, + "epochs_to_best_checkpoint": 103, + "final_epoch": 120, + "gpu_name": "NVIDIA A100 80GB PCIe", + "resumed": false, + "run_type": "final", + "seconds_per_epoch": 12.60650774637858, + "seconds_per_epoch_measured_mean": 12.508194618439301, + "seconds_per_epoch_measured_std": 1.8517254170402915, + "strategy": 3, + "strategy3_bootstrap_loaded": true, + "strategy3_decoder_state": "frozen", + "strategy3_encoder_state": "frozen", + "strategy3_freeze_active": true, + "strategy3_freeze_requested": true, + "strategy3_segmentation_head_state": "frozen", + "time_to_best_seconds": 1290.955915441271 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/timing.csv b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/timing.csv new file mode 100644 index 0000000000000000000000000000000000000000..0aa77e429c34573782381b9d5b638e99110bae1f --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_002/pct_100/repeat_01/strategy_3/final/timing.csv @@ -0,0 +1,2 @@ +scope,strategy,tmax,device,num_batches,num_samples,total_inference_ms,avg_batch_inference_ms,std_batch_inference_ms,avg_sample_inference_ms,std_sample_inference_ms,mean_per_image_inference_ms,std_per_image_inference_ms,mean_per_image_inference_seconds,std_per_image_inference_seconds +test_set_evaluation,3,8,cuda,2,65,637.888511,318.944256,133.836232,9.813669,0.639775,9.813669,0.639775,0.009813669,0.000639775 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt.meta.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt.meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f92c68ad883c9d257d8dbce8a83ef216e1a4e7cf --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt.meta.json @@ -0,0 +1,59 @@ +{ + "backbone_family": "smp", + "checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt", + "dataset_percent": 1.0, + "epoch": 90, + "last_restore": { + "expected_run_type": null, + "restored_at_epoch": 90, + "restored_keys": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + } + }, + "run_type": "final", + "saved_keys": [ + "best_metric_name", + "best_metric_value", + "config", + "elapsed_seconds", + "epoch", + "epoch_metrics", + "history", + "model_state_dict", + "optimizer_state_dict", + "patience_counter", + "run_config", + "run_type", + "scheduler_state_dict" + ], + "state_presence": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + }, + "strategy": 2 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/latest.pt.meta.json b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/latest.pt.meta.json new file mode 100644 index 0000000000000000000000000000000000000000..7d074b0a63680757503671c17e6adaca4f627410 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/latest.pt.meta.json @@ -0,0 +1,39 @@ +{ + "backbone_family": "smp", + "checkpoint_path": "/workspace/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_003/pct_100/repeat_01/strategy_2/final/checkpoints/latest.pt", + "dataset_percent": 1.0, + "epoch": 100, + "run_type": "final", + "saved_keys": [ + "best_metric_name", + "best_metric_value", + "config", + "elapsed_seconds", + "epoch", + "epoch_metrics", + "history", + "model_state_dict", + "optimizer_state_dict", + "patience_counter", + "run_config", + "run_type", + "scheduler_state_dict" + ], + "state_presence": { + "alpha_optimizer_state_dict": false, + "best_metric_name": true, + "best_metric_value": true, + "elapsed_seconds": true, + "epoch_metrics": true, + "history": true, + "log_alpha": false, + "model_state_dict": true, + "optimizer_state_dict": true, + "patience_counter": true, + "resume_source": false, + "run_config": true, + "scaler_state_dict": false, + "scheduler_state_dict": true + }, + "strategy": 2 +} \ No newline at end of file diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions/BUSI_0088_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions/BUSI_0088_M.png new file mode 100644 index 0000000000000000000000000000000000000000..62b2f9672754459e5b1bd1e2d12dafff7d622cfa --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions/BUSI_0088_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c2a946a616f3e567c33cfa8b821e288b1c7736f65297054e13024133cb7865a +size 258 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0002_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0002_M.png new file mode 100644 index 0000000000000000000000000000000000000000..1b0d21b98f2ca2f33df463e1e1cefd24515b0bcd --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0002_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b019af332e15ec0be7caeebc77132b575bb8186f03b4d35818b041c25871f8d8 +size 489 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0005_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0005_B.png new file mode 100644 index 0000000000000000000000000000000000000000..aeb641656be975b8fc37aa8ed92c3fe6d8fce823 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0005_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2bd5f0b63646835fc8716601587aa8ff10aa89b41355a166d9f4807740f11d16 +size 163 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_B.png new file mode 100644 index 0000000000000000000000000000000000000000..fea7856fef2e6f004138899d1dfdc986972cfab9 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebd732dfb4b848b4970173065bea4849f7c049826e36cdf078216200a16a8f0a +size 479 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_M.png new file mode 100644 index 0000000000000000000000000000000000000000..ec5b85958cc16705422674a9c9629b9252e83763 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0018_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0472bcb2c204f32e298b40d78cdf8b5f368d58698d5f9e22b02a4cd41f23f4e +size 186 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0020_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0020_B.png new file mode 100644 index 0000000000000000000000000000000000000000..8274af42662c952d26f15d3a19345cd9dc73703e --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0020_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed3d35e98a9a787ec848158aa2ca8d2323470eec5a04fe284331d84ab93832cc +size 240 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0023_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0023_B.png new file mode 100644 index 0000000000000000000000000000000000000000..8b06be035f0381e8577da25c5b8cc402a7d19833 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0023_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4906941c8acd4b5aaad3356abe0f36e199ba4fa07d1c82ef3478abb253e256a5 +size 247 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0067_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0067_B.png new file mode 100644 index 0000000000000000000000000000000000000000..5d8c1e6f0eb0a1853eda0c1908db1f27647ec7f9 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0067_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7faf948ec24a4c82e86498b81259db6a91c0ca5b96f075e25f0dacd7585e758 +size 343 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0068_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0068_B.png new file mode 100644 index 0000000000000000000000000000000000000000..0e9a54d9e48bcafd3c9b4bcb32816cea8a890cff --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0068_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:057018713a186e4d579c5682c60e6e41eb94e53a5da0984ec3b20d0cb16a3516 +size 402 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0072_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0072_M.png new file mode 100644 index 0000000000000000000000000000000000000000..403433f64c92cee0841098cd76292463ed62ca8b --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0072_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ea65ec36286519828f8c3dfbf250f4b7a18beb66b38dece48b9766bc1557dc8 +size 462 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0087_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0087_B.png new file mode 100644 index 0000000000000000000000000000000000000000..4595d577627fdf010322bb7fe654b1d864a38483 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0087_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6a5d58b2c54143877c11ee9f89317074ee089a7fabe7a9cca10de80e47f1c2c +size 187 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0088_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0088_M.png new file mode 100644 index 0000000000000000000000000000000000000000..eb4201701ce7e53efb7e4d52c6914172d4e19a10 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0088_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92954ff1098637ba0875b7f45c87586076fee591a974e84daf12d3fc7cec358f +size 263 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0091_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0091_B.png new file mode 100644 index 0000000000000000000000000000000000000000..cf9df2f4b38c8a526d5fcab7420b5c90ce24b04f --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0091_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0c4ea35b616aaed59005d8a239addc55a61541bee025c4202e8c68df9db0925 +size 164 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0097_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0097_B.png new file mode 100644 index 0000000000000000000000000000000000000000..d60a050321c2c3fdb61c84e5b349b686540d8276 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0097_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f8202ba0bee7327671b583935e58a41821c82acea907a9de3894464ed1c3da1 +size 387 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0102_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0102_M.png new file mode 100644 index 0000000000000000000000000000000000000000..aad5f74ceadca1f3ad2b85da138a7545ecfdad28 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0102_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902d655c3f3c116226a022454942507d9352b0ffeb058dc9863bf866496521b3 +size 336 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0114_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0114_M.png new file mode 100644 index 0000000000000000000000000000000000000000..d4c7db2206b63d88ee1914099adc47b98e8ccfce --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0114_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96d4103323fcf886d97b6922099ec622ce6bef352c9363db59565247149719cd +size 437 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0119_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0119_M.png new file mode 100644 index 0000000000000000000000000000000000000000..2d342852f080aaf36f53b0878e7e20b0400674e1 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0119_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21aa6e22429e3d4960ef7cbf00f7ac0a990d24f60cd1d4855bd891f09cfebc24 +size 360 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0158_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0158_B.png new file mode 100644 index 0000000000000000000000000000000000000000..7b01de85b05dfd02f2cb139d6efd5c2e35e1f16a --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0158_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:918e33fa234e0e305bb3b98474e7b6417db1ec43d286562d1e5b771877e1bd9c +size 317 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0167_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0167_M.png new file mode 100644 index 0000000000000000000000000000000000000000..d2f242792f88b6794f9dd44bf942d36ff8e9faa4 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0167_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4fe1821f1fedd6cfb5f117b46f62e3c3f2760f72eeb81af7b6bc13fa74cf781 +size 378 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0173_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0173_B.png new file mode 100644 index 0000000000000000000000000000000000000000..81542900ae296e0709d5b8d5383e099160397323 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0173_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80e2a174863011c54610a732a966de3d4530274eb6d3b64fe3a9e81b6441f4cf +size 259 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0176_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0176_B.png new file mode 100644 index 0000000000000000000000000000000000000000..529057a87716eca56140cac9bb690670559ed361 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0176_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:137f333f1826953385258548919f9d2c89bf638e1476c34fccf712d111460a64 +size 194 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0179_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0179_B.png new file mode 100644 index 0000000000000000000000000000000000000000..ef6403dd81bb8461cb8f9788cca55c47beb97b55 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0179_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4cea71e664b07eb0ba054f6a343d9c43a3d41c7249eb78827a104d8d782c2bb5 +size 166 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0184_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0184_M.png new file mode 100644 index 0000000000000000000000000000000000000000..3f807a014a632c6ae3e25f94e8b57248aa37cca1 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0184_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a07c40a3d1b350fa9e47dbe221bc354205bd3c863c1e7fd66a15b17c772b6fb +size 500 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0199_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0199_M.png new file mode 100644 index 0000000000000000000000000000000000000000..53612c444b4013d9b5033244e4eb32ecf0c54f5d --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0199_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1eb80355bf079f077ee37753e3ee6b2c69bc05fbe34d0c4115cb5db9b02e1ba1 +size 430 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0200_M.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0200_M.png new file mode 100644 index 0000000000000000000000000000000000000000..ebee04e53fdfe6fadcf9c8dab68d9e4063858ba9 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0200_M.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25d11c0ec2d812537b4f3c92ba6612c0cfd3bdf8c82c71ac3ef43049bb3dcc86 +size 238 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0233_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0233_B.png new file mode 100644 index 0000000000000000000000000000000000000000..b4b3a5649fde47fd0c5d422fd0f10c32379d1ba7 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0233_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efd6906e967ce4b1145dc9a95afe76b9d2c007a771d6b85f6546aa77226863dc +size 296 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0261_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0261_B.png new file mode 100644 index 0000000000000000000000000000000000000000..6a27b3a550a8f1e596eb5e29c966965f990647d3 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0261_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:313eb30c12d0179f365c9752da9cfb25bde2817d3c9f5ca067978628bdabacc6 +size 310 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0289_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0289_B.png new file mode 100644 index 0000000000000000000000000000000000000000..c143101e9b73ca65b387035c652c79ce1334b305 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0289_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06d2e890e6ea7ab4ade1f31640f367fd394d5d63f548215739a9384a0b315c10 +size 276 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0302_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0302_B.png new file mode 100644 index 0000000000000000000000000000000000000000..ba2d369b235bfcd2029c3ab6d1ebd1bad08942a1 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0302_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca6f72688a6ddc827e6e7d8ac6ff13b967e8dc552414b841dcc94ae6dfff3c00 +size 260 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0306_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0306_B.png new file mode 100644 index 0000000000000000000000000000000000000000..205effe5462b1fdfb9385598d29f378e130f4408 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0306_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fade216040d1dfe719343d8e2c84e464c48975e6517e32477dee86d80fe65a0 +size 328 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0348_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0348_B.png new file mode 100644 index 0000000000000000000000000000000000000000..02fc45870303d3987e22936a4c9fee2395895c0a --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0348_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fe13cc31fd4858c28e0bd8b3bdad8097839622f43f60e63e17bd093c817516c +size 184 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0370_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0370_B.png new file mode 100644 index 0000000000000000000000000000000000000000..3f56763dca5371dc6751db8217eba38501603744 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0370_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:269238fe82f7ef5b1f9b662d715251292b863b68c0536cc9183aea00a4be4213 +size 366 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0373_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0373_B.png new file mode 100644 index 0000000000000000000000000000000000000000..5bcce38a665c37d405442f1e9a0a075077efba07 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0373_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25e009c7a3f6d1aaa02d71c0311896e1d1cac55641bab00161b86ef55f864c71 +size 227 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0392_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0392_B.png new file mode 100644 index 0000000000000000000000000000000000000000..eec953339bcee9f3ce79fd545d1fe4b9dbb4009d --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0392_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72b0b988dad2466b49f9a59ff23676bf45f9eeee8d8ed6337586748be019dce3 +size 396 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0407_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0407_B.png new file mode 100644 index 0000000000000000000000000000000000000000..a478e12e4420fd9bbf613dbbb302183fe74242ad --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0407_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5bf681dbe520cae6c6e48193bae6221e0d30f97d43edef8906524d03ddf8f5d +size 415 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0421_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0421_B.png new file mode 100644 index 0000000000000000000000000000000000000000..2eec071a11b03c6f2087ec81d295afd80a3c41a7 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0421_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2019e4bc9ac6a736df0a6878e8f0510443cbad7dbc01990e3d4ac891e6bc925f +size 295 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0434_B.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0434_B.png new file mode 100644 index 0000000000000000000000000000000000000000..5998eb036fd7b4309ba64e1e83ce60a40ef893d3 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/final/predictions_255/BUSI_0434_B.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a77a7d881b53d607029d4e43451c385bc42c04ca2ed5b806df2759c5386ad483 +size 346 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_panel.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_panel.png new file mode 100644 index 0000000000000000000000000000000000000000..b292bdd62a5e920e13a0171ad68a1c17fbdc88a5 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_panel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b7a2dad3bcd4724225de34a1e6c50f5a85e3d61492e34239f42ba52cda1f4b6 +size 60138 diff --git a/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_prediction.png b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_prediction.png new file mode 100644 index 0000000000000000000000000000000000000000..74114cbb359d2135f7f1101b2867d850044bd906 --- /dev/null +++ b/runs/UPerNet_PVTv2_b2/repeated_holdout/stratified_holdout_v1/phase_010/pct_100/repeat_01/strategy_3/smoke_test/smoke_prediction.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c551564ef73a8e9d319ea19830fbbdc389d0df1a37c872e8b3ceceb6feccef3 +size 206 diff --git a/runs/_plots/UPerNet_PVTv2_b2__s2_vs_s3.png b/runs/_plots/UPerNet_PVTv2_b2__s2_vs_s3.png new file mode 100644 index 0000000000000000000000000000000000000000..e0570c6563d96e957555a2446b54238ac8f6cc9f --- /dev/null +++ b/runs/_plots/UPerNet_PVTv2_b2__s2_vs_s3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:507aff1fb39ca964af3fdc0d3811789b047a4bcdbb98f145d9df41cedcb86451 +size 184638 diff --git a/runs/_stats/UPerNet_PVTv2_b2__s2_vs_s3_stats.xlsx b/runs/_stats/UPerNet_PVTv2_b2__s2_vs_s3_stats.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f77113e58e188920630bea48f019ade39e1be2b8 --- /dev/null +++ b/runs/_stats/UPerNet_PVTv2_b2__s2_vs_s3_stats.xlsx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ccc03dc8a2de6567ddb1bddfef2751c69e72e0e63d8c28ac89a17ad3528fcae +size 103034