Image-to-Image
Diffusers
Safetensors
English
agriculture
world-model
plant-growth
developmental-reasoning
image-editing
rice
maize
research
Instructions to use ecnu-icalk/ArgoWM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use ecnu-icalk/ArgoWM with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline from diffusers.utils import load_image # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("ecnu-icalk/ArgoWM", dtype=torch.bfloat16, device_map="cuda") prompt = "Turn this cat into a dog" input_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png") image = pipe(image=input_image, prompt=prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse files- .gitattributes +16 -37
- .gitignore +67 -0
- LICENSE +202 -0
- LICENSES.md +36 -0
- NOTICE +17 -0
- README.md +123 -0
- README.zh-CN.md +3 -0
- README_zh-CN.md +100 -0
- THIRD_PARTY.md +29 -0
- checkpoints/README.md +9 -0
- checkpoints/maize/phenoclock/adapter_model.safetensors +3 -0
- checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors +3 -0
- checkpoints/rice/phenoclock/adapter_model.safetensors +3 -0
- checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors +3 -0
- licenses/Qwen3.8-27B-LICENSE.txt +202 -0
- pyproject.toml +20 -0
- src/wgsr_v9/cot_evaluation/__init__.py +4 -0
- src/wgsr_v9/cot_evaluation/metrics.py +84 -0
- src/wgsr_v9/cot_evaluation/parser.py +154 -0
- src/wgsr_v9/cot_evaluation/reference.py +212 -0
- src/wgsr_v9/cot_evaluation/report.py +192 -0
- src/wgsr_v9/cot_evaluation/semantic.py +97 -0
- src/wgsr_v9/cot_evaluation/uncertainty.py +94 -0
- src/wgsr_v9/diffsynth_batching.py +212 -0
- src/wgsr_v9/executor_cache_builder.py +316 -0
- src/wgsr_v9/executor_cache_compactor.py +184 -0
- src/wgsr_v9/executor_inference/__init__.py +47 -0
- src/wgsr_v9/executor_inference/checkpoint.py +99 -0
- src/wgsr_v9/executor_inference/cli.py +98 -0
- src/wgsr_v9/executor_inference/config.py +80 -0
- src/wgsr_v9/executor_inference/constants.py +10 -0
- src/wgsr_v9/executor_inference/manifest.py +171 -0
- src/wgsr_v9/executor_inference/runner.py +571 -0
- src/wgsr_v9/maize/__init__.py +37 -0
- src/wgsr_v9/maize/contract.py +232 -0
- src/wgsr_v9/maize/cot.py +605 -0
- src/wgsr_v9/maize/experiment.py +103 -0
- src/wgsr_v9/maize/geometry.py +54 -0
- src/wgsr_v9/maize/grouped_loss.py +50 -0
- src/wgsr_v9/maize/naming.py +57 -0
- src/wgsr_v9/maize/planner_export.py +66 -0
- src/wgsr_v9/maize/training.py +178 -0
.gitattributes
CHANGED
|
@@ -1,38 +1,17 @@
|
|
| 1 |
-
*
|
| 2 |
-
*.
|
| 3 |
-
*.
|
| 4 |
-
*.
|
| 5 |
-
*.
|
| 6 |
-
*.
|
| 7 |
-
*.
|
| 8 |
-
*.
|
| 9 |
-
*.
|
| 10 |
-
*.
|
| 11 |
-
*.
|
| 12 |
-
*.
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
*
|
| 29 |
-
*
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
assets/method-overview.pdf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
-
assets/method-overview.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
-
assets/growth-script-templates.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
* text=auto
|
| 2 |
+
*.md text eol=lf
|
| 3 |
+
*.py text eol=lf
|
| 4 |
+
*.json text eol=lf
|
| 5 |
+
*.yaml text eol=lf
|
| 6 |
+
*.yml text eol=lf
|
| 7 |
+
*.txt text eol=lf
|
| 8 |
+
*.svg text eol=lf
|
| 9 |
+
*.png binary
|
| 10 |
+
*.jpg binary
|
| 11 |
+
*.jpeg binary
|
| 12 |
+
*.pdf binary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
|
| 15 |
+
# Preserve frozen protocol and upstream license bytes across Git checkouts.
|
| 16 |
+
protocols/** -text
|
| 17 |
+
licenses/** -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*.egg-info/
|
| 4 |
+
.pytest_cache/
|
| 5 |
+
.ruff_cache/
|
| 6 |
+
.venv*/
|
| 7 |
+
.env
|
| 8 |
+
.env.*
|
| 9 |
+
!.env.example
|
| 10 |
+
.DS_Store
|
| 11 |
+
/build/
|
| 12 |
+
/dist/
|
| 13 |
+
/data/
|
| 14 |
+
/runs/
|
| 15 |
+
/models/
|
| 16 |
+
/checkpoints/
|
| 17 |
+
/third_party/
|
| 18 |
+
/configs/local*/
|
| 19 |
+
/configs/local.json
|
| 20 |
+
/configs/local.*.json
|
| 21 |
+
!/configs/local.example.json
|
| 22 |
+
*.safetensors
|
| 23 |
+
*.ckpt
|
| 24 |
+
*.pth
|
| 25 |
+
*.pt
|
| 26 |
+
*.pem
|
| 27 |
+
*.key
|
| 28 |
+
*.log
|
| 29 |
+
|
| 30 |
+
# Local service credentials and private-key containers
|
| 31 |
+
AGENTS.md
|
| 32 |
+
auth.json
|
| 33 |
+
auth.local.json
|
| 34 |
+
credentials.json
|
| 35 |
+
credentials.local.json
|
| 36 |
+
secrets.json
|
| 37 |
+
secrets.yaml
|
| 38 |
+
secrets.yml
|
| 39 |
+
.netrc
|
| 40 |
+
.pypirc
|
| 41 |
+
*.p12
|
| 42 |
+
*.pfx
|
| 43 |
+
|
| 44 |
+
# Local Hub upload cache and development metadata
|
| 45 |
+
.cache/huggingface/
|
| 46 |
+
*.sublime-workspace
|
| 47 |
+
|
| 48 |
+
# Published AgroWM components; all other training weights remain ignored.
|
| 49 |
+
!/checkpoints/
|
| 50 |
+
/checkpoints/*
|
| 51 |
+
!/checkpoints/README.md
|
| 52 |
+
!/checkpoints/manifest.json
|
| 53 |
+
!/checkpoints/SHA256SUMS
|
| 54 |
+
!/checkpoints/rice/
|
| 55 |
+
!/checkpoints/maize/
|
| 56 |
+
/checkpoints/rice/*
|
| 57 |
+
/checkpoints/maize/*
|
| 58 |
+
!/checkpoints/rice/phenoclock/
|
| 59 |
+
!/checkpoints/rice/rooted_renderer/
|
| 60 |
+
!/checkpoints/maize/phenoclock/
|
| 61 |
+
!/checkpoints/maize/rooted_renderer/
|
| 62 |
+
!/checkpoints/rice/phenoclock/adapter_model.safetensors
|
| 63 |
+
!/checkpoints/maize/phenoclock/adapter_model.safetensors
|
| 64 |
+
!/checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors
|
| 65 |
+
!/checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors
|
| 66 |
+
|
| 67 |
+
RELEASE_MANIFEST.json
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
LICENSES.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# License scope
|
| 2 |
+
|
| 3 |
+
**Built with Qwen.** The paired AgroWM code and model releases have
|
| 4 |
+
component-specific license terms. The Apache-2.0 license for AgroWM's original code does not remove the
|
| 5 |
+
restrictions on the Rooted Renderer weights inherited from Qwen Image 2.1.
|
| 6 |
+
|
| 7 |
+
| Component | Applicable terms |
|
| 8 |
+
|---|---|
|
| 9 |
+
| Original AgroWM code and documentation | [Apache License 2.0](LICENSE) |
|
| 10 |
+
| Rice and maize PhenoClock LoRA adapters | Apache-2.0; the [Qwen3.8-27B upstream license](licenses/Qwen3.8-27B-LICENSE.txt) is retained |
|
| 11 |
+
| Rice and maize Rooted Renderer weights and their base architecture | [Qwen Research License Agreement](licenses/Qwen-Image-2.1-LICENSE.txt), including its non-commercial research/evaluation restriction |
|
| 12 |
+
| Other dependencies and data | Their respective upstream licenses; see [THIRD_PARTY.md](THIRD_PARTY.md) |
|
| 13 |
+
|
| 14 |
+
The Rooted Renderers are full fine-tuned derivatives of Qwen Image 2.1. Their
|
| 15 |
+
upstream license permits redistribution subject to its conditions; commercial use
|
| 16 |
+
requires a separate license from the upstream licensor. They must not be treated
|
| 17 |
+
as unrestricted Apache-2.0 model weights.
|
| 18 |
+
|
| 19 |
+
The model-card metadata therefore uses a custom combined license entry pointing
|
| 20 |
+
to this file. It does not offer a choice of license for the Renderer.
|
| 21 |
+
|
| 22 |
+
## Attribution and modifications
|
| 23 |
+
|
| 24 |
+
- PhenoClock: Qwen3.8-27B, Copyright 2026 Alibaba Cloud. AgroWM contributes
|
| 25 |
+
crop-specific LoRA adapters trained to predict structured Growth Scripts.
|
| 26 |
+
- Rooted Renderer: Qwen Image 2.1, Copyright (c) 2026 Hangzhou Tongyi Laboratory
|
| 27 |
+
Technology Co., Ltd. AgroWM fine-tunes the diffusion transformer on source
|
| 28 |
+
images and teacher Growth Scripts. Text-encoder and VAE weights are not included.
|
| 29 |
+
- The two Renderer files named `diffusion_pytorch_model.safetensors` contain these
|
| 30 |
+
fine-tuning modifications. They are not the original base-model parameters.
|
| 31 |
+
- In the adapter configurations, the original private machine path is replaced
|
| 32 |
+
by the public base-model identifier. No weight tensor is altered for packaging.
|
| 33 |
+
|
| 34 |
+
Required upstream notices are retained in [NOTICE](NOTICE), with copies alongside
|
| 35 |
+
the component files in the model repository. Upstream license texts are included unmodified under
|
| 36 |
+
`licenses/`.
|
NOTICE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
AgroWM
|
| 2 |
+
Built with Qwen.
|
| 3 |
+
|
| 4 |
+
PhenoClock is based on Qwen3.8-27B.
|
| 5 |
+
Copyright 2026 Alibaba Cloud.
|
| 6 |
+
Upstream terms: licenses/Qwen3.8-27B-LICENSE.txt (Apache License 2.0).
|
| 7 |
+
The released adapter_model.safetensors files are crop-specific LoRA adapters
|
| 8 |
+
trained by the AgroWM project. Adapter configuration base paths have been changed
|
| 9 |
+
to the public model identifier for portability.
|
| 10 |
+
|
| 11 |
+
Rooted Renderer is based on Qwen Image 2.1.
|
| 12 |
+
Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved.
|
| 13 |
+
Upstream terms: licenses/Qwen-Image-2.1-LICENSE.txt.
|
| 14 |
+
The released diffusion_pytorch_model.safetensors files were modified by the
|
| 15 |
+
AgroWM project through crop-specific full diffusion-transformer fine-tuning on
|
| 16 |
+
plant growth pairs and Growth Scripts. They are not unmodified Qwen weights.
|
| 17 |
+
They remain subject to the Qwen Research License's non-commercial restrictions.
|
README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: agrowm-apache-2.0-and-qwen-research
|
| 4 |
+
license_link: https://huggingface.co/ecnu-icalk/ArgoWM/blob/main/LICENSES.md
|
| 5 |
+
language:
|
| 6 |
+
- en
|
| 7 |
+
pipeline_tag: image-to-image
|
| 8 |
+
base_model:
|
| 9 |
+
- Qwen/Qwen3.8-27B
|
| 10 |
+
- Qwen/Qwen-Image-2.1
|
| 11 |
+
base_model_relation: finetune
|
| 12 |
+
tags:
|
| 13 |
+
- agriculture
|
| 14 |
+
- world-model
|
| 15 |
+
- plant-growth
|
| 16 |
+
- developmental-reasoning
|
| 17 |
+
- image-editing
|
| 18 |
+
- rice
|
| 19 |
+
- maize
|
| 20 |
+
- research
|
| 21 |
+
inference: false
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
<div align="center">
|
| 25 |
+
|
| 26 |
+
# AgroWM
|
| 27 |
+
|
| 28 |
+
**Can World Models Predict Rice Growth? Toward Agricultural World Models**
|
| 29 |
+
|
| 30 |
+
[](https://arxiv.org/abs/2611.26145)
|
| 31 |
+
[](https://github.com/ECNU-ICALK/ArgoWM)
|
| 32 |
+
[](https://huggingface.co/ecnu-icalk/ArgoWM)
|
| 33 |
+
|
| 34 |
+
**English** · [简体中文](README_zh-CN.md)
|
| 35 |
+
|
| 36 |
+
Built with Qwen
|
| 37 |
+
|
| 38 |
+
</div>
|
| 39 |
+
|
| 40 |
+
**AgroWM** predicts how the same plant will look days to months into the future from a single photograph. It first reasons about the plant's development, then generates its future appearance. We study this task on rice and maize.
|
| 41 |
+
|
| 42 |
+
> **Reason about development. Then render growth.**
|
| 43 |
+
|
| 44 |
+
## How it works
|
| 45 |
+
|
| 46 |
+
[](assets/method-overview.pdf)
|
| 47 |
+
|
| 48 |
+
*Figure 3 from the paper. Click the figure for the vector PDF.*
|
| 49 |
+
|
| 50 |
+
- **PhenoClock** infers the current growth stage, predicts the future stage, and writes a **Growth Script** with targets for plant height, area, color, and organs.
|
| 51 |
+
- **Rooted Renderer** follows the script to edit the source photograph while preserving the plant's identity and viewpoint.
|
| 52 |
+
|
| 53 |
+
PhenoClock is built on **Qwen3.8-27B**; the Rooted Renderer is built on **Qwen Image 2.1**. See the [Growth Script examples](examples/README.md) for the intermediate format.
|
| 54 |
+
|
| 55 |
+
## Main results
|
| 56 |
+
|
| 57 |
+
Results reported in the paper, compared with the same image backbone fine-tuned without Growth Scripts (Simple FT):
|
| 58 |
+
|
| 59 |
+
| Crop | Method | DINO ↑ | Area error ↓ | Height error ↓ | Stage R@1 (%) ↑ |
|
| 60 |
+
|---|---|---:|---:|---:|---:|
|
| 61 |
+
| Rice | Simple FT | 0.834 | 3.73 | 7.83 | 47.4 |
|
| 62 |
+
| Rice | **AgroWM** | **0.860** | **3.51** | **7.43** | **54.6** |
|
| 63 |
+
| Maize | Simple FT | 0.764 | 1.97 | 11.12 | 30.1 |
|
| 64 |
+
| Maize | **AgroWM** | **0.795** | **1.73** | **10.61** | **30.9** |
|
| 65 |
+
|
| 66 |
+
At **9–20 weeks** on rice, AgroWM reaches **46.4% Stage R@1**, compared with **35.7%** for Simple FT. Rice and maize models are trained independently.
|
| 67 |
+
|
| 68 |
+
Area and Height are image-proxy errors in percentage points. Stage R@1 measures whether a forecast retrieves the target stage from the same plant's observed image sequence. See [full results and evaluation details](docs/RESULTS.md).
|
| 69 |
+
|
| 70 |
+
## Quick start
|
| 71 |
+
|
| 72 |
+
This model repository contains the final rice and maize PhenoClock adapters and Rooted Renderer weights, together with the matching [GitHub code](https://github.com/ECNU-ICALK/ArgoWM).
|
| 73 |
+
|
| 74 |
+
Clone the code, then download the model files once they are available on Hugging Face:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
git clone https://github.com/ECNU-ICALK/ArgoWM.git
|
| 78 |
+
cd ArgoWM
|
| 79 |
+
|
| 80 |
+
python -m pip install -U huggingface_hub
|
| 81 |
+
hf download ecnu-icalk/ArgoWM --include 'checkpoints/**' --local-dir .
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
If you already have the full Hugging Face repository, use that directory directly. The four released parameter files total about **30 GB**.
|
| 85 |
+
|
| 86 |
+
For inference, use **Linux, Python 3.12 and NVIDIA GPUs**:
|
| 87 |
+
|
| 88 |
+
1. [Install the environments](docs/INSTALL.md) and obtain the two required base models.
|
| 89 |
+
2. [Prepare your data](docs/DATA.md). The current workflow reads prepared image-pair manifests.
|
| 90 |
+
3. [Configure and run AgroWM](docs/CHECKPOINTS.md#run-the-existing-benchmark-workflow) with the released weights.
|
| 91 |
+
|
| 92 |
+
To reproduce training or evaluate predictions, follow the [training and evaluation guide](docs/RUNNING.md). Checkpoints include **AgroWM only**; base models, datasets, and baseline weights are obtained separately.
|
| 93 |
+
|
| 94 |
+
## Documentation
|
| 95 |
+
|
| 96 |
+
| Guide | Contents |
|
| 97 |
+
|---|---|
|
| 98 |
+
| [Models and inference](docs/CHECKPOINTS.md) | Components, loading, inference commands, and intended use |
|
| 99 |
+
| [Training and evaluation](docs/RUNNING.md) | Rice and maize experiment workflows |
|
| 100 |
+
| [Prompts](protocols/README.md) · [Growth Scripts](examples/README.md) | Prompt templates and script formats |
|
| 101 |
+
| [Experimental settings](docs/PROTOCOL.md) | Training configuration and metric definitions |
|
| 102 |
+
| [Code and model releases](docs/REPOSITORIES.md) | Matching versions, downloads, and checksums |
|
| 103 |
+
|
| 104 |
+
The experiments use white-background rice and maize images. Field scenes and other crops require further validation. Questions and bug reports are welcome through [GitHub Issues](https://github.com/ECNU-ICALK/ArgoWM/issues).
|
| 105 |
+
|
| 106 |
+
## Citation
|
| 107 |
+
|
| 108 |
+
If you use AgroWM in your research, please cite our [paper](https://arxiv.org/abs/2611.26145):
|
| 109 |
+
|
| 110 |
+
```bibtex
|
| 111 |
+
@misc{ji2026agrowm,
|
| 112 |
+
title = {Can World Models Predict Rice Growth? Toward Agricultural World Models},
|
| 113 |
+
author = {Wenkai Ji and Zeteng Li and Yinkun Guo and Jie Zhou and Liang He and Zhenong Jin},
|
| 114 |
+
year = {2026},
|
| 115 |
+
eprint = {2611.26145},
|
| 116 |
+
archivePrefix = {arXiv},
|
| 117 |
+
url = {https://arxiv.org/abs/2611.26145}
|
| 118 |
+
}
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
## License
|
| 122 |
+
|
| 123 |
+
Code, documentation, and PhenoClock adapters use **[Apache-2.0](LICENSE)**. Rooted Renderer weights follow the **[Qwen Research License](LICENSES.md)** for non-commercial research and evaluation. See [LICENSES.md](LICENSES.md) for component-specific terms and [NOTICE](NOTICE) for attribution.
|
README.zh-CN.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AgroWM 中文说明
|
| 2 |
+
|
| 3 |
+
中文文档位于 [README_zh-CN.md](README_zh-CN.md)。
|
README_zh-CN.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
# AgroWM
|
| 4 |
+
|
| 5 |
+
**Can World Models Predict Rice Growth? Toward Agricultural World Models**
|
| 6 |
+
|
| 7 |
+
[](https://arxiv.org/abs/2611.26145)
|
| 8 |
+
[](https://github.com/ECNU-ICALK/ArgoWM)
|
| 9 |
+
[](https://huggingface.co/ecnu-icalk/ArgoWM)
|
| 10 |
+
|
| 11 |
+
[English](README.md) · **简体中文**
|
| 12 |
+
|
| 13 |
+
Built with Qwen
|
| 14 |
+
|
| 15 |
+
</div>
|
| 16 |
+
|
| 17 |
+
**AgroWM** 从一张植物照片出发,预测同一株植物在数天至数月后的外观。它先推理植物的发育过程,再生成未来图像。我们在水稻和玉米上验证了这一方法。
|
| 18 |
+
|
| 19 |
+
> **先推理发育过程,再生成未来生长图像。**
|
| 20 |
+
|
| 21 |
+
## 方法
|
| 22 |
+
|
| 23 |
+
[](assets/method-overview.pdf)
|
| 24 |
+
|
| 25 |
+
*论文中的 Figure 3 原图,点击可查看矢量 PDF。*
|
| 26 |
+
|
| 27 |
+
- **PhenoClock** 推断当前生长阶段、预测未来阶段,并生成包含株高、面积、颜色和器官变化目标的 **Growth Script**。
|
| 28 |
+
- **Rooted Renderer** 按照脚本编辑源照片,在保留植株身份和视角的基础上生成未来外观。
|
| 29 |
+
|
| 30 |
+
PhenoClock 基于 **Qwen3.8-27B**,Rooted Renderer 基于 **Qwen Image 2.1**。中间脚本的具体格式见 [Growth Script 示例](examples/README.md)。
|
| 31 |
+
|
| 32 |
+
## 主要结果
|
| 33 |
+
|
| 34 |
+
以下为论文报告结果。Simple FT 使用同一图像基座进行微调,不使用 Growth Script。
|
| 35 |
+
|
| 36 |
+
| 作物 | 方法 | DINO ↑ | 面积误差 ↓ | 高度误差 ↓ | Stage R@1 (%) ↑ |
|
| 37 |
+
|---|---|---:|---:|---:|---:|
|
| 38 |
+
| 水稻 | Simple FT | 0.834 | 3.73 | 7.83 | 47.4 |
|
| 39 |
+
| 水稻 | **AgroWM** | **0.860** | **3.51** | **7.43** | **54.6** |
|
| 40 |
+
| 玉米 | Simple FT | 0.764 | 1.97 | 11.12 | 30.1 |
|
| 41 |
+
| 玉米 | **AgroWM** | **0.795** | **1.73** | **10.61** | **30.9** |
|
| 42 |
+
|
| 43 |
+
在水稻 **9–20 周**预测中,AgroWM 的 Stage R@1 为 **46.4%**,Simple FT 为 **35.7%**。水稻和玉米模型分别独立训练。
|
| 44 |
+
|
| 45 |
+
面积与高度为图像代理量误差,单位为百分点。Stage R@1 衡量预测图像是否能从同一株植物的真实图像序列中检索到目标阶段。[完整结果与评测说明](docs/RESULTS.md)。
|
| 46 |
+
|
| 47 |
+
## 快速开始
|
| 48 |
+
|
| 49 |
+
本模型仓库包含水稻和玉米的最终 PhenoClock adapter、Rooted Renderer 权重,以及对应的 [GitHub 代码](https://github.com/ECNU-ICALK/ArgoWM)。
|
| 50 |
+
|
| 51 |
+
克隆代码;模型文件在 Hugging Face 发布后,可运行下面的下载命令:
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
git clone https://github.com/ECNU-ICALK/ArgoWM.git
|
| 55 |
+
cd ArgoWM
|
| 56 |
+
|
| 57 |
+
python -m pip install -U huggingface_hub
|
| 58 |
+
hf download ecnu-icalk/ArgoWM --include 'checkpoints/**' --local-dir .
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
如果已下载完整的 Hugging Face 仓库,直接使用该目录即可。四份发布权重合计约 **30 GB**。
|
| 62 |
+
|
| 63 |
+
推理需要 **Linux、Python 3.12 和 NVIDIA GPU**:
|
| 64 |
+
|
| 65 |
+
1. [安装环境](docs/INSTALL.md),准备两套所需的原始基座模型。
|
| 66 |
+
2. [准备数据](docs/DATA.md),当前流程读取整理好的图像对 manifest。
|
| 67 |
+
3. 按照[模型加载与推理指南](docs/CHECKPOINTS.md#run-the-existing-benchmark-workflow)配置路径并运行 AgroWM。
|
| 68 |
+
|
| 69 |
+
从基座训练或评测预测结果,见[训练与评测指南](docs/RUNNING.md)。本次权重仅包含 **AgroWM**;原始基座、数据集和基线权重需另行准备。
|
| 70 |
+
|
| 71 |
+
## 文档
|
| 72 |
+
|
| 73 |
+
| 文档 | 内容 |
|
| 74 |
+
|---|---|
|
| 75 |
+
| [模型与推理](docs/CHECKPOINTS.md) | 模型组件、加载方式、推理命令和适用范围 |
|
| 76 |
+
| [训练与评测](docs/RUNNING.md) | 水稻和玉米的主线实验流程 |
|
| 77 |
+
| [Prompt](protocols/README.md) · [Growth Script](examples/README.md) | 提示词模板与脚本格式 |
|
| 78 |
+
| [实验设置](docs/PROTOCOL.md) | 训练配置与指标定义 |
|
| 79 |
+
| [代码与模型对应](docs/REPOSITORIES.md) | 配套版本、下载与校验 |
|
| 80 |
+
|
| 81 |
+
现有实验使用白背景水稻和玉米图像,田间场景与其他作物仍需进一步验证。问题和错误报告可提交到 [GitHub Issues](https://github.com/ECNU-ICALK/ArgoWM/issues)。
|
| 82 |
+
|
| 83 |
+
## 引用
|
| 84 |
+
|
| 85 |
+
如果本项目对你的研究有帮助,请引用我们的[论文](https://arxiv.org/abs/2611.26145):
|
| 86 |
+
|
| 87 |
+
```bibtex
|
| 88 |
+
@misc{ji2026agrowm,
|
| 89 |
+
title = {Can World Models Predict Rice Growth? Toward Agricultural World Models},
|
| 90 |
+
author = {Wenkai Ji and Zeteng Li and Yinkun Guo and Jie Zhou and Liang He and Zhenong Jin},
|
| 91 |
+
year = {2026},
|
| 92 |
+
eprint = {2611.26145},
|
| 93 |
+
archivePrefix = {arXiv},
|
| 94 |
+
url = {https://arxiv.org/abs/2611.26145}
|
| 95 |
+
}
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
## 许可证
|
| 99 |
+
|
| 100 |
+
代码、文档和 PhenoClock adapter 使用 **[Apache-2.0](LICENSE)**。Rooted Renderer 权重遵循 **[Qwen Research License](LICENSES.md)**,限非商业研究和评估。各组件的具体条款见 [LICENSES.md](LICENSES.md),署名见 [NOTICE](NOTICE)。
|
THIRD_PARTY.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party software and models
|
| 2 |
+
|
| 3 |
+
**Built with Qwen.** AgroWM code, documentation, and PhenoClock adapters use
|
| 4 |
+
[Apache-2.0](LICENSE). Rooted Renderer weights use the
|
| 5 |
+
[Qwen Research License](licenses/Qwen-Image-2.1-LICENSE.txt), which restricts use to
|
| 6 |
+
non-commercial research/evaluation. See [LICENSES.md](LICENSES.md) and [NOTICE](NOTICE).
|
| 7 |
+
External software, data and model parameters retain their own licenses; the
|
| 8 |
+
AgroWM license does not replace their terms.
|
| 9 |
+
|
| 10 |
+
| Dependency | Reference | Use |
|
| 11 |
+
|---|---|---|
|
| 12 |
+
| Qwen3.8-27B | https://huggingface.co/Qwen/Qwen3.8-27B | PhenoClock base model |
|
| 13 |
+
| Qwen Image 2.1 | https://huggingface.co/Qwen/Qwen-Image-2.1 | Rooted Renderer and image baselines |
|
| 14 |
+
| DiffSynth-Studio | https://github.com/modelscope/DiffSynth-Studio, commit `60b709c4dab8eeabce06ee9bc168328ed4c780e8` | Renderer training |
|
| 15 |
+
| Diffusers | https://github.com/huggingface/diffusers, commit `578c9b2c6636ab2424a0e56186268b83623656b2` | Image inference; use the full pinned revision in requirements/renderer.txt |
|
| 16 |
+
| ms-swift | https://github.com/modelscope/ms-swift, version 4.6.0 | Planner training and inference |
|
| 17 |
+
| Transformers | https://github.com/huggingface/transformers | Model and tokenizer interfaces |
|
| 18 |
+
| DINOv2 / timm | https://github.com/facebookresearch/dinov2 and https://github.com/huggingface/pytorch-image-models | Image evaluation |
|
| 19 |
+
|
| 20 |
+
Base-model files, third-party repositories and datasets are not vendored here.
|
| 21 |
+
Obtain them through their original distribution channels and retain the relevant
|
| 22 |
+
notices. WGSR and WGSM images belong to the Open Plant Image Archive dataset
|
| 23 |
+
families; follow the source datasets' access and redistribution terms.
|
| 24 |
+
|
| 25 |
+
`assets/method-overview.pdf` is the original Figure 3 extracted from the
|
| 26 |
+
manuscript, with a PNG preview. It has not been redrawn.
|
| 27 |
+
`assets/growth-script-templates.png` reproduces the project's Growth Script format
|
| 28 |
+
figure. Text files under `examples/` are synthetic format demonstrations, not
|
| 29 |
+
released dataset observations or measured model outputs.
|
checkpoints/README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AgroWM final model parameters
|
| 2 |
+
|
| 3 |
+
Rice and maize each contain a PhenoClock LoRA adapter and a Rooted Renderer full
|
| 4 |
+
diffusion-transformer checkpoint. All files belong to **Ours**; no baseline
|
| 5 |
+
parameters or optimizer states are included.
|
| 6 |
+
|
| 7 |
+
See [the loading guide](../docs/CHECKPOINTS.md) for required base models and
|
| 8 |
+
inference commands. [manifest.json](manifest.json) records component identities;
|
| 9 |
+
[SHA256SUMS](SHA256SUMS) provides checksums relative to the repository root.
|
checkpoints/maize/phenoclock/adapter_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d7ce12e54a8275c43e2649301c31edb5a2a85652783b17a1d98fe325b8a05c9
|
| 3 |
+
size 467063552
|
checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5385aa6df6c211c488b451acd611a26fabda96ef3142a3f949454f278792f60
|
| 3 |
+
size 14230284584
|
checkpoints/rice/phenoclock/adapter_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8f02194330f037d6882cc91be2e3bb3dbfc26b3b5843aa01878d93b98150ec3a
|
| 3 |
+
size 933974032
|
checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:545a91b5bb832e19787d073cdc8609e387aef831b06718031a05898a4a556708
|
| 3 |
+
size 14230284584
|
licenses/Qwen3.8-27B-LICENSE.txt
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright 2026 Alibaba Cloud
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
pyproject.toml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "agrowm"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "AgroWM: developmental reasoning for plant growth forecasting"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = {file = "LICENSE"}
|
| 11 |
+
requires-python = ">=3.12"
|
| 12 |
+
dependencies = ["numpy>=2", "Pillow>=11", "PyYAML>=6", "scipy>=1.14"]
|
| 13 |
+
|
| 14 |
+
[tool.setuptools.packages.find]
|
| 15 |
+
where = ["src"]
|
| 16 |
+
include = ["wgsr_v9*"]
|
| 17 |
+
|
| 18 |
+
[tool.ruff]
|
| 19 |
+
line-length = 100
|
| 20 |
+
target-version = "py312"
|
src/wgsr_v9/cot_evaluation/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline evaluation of observable planner CoT content."""
|
| 2 |
+
|
| 3 |
+
ALGORITHM_VERSION = "wgsr_v9_planner_cot_evaluator_v1_3"
|
| 4 |
+
PROTOCOL_VERSION = "wgsr_v9_planner_cot_quality_evaluation_v1"
|
src/wgsr_v9/cot_evaluation/metrics.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Metrics with explicit reference and prediction coverage denominators."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import Counter
|
| 5 |
+
import math
|
| 6 |
+
import statistics
|
| 7 |
+
from typing import Any, Sequence
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def ratio(numerator: float, denominator: int | float) -> float | None:
|
| 11 |
+
return numerator / denominator if denominator else None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def classification(truth: Sequence[Any], prediction: Sequence[Any], labels: Sequence[Any],
|
| 15 |
+
*, weights: Sequence[float] | None = None) -> dict[str, Any]:
|
| 16 |
+
if len(truth) != len(prediction):
|
| 17 |
+
raise ValueError("classification arrays are not aligned")
|
| 18 |
+
weight = list(weights) if weights is not None else [1.0] * len(truth)
|
| 19 |
+
if len(weight) != len(truth):
|
| 20 |
+
raise ValueError("classification weights are not aligned")
|
| 21 |
+
counts: Counter[tuple[Any, Any]] = Counter()
|
| 22 |
+
for y, p, w in zip(truth, prediction, weight):
|
| 23 |
+
if y not in labels:
|
| 24 |
+
raise ValueError(f"unknown reference label: {y}")
|
| 25 |
+
counts[(y, p if p in labels else None)] += w
|
| 26 |
+
total = sum(weight)
|
| 27 |
+
valid = sum(w for p, w in zip(prediction, weight) if p in labels)
|
| 28 |
+
correct = sum(counts[(label, label)] for label in labels)
|
| 29 |
+
per_class = []
|
| 30 |
+
for label in labels:
|
| 31 |
+
tp = counts[(label, label)]
|
| 32 |
+
support = sum(v for (y, _), v in counts.items() if y == label)
|
| 33 |
+
predicted = sum(v for (_, p), v in counts.items() if p == label)
|
| 34 |
+
per_class.append({"label": label, "support": support, "predicted": predicted,
|
| 35 |
+
"precision": ratio(tp, predicted), "recall": ratio(tp, support),
|
| 36 |
+
"f1": 2 * tp / (support + predicted) if support + predicted else 0.0})
|
| 37 |
+
return {"n_reference": len(truth), "weight_sum": total, "n_parsed": sum(p in labels for p in prediction),
|
| 38 |
+
"coverage": ratio(valid, total), "accuracy": ratio(correct, total),
|
| 39 |
+
"macro_f1": statistics.fmean(r["f1"] for r in per_class) if total else None,
|
| 40 |
+
"balanced_accuracy": statistics.fmean(r["recall"] for r in per_class if r["support"]) if total else None,
|
| 41 |
+
"per_class": per_class,
|
| 42 |
+
"confusion": [{"reference": y, "prediction": p if p is not None else "invalid", "count": count}
|
| 43 |
+
for (y, p), count in counts.items()]}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def direction(value: float, deadband: float) -> str:
|
| 47 |
+
return "decrease" if value < -deadband else ("increase" if value > deadband else "stable")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def numeric(truth: Sequence[float | None], prediction: Sequence[float | None], *,
|
| 51 |
+
tolerances: Sequence[float] = (1, 2, 5)) -> dict[str, Any]:
|
| 52 |
+
if len(truth) != len(prediction):
|
| 53 |
+
raise ValueError("numeric arrays are not aligned")
|
| 54 |
+
eligible = [(float(y), float(p) if p is not None and math.isfinite(p) else None)
|
| 55 |
+
for y, p in zip(truth, prediction) if y is not None and math.isfinite(y)]
|
| 56 |
+
error = [p - y for y, p in eligible if p is not None]
|
| 57 |
+
absolute = [abs(e) for e in error]
|
| 58 |
+
return {"n_reference": len(eligible), "n_parsed": len(error), "coverage": ratio(len(error), len(eligible)),
|
| 59 |
+
"mae": statistics.fmean(absolute) if error else None,
|
| 60 |
+
"median_absolute_error": statistics.median(absolute) if error else None,
|
| 61 |
+
"rmse": math.sqrt(statistics.fmean(e * e for e in error)) if error else None,
|
| 62 |
+
"signed_bias": statistics.fmean(error) if error else None,
|
| 63 |
+
"within_tolerance": {str(t): ratio(sum(e <= t + 1e-10 for e in absolute), len(eligible)) for t in tolerances}}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def direction_metrics(truth: Sequence[float | None], prediction: Sequence[float | None],
|
| 67 |
+
*, deadband: float) -> dict[str, Any]:
|
| 68 |
+
pairs = [(y, p) for y, p in zip(truth, prediction) if y is not None]
|
| 69 |
+
ys = [direction(y, deadband) for y, _ in pairs]
|
| 70 |
+
ps = [direction(p, deadband) if p is not None else None for _, p in pairs]
|
| 71 |
+
result = classification(ys, ps, ["decrease", "stable", "increase"])
|
| 72 |
+
changed = [(y, p) for y, p in zip(ys, ps) if y != "stable"]
|
| 73 |
+
result.update(deadband_pp=deadband, changed_reference_count=len(changed),
|
| 74 |
+
changed_only_accuracy=ratio(sum(y == p for y, p in changed), len(changed)))
|
| 75 |
+
return result
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def stage_metrics(truth: Sequence[str], prediction: Sequence[str | None], stages: list[str]) -> dict[str, Any]:
|
| 79 |
+
result = classification(truth, prediction, stages)
|
| 80 |
+
differences = [stages.index(p) - stages.index(y) for y, p in zip(truth, prediction) if p in stages]
|
| 81 |
+
result.update(ordinal_mae=statistics.fmean(abs(d) for d in differences) if differences else None,
|
| 82 |
+
signed_stage_bias=statistics.fmean(differences) if differences else None,
|
| 83 |
+
within_one_stage_accuracy=ratio(sum(abs(d) <= 1 for d in differences), len(truth)))
|
| 84 |
+
return result
|
src/wgsr_v9/cot_evaluation/parser.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lossless field locations and independent endpoint parsing; no text repair."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from decimal import Decimal, InvalidOperation
|
| 6 |
+
import re
|
| 7 |
+
from typing import Any
|
| 8 |
+
from ..cot_metric_names import validate_metric_name
|
| 9 |
+
|
| 10 |
+
SECTIONS = ("Stage reasoning", "Growth plan", "Target phenotype")
|
| 11 |
+
NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)"
|
| 12 |
+
TRANSLATE = str.maketrans({"%": "%", "−": "-", "+": "+"})
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def scalar(text: str, role: str, *, binary: bool = False) -> tuple[float | int | None, str | None]:
|
| 16 |
+
matches = list(re.finditer(rf"\b{role}\s*=", text))
|
| 17 |
+
if len(matches) != 1:
|
| 18 |
+
return None, "missing" if not matches else "duplicate"
|
| 19 |
+
suffix = text[matches[0].end():].strip()
|
| 20 |
+
if binary and role != "Change":
|
| 21 |
+
match = re.match(r"(not visible|visible)(?=\s*(?:;|\.(?:\s|$)|$))", suffix)
|
| 22 |
+
return (int(match[1] == "visible"), None) if match else (None, "invalid_binary_label")
|
| 23 |
+
unit = "" if binary else ("pp" if role == "Change" else "%")
|
| 24 |
+
match = re.match(rf"({NUMBER})\s*{unit}(?=\s*(?:;|\.(?:\s|$)|$))", suffix)
|
| 25 |
+
if not match or len(match[1]) > 32:
|
| 26 |
+
return None, "invalid_number_or_unit"
|
| 27 |
+
try:
|
| 28 |
+
value = Decimal(match[1])
|
| 29 |
+
except InvalidOperation:
|
| 30 |
+
return None, "invalid_number"
|
| 31 |
+
lower, upper = (-1, 1) if binary else ((-100, 100) if role == "Change" else (0, 100))
|
| 32 |
+
if not value.is_finite() or not lower <= value <= upper:
|
| 33 |
+
return None, "out_of_range"
|
| 34 |
+
if binary and value != int(value):
|
| 35 |
+
return None, "noninteger_change"
|
| 36 |
+
return (int(value) if binary else float(value)), None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_cot(text: str, view: str, bindings: dict[str, Any], stages: list[str],
|
| 40 |
+
*, finish_reason: str = "stop", output_wrapper: str = "think") -> dict[str, Any]:
|
| 41 |
+
issues: list[str] = []
|
| 42 |
+
normalized_events: list[str] = []
|
| 43 |
+
if "\r" in text:
|
| 44 |
+
normalized_events.append("line_endings")
|
| 45 |
+
if text.translate(TRANSLATE) != text:
|
| 46 |
+
normalized_events.append("unicode_numeric_characters")
|
| 47 |
+
if finish_reason in {"length", "max_tokens", "max_new_tokens"}:
|
| 48 |
+
issues.append("truncated")
|
| 49 |
+
if output_wrapper == "think":
|
| 50 |
+
wrapper = re.fullmatch(r"\s*<think>(.*?)</think>\s*", text, re.DOTALL)
|
| 51 |
+
wrapper_valid = (text.count("<think>") == text.count("</think>") == 1
|
| 52 |
+
and "<GROWTH_COT>" not in text and "</GROWTH_COT>" not in text)
|
| 53 |
+
elif output_wrapper == "GROWTH_COT":
|
| 54 |
+
wrapper = re.fullmatch(r"\s*(?:<think>\s*</think>\s*)?<GROWTH_COT>(.*?)</GROWTH_COT>\s*",
|
| 55 |
+
text, re.DOTALL)
|
| 56 |
+
wrapper_valid = (text.count("<GROWTH_COT>") == text.count("</GROWTH_COT>") == 1
|
| 57 |
+
and text.count("<think>") == text.count("</think>") <= 1)
|
| 58 |
+
if wrapper and ("<think>" in wrapper[1] or "</think>" in wrapper[1]):
|
| 59 |
+
wrapper_valid = False
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"unsupported output wrapper: {output_wrapper}")
|
| 62 |
+
if not wrapper or not wrapper_valid:
|
| 63 |
+
issues.append("invalid_wrapper")
|
| 64 |
+
if wrapper:
|
| 65 |
+
body, offset = wrapper[1], wrapper.start(1)
|
| 66 |
+
else:
|
| 67 |
+
body, offset = text, 0
|
| 68 |
+
section: str | None = None
|
| 69 |
+
headings: list[str] = []
|
| 70 |
+
points: dict[str, dict[str, list[dict[str, Any]]]] = {s: defaultdict(list) for s in SECTIONS}
|
| 71 |
+
labels = {value: key for key, value in bindings[view]["section_labels"].items()}
|
| 72 |
+
expected = bindings[view]["ordered_keys"]
|
| 73 |
+
cursor = offset
|
| 74 |
+
for raw in body.splitlines(keepends=True):
|
| 75 |
+
line = raw.strip()
|
| 76 |
+
start, end = cursor, cursor + len(raw)
|
| 77 |
+
cursor = end
|
| 78 |
+
if not line or line in {"<think>", "</think>"}:
|
| 79 |
+
continue
|
| 80 |
+
if line in SECTIONS:
|
| 81 |
+
section = line
|
| 82 |
+
headings.append(line)
|
| 83 |
+
continue
|
| 84 |
+
if section is None:
|
| 85 |
+
issues.append("content_outside_sections")
|
| 86 |
+
continue
|
| 87 |
+
label, separator, value = line.partition(":")
|
| 88 |
+
label, value = label.strip(), value.strip()
|
| 89 |
+
valid_labels = {"Current stage": "current", "Future stage": "future"} if section == SECTIONS[0] else labels
|
| 90 |
+
if not separator or label not in valid_labels:
|
| 91 |
+
issues.append(f"unknown_or_wrong_view_field:{section}:{label}")
|
| 92 |
+
continue
|
| 93 |
+
key = valid_labels[label]
|
| 94 |
+
points[section][key].append({"start": start, "end": end, "raw": raw,
|
| 95 |
+
"label": label, "text": value})
|
| 96 |
+
if headings != list(SECTIONS):
|
| 97 |
+
issues.append("missing_duplicate_or_unordered_sections")
|
| 98 |
+
stage_values: dict[str, str | None] = {}
|
| 99 |
+
stage_errors: dict[str, str | None] = {}
|
| 100 |
+
for key in ("current", "future"):
|
| 101 |
+
occurrences = points[SECTIONS[0]].get(key, [])
|
| 102 |
+
value = occurrences[0]["text"].removesuffix(".").strip() if len(occurrences) == 1 else None
|
| 103 |
+
error = ("missing" if not occurrences else "duplicate") if len(occurrences) != 1 else (None if value in stages else "unknown_stage")
|
| 104 |
+
stage_values[key] = value if error is None else None
|
| 105 |
+
stage_errors[key] = error
|
| 106 |
+
if error:
|
| 107 |
+
issues.append(f"stage:{key}:{error}")
|
| 108 |
+
fields: dict[str, Any] = {}
|
| 109 |
+
qualitative: dict[str, dict[str, str | None]] = {s: {} for s in SECTIONS[1:]}
|
| 110 |
+
for section in SECTIONS[1:]:
|
| 111 |
+
for key in expected:
|
| 112 |
+
occurrences = points[section].get(key, [])
|
| 113 |
+
valid = len(occurrences) == 1 and bool(occurrences[0]["text"])
|
| 114 |
+
if not valid:
|
| 115 |
+
problem = "missing" if not occurrences else ("duplicate" if len(occurrences) > 1 else "empty")
|
| 116 |
+
issues.append(f"point:{section}:{key}:{problem}")
|
| 117 |
+
value = occurrences[0]["text"] if valid else None
|
| 118 |
+
if section == "Target phenotype":
|
| 119 |
+
if value and re.search(r"\b(?:Metric|Source|Target|Change)\s*=|\d\s*(?:%|%|pp\b)", value):
|
| 120 |
+
issues.append(f"numeric_phenotype:{key}")
|
| 121 |
+
qualitative[section][key] = value
|
| 122 |
+
continue
|
| 123 |
+
normalized = value.translate(TRANSLATE) if value else ""
|
| 124 |
+
metric_error = None
|
| 125 |
+
if valid:
|
| 126 |
+
try:
|
| 127 |
+
validate_metric_name(value, key, bindings[view])
|
| 128 |
+
except ValueError as exc:
|
| 129 |
+
metric_error = str(exc)
|
| 130 |
+
issues.append(f"metric_binding:{key}:{metric_error}")
|
| 131 |
+
values: dict[str, Any] = {}
|
| 132 |
+
errors: dict[str, str | None] = {}
|
| 133 |
+
for role, output in (("Source", "source"), ("Target", "target"), ("Change", "declared_change")):
|
| 134 |
+
parsed, error = scalar(normalized, role, binary=key == "panicle") if valid else (None, "invalid_field")
|
| 135 |
+
if metric_error:
|
| 136 |
+
parsed, error = None, "invalid_metric_binding"
|
| 137 |
+
values[output], errors[output] = parsed, error
|
| 138 |
+
derived = None
|
| 139 |
+
residual = None
|
| 140 |
+
if values["source"] is not None and values["target"] is not None:
|
| 141 |
+
derived = float(Decimal(str(values["target"])) - Decimal(str(values["source"])))
|
| 142 |
+
if values["declared_change"] is not None:
|
| 143 |
+
residual = float(Decimal(str(values["declared_change"])) - Decimal(str(derived)))
|
| 144 |
+
prefix = re.split(r"\b(?:Metric|Source|Target|Change)\s*=", value or "", maxsplit=1)[0].strip()
|
| 145 |
+
qualitative[section][key] = prefix if valid and prefix else None
|
| 146 |
+
if valid and not prefix:
|
| 147 |
+
issues.append(f"point:{section}:{key}:empty_qualitative")
|
| 148 |
+
fields[key] = {**values, "derived_change": derived, "arithmetic_residual": residual,
|
| 149 |
+
"parse_errors": errors, "raw_text": value,
|
| 150 |
+
"numeric_assignment_present": bool(re.search(r"\b(?:Source|Target|Change)\s*=", normalized))}
|
| 151 |
+
return {"structure_valid": not issues, "issues": sorted(set(issues)), "issue_counts": dict(Counter(issues)),
|
| 152 |
+
"normalizations": normalized_events, "stages": stage_values, "stage_errors": stage_errors,
|
| 153 |
+
"fields": fields, "qualitative": qualitative, "occurrences": points,
|
| 154 |
+
"heading_order": headings, "finish_reason": finish_reason}
|
src/wgsr_v9/cot_evaluation/reference.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen input alignment and reference scoring, independent of teacher phrasing."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from ..evaluation_io import read_jsonl, sha256_file
|
| 10 |
+
from . import ALGORITHM_VERSION, PROTOCOL_VERSION
|
| 11 |
+
from .parser import parse_cot
|
| 12 |
+
from ..cot_metric_names import FORMAT, name_cot_evidence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def text_hash(text: str) -> str:
|
| 16 |
+
return hashlib.sha256(text.encode()).hexdigest()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def indexed(rows: list[dict[str, Any]], key: str) -> dict[str, dict[str, Any]]:
|
| 20 |
+
result = {row[key]: row for row in rows}
|
| 21 |
+
if len(result) != len(rows):
|
| 22 |
+
raise ValueError(f"duplicate {key}")
|
| 23 |
+
return result
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def alias_fields(values: dict[str, Any], aliases: dict[str, str]) -> dict[str, Any]:
|
| 28 |
+
"""Map versioned field IDs to evaluation IDs without touching model text."""
|
| 29 |
+
result = {aliases.get(key, key): value for key, value in values.items()}
|
| 30 |
+
if len(result) != len(values):
|
| 31 |
+
raise ValueError("field alias collision")
|
| 32 |
+
return result
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def same_image(a: Path, b: Path, *, allow_hash_match: bool,
|
| 36 |
+
cache: dict[Path, str]) -> bool:
|
| 37 |
+
if a == b:
|
| 38 |
+
return True
|
| 39 |
+
if not allow_hash_match:
|
| 40 |
+
return False
|
| 41 |
+
for path in (a, b):
|
| 42 |
+
if path not in cache:
|
| 43 |
+
cache[path] = sha256_file(path)
|
| 44 |
+
return cache[a] == cache[b]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def score_fields(parsed: dict[str, Any], request: dict[str, Any], contract: dict[str, Any]) -> dict[str, Any]:
|
| 48 |
+
output: dict[str, Any] = {}
|
| 49 |
+
for key, evidence in request["metric_evidence"].items():
|
| 50 |
+
predicted = parsed["fields"][key]
|
| 51 |
+
binary = key == "panicle"
|
| 52 |
+
spec = None if binary else contract["continuous_metrics"][key]
|
| 53 |
+
if spec and evidence["metric_key"] != spec["metric_key"]:
|
| 54 |
+
raise ValueError(f"reference metric mismatch: {key}")
|
| 55 |
+
multiplier = 1 if binary else spec["display_multiplier"]
|
| 56 |
+
reference: dict[str, float | None] = {}
|
| 57 |
+
for role in ("source", "target"):
|
| 58 |
+
observation = evidence[role]
|
| 59 |
+
reference[role] = (float(observation["value"]) * multiplier
|
| 60 |
+
if observation["status"] == "available" and evidence["qc"].get("valid") is True else None)
|
| 61 |
+
both = all(reference[role] is not None for role in ("source", "target"))
|
| 62 |
+
delta = reference["target"] - reference["source"] if both else None
|
| 63 |
+
reference.update(declared_change=delta, derived_change=delta)
|
| 64 |
+
output[key] = {
|
| 65 |
+
"reference": reference,
|
| 66 |
+
"prediction": {role: predicted[role] for role in reference},
|
| 67 |
+
"reference_status": {role: evidence[role]["status"] for role in ("source", "target")},
|
| 68 |
+
"reference_qc": evidence["qc"], "metric_key": evidence["metric_key"],
|
| 69 |
+
"unit": "binary" if binary else "percentage_points", "parse_errors": predicted["parse_errors"],
|
| 70 |
+
"arithmetic_residual": predicted["arithmetic_residual"],
|
| 71 |
+
"arithmetic_consistent": (abs(predicted["arithmetic_residual"]) <= (0 if binary else .02) + 1e-10
|
| 72 |
+
if predicted["arithmetic_residual"] is not None else None),
|
| 73 |
+
"unscorable_assertions": [role for role in ("source", "target") if reference[role] is None and predicted[role] is not None],
|
| 74 |
+
}
|
| 75 |
+
return output
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_inputs(config: dict[str, Any], root: Path, output: Path) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, Any], list[str]]:
|
| 79 |
+
contract = json.loads((root / config["protocol"]).read_text())
|
| 80 |
+
protocol_root = root / config["cot_protocol_root"]
|
| 81 |
+
bindings = json.loads((protocol_root / "VIEW_VARIABLE_BINDINGS.json").read_text())
|
| 82 |
+
aliases = config.get("field_aliases", {})
|
| 83 |
+
for view in ("front", "top"):
|
| 84 |
+
spec = bindings[view]
|
| 85 |
+
for key, value in list(spec.items()):
|
| 86 |
+
if isinstance(value, dict):
|
| 87 |
+
spec[key] = alias_fields(value, aliases)
|
| 88 |
+
spec["ordered_keys"] = [aliases.get(key, key) for key in spec["ordered_keys"]]
|
| 89 |
+
wrapper = config.get("output_wrapper", "think")
|
| 90 |
+
allow_hash_match = config.get("allow_image_hash_match", False)
|
| 91 |
+
image_hash_cache: dict[Path, str] = {}
|
| 92 |
+
validation_root = (root / config["planner_validation"]).parent
|
| 93 |
+
stages = json.loads((protocol_root / "OUTPUT_SCHEMA_FRONT.json").read_text())["$defs"]["stage_id"]["enum"]
|
| 94 |
+
predictions = indexed(read_jsonl(root / config["prediction_ledger"]), "request_id")
|
| 95 |
+
validation = indexed(read_jsonl(root / config["planner_validation"]), "id")
|
| 96 |
+
canonical = read_jsonl(root / config["canonical_manifest"])
|
| 97 |
+
canonical_index = indexed(canonical, "pair_id")
|
| 98 |
+
if set(validation) != set(canonical_index) or not set(predictions).issubset(canonical_index):
|
| 99 |
+
raise ValueError("input ID sets do not align")
|
| 100 |
+
requests: dict[str, Any] = {}
|
| 101 |
+
for row in read_jsonl(root / config["reference_requests"]):
|
| 102 |
+
if row["request_id"] in canonical_index:
|
| 103 |
+
if row["request_id"] in requests:
|
| 104 |
+
raise ValueError("duplicate reference request")
|
| 105 |
+
row["metric_evidence"] = alias_fields(row["metric_evidence"], aliases)
|
| 106 |
+
requests[row["request_id"]] = row
|
| 107 |
+
if set(requests) != set(canonical_index):
|
| 108 |
+
raise ValueError("missing reference requests")
|
| 109 |
+
if len(canonical) != config["expected_validation_rows"]:
|
| 110 |
+
raise ValueError("unexpected validation count")
|
| 111 |
+
scored = []
|
| 112 |
+
teacher_max_rounding_error = 0.0
|
| 113 |
+
reference_digest = hashlib.sha256()
|
| 114 |
+
for index, canonical_row in enumerate(canonical):
|
| 115 |
+
request_id = canonical_row["pair_id"]
|
| 116 |
+
request, training = requests[request_id], validation[request_id]
|
| 117 |
+
prediction = predictions.get(request_id)
|
| 118 |
+
if request["split"] != "val" or training["planner_metadata"]["cot_version"] != config["cot_version"]:
|
| 119 |
+
raise ValueError(f"wrong split/version: {request_id}")
|
| 120 |
+
if request["source"]["path"] != canonical_row["source_image_path"] or request["target"]["path"] != canonical_row["target_image_path"]:
|
| 121 |
+
raise ValueError(f"image identity mismatch: {request_id}")
|
| 122 |
+
training_image = Path(training["input_path"])
|
| 123 |
+
if not training_image.is_absolute():
|
| 124 |
+
training_image = validation_root / training_image
|
| 125 |
+
if not same_image(training_image, Path(request["source"]["path"]),
|
| 126 |
+
allow_hash_match=allow_hash_match, cache=image_hash_cache):
|
| 127 |
+
raise ValueError(f"training image identity mismatch: {request_id}")
|
| 128 |
+
if prediction and (not same_image(Path(prediction["input_path"]), training_image,
|
| 129 |
+
allow_hash_match=allow_hash_match, cache=image_hash_cache) or prediction["view"] != request["view"] or prediction["cot_version"] != config["cot_version"]):
|
| 130 |
+
raise ValueError(f"prediction identity mismatch: {request_id}")
|
| 131 |
+
if training["messages"][-1]["role"] != "assistant":
|
| 132 |
+
raise ValueError("teacher message not found")
|
| 133 |
+
teacher_text = training["messages"][-1]["content"]
|
| 134 |
+
provider = root / config["teacher_provider_root"]
|
| 135 |
+
annotation_path = provider / "annotations" / f"{request_id}.json"
|
| 136 |
+
rendered_path = provider / "rendered" / f"{request_id}.txt"
|
| 137 |
+
annotation = json.loads(annotation_path.read_text())
|
| 138 |
+
rendered = rendered_path.read_text().strip()
|
| 139 |
+
teacher_body = teacher_text.strip().removeprefix(f"<{wrapper}>").removesuffix(f"</{wrapper}>").strip()
|
| 140 |
+
expected_body = rendered.removeprefix("<GROWTH_COT>").removesuffix("</GROWTH_COT>").strip()
|
| 141 |
+
if bindings[request["view"]].get("numeric_evidence_format") == FORMAT:
|
| 142 |
+
expected_body = name_cot_evidence(expected_body, request["view"], bindings)
|
| 143 |
+
if expected_body != teacher_body:
|
| 144 |
+
raise ValueError(f"teacher renderer differs: {request_id}")
|
| 145 |
+
for role, ref_side in (("current", "source"), ("future", "target")):
|
| 146 |
+
if annotation["stage_reasoning"][f"{role}_stage"] != request[ref_side]["stage_id"]:
|
| 147 |
+
raise ValueError("teacher stage/reference mismatch")
|
| 148 |
+
reference_digest.update(request_id.encode() + b"\0" + annotation_path.read_bytes() + b"\0" + rendered_path.read_bytes())
|
| 149 |
+
teacher = parse_cot(teacher_text, request["view"], bindings, stages, output_wrapper=wrapper)
|
| 150 |
+
if not teacher["structure_valid"]:
|
| 151 |
+
raise ValueError(f"teacher structure invalid: {request_id}: {teacher['issues']}")
|
| 152 |
+
teacher_fields = score_fields(teacher, request, contract)
|
| 153 |
+
for key, field in teacher_fields.items():
|
| 154 |
+
for role, ref in field["reference"].items():
|
| 155 |
+
if ref is None:
|
| 156 |
+
continue
|
| 157 |
+
pred = field["prediction"][role]
|
| 158 |
+
tolerance = 0 if key == "panicle" else (.010001 if role == "derived_change" else .005001)
|
| 159 |
+
if pred is None or abs(pred - ref) > tolerance:
|
| 160 |
+
raise ValueError(f"teacher numeric self-check failed: {request_id}/{key}/{role}")
|
| 161 |
+
teacher_max_rounding_error = max(teacher_max_rounding_error, abs(pred - ref))
|
| 162 |
+
raw = prediction[config["text_field"]] if prediction else ""
|
| 163 |
+
parsed = parse_cot(raw, request["view"], bindings, stages,
|
| 164 |
+
finish_reason=prediction.get("finish_reason", "unknown") if prediction else "missing",
|
| 165 |
+
output_wrapper=wrapper)
|
| 166 |
+
if config.get("validate_direct_contract", False):
|
| 167 |
+
from ..planner_direct import validate_direct_body
|
| 168 |
+
for text, result in ((teacher_text, teacher), (raw, parsed)):
|
| 169 |
+
try:
|
| 170 |
+
# Wrapper validity is checked separately and never repaired.
|
| 171 |
+
body = text.split("<GROWTH_COT>", 1)[-1].split("</GROWTH_COT>", 1)[0]
|
| 172 |
+
validate_direct_body(body.strip(), request["view"])
|
| 173 |
+
except ValueError as exc:
|
| 174 |
+
result["issues"].append(f"direct_contract:{exc}")
|
| 175 |
+
result["structure_valid"] = False
|
| 176 |
+
if not teacher["structure_valid"]:
|
| 177 |
+
raise ValueError(f"teacher direct contract invalid: {request_id}")
|
| 178 |
+
fields = score_fields(parsed, request, contract)
|
| 179 |
+
numeric_issues = [f"numeric:{key}:{role}:{error}" for key, field in fields.items()
|
| 180 |
+
for role, error in field["parse_errors"].items()
|
| 181 |
+
if field["reference"][role] is not None and error]
|
| 182 |
+
# Numeric evidence omitted by reference QC is allowed by the rendering contract.
|
| 183 |
+
strict = parsed["structure_valid"] and not numeric_issues
|
| 184 |
+
scored.append({
|
| 185 |
+
"algorithm_version": ALGORITHM_VERSION, "protocol_version": PROTOCOL_VERSION,
|
| 186 |
+
"request_id": request_id, "pair_group_id": request["pair_group_id"], "plant_id": request["plant_id"],
|
| 187 |
+
"row_index": index, "view": request["view"], "actual_interval_days": request["actual_interval_days"],
|
| 188 |
+
"horizon_bucket": canonical_row["horizon_bucket"], "source_path": request["source"]["path"],
|
| 189 |
+
"target_path": request["target"]["path"], "source_stage": request["source"]["stage_id"],
|
| 190 |
+
"target_stage": request["target"]["stage_id"],
|
| 191 |
+
"same_stage_or_cross_stage": "same" if request["source"]["stage_id"] == request["target"]["stage_id"] else "cross",
|
| 192 |
+
"panicle_emergence": fields["panicle"]["reference"]["derived_change"] == 1,
|
| 193 |
+
"input_path": str(root / config["prediction_ledger"]), "output_path": str(output / "per_sample.jsonl"),
|
| 194 |
+
"status": "scored" if prediction else "missing_prediction", "error": None if prediction else "prediction missing",
|
| 195 |
+
"retry_count": 0, "prediction_sha256": text_hash(raw), "reference_sha256": text_hash(json.dumps(request, sort_keys=True)),
|
| 196 |
+
"teacher_sha256": text_hash(teacher_text), "raw_text": raw, "teacher_text": teacher_text,
|
| 197 |
+
"parse_status": "valid" if strict else "partial_or_invalid", "strict_structure_valid": strict,
|
| 198 |
+
"issues": parsed["issues"] + numeric_issues, "parsed": parsed, "teacher_parsed": teacher,
|
| 199 |
+
"numeric": fields, "denominator_eligibility": {key: {role: value is not None for role, value in field["reference"].items()} for key, field in fields.items()},
|
| 200 |
+
})
|
| 201 |
+
if len({r["plant_id"] for r in scored}) != config["expected_plants"] or len({r["pair_group_id"] for r in scored}) != config["expected_pair_groups"]:
|
| 202 |
+
raise ValueError("unexpected plant or pair-group count")
|
| 203 |
+
audit = {"status": "passed", "rows": len(scored), "predictions": len(predictions),
|
| 204 |
+
"missing_predictions": len(canonical) - len(predictions), "teacher_selfcheck_rows": len(scored),
|
| 205 |
+
"teacher_max_rounding_error_pp_including_derived_change": teacher_max_rounding_error,
|
| 206 |
+
"provider_reference_sha256": reference_digest.hexdigest(),
|
| 207 |
+
"input_hashes": {key: sha256_file(root / config[key]) for key in ("prediction_ledger", "planner_validation", "canonical_manifest", "reference_requests", "protocol")},
|
| 208 |
+
"binding_sha256": sha256_file(protocol_root / "VIEW_VARIABLE_BINDINGS.json"),
|
| 209 |
+
"output_wrapper": wrapper, "field_aliases": aliases,
|
| 210 |
+
"image_identity_mode": "path_or_sha256" if allow_hash_match else "exact_path",
|
| 211 |
+
"image_files_hashed": len(image_hash_cache)}
|
| 212 |
+
return scored, audit, contract, stages
|
src/wgsr_v9/cot_evaluation/report.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-field summaries, grouped diagnostics and observable consistency."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
import re
|
| 6 |
+
import statistics
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from .metrics import classification, direction_metrics, numeric, ratio, stage_metrics
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def explicit_metric_direction(text: str, key: str) -> set[str]:
|
| 13 |
+
"""Find direct metric predicates, excluding modifiers of other plant parts."""
|
| 14 |
+
anchor = {
|
| 15 |
+
"culm": r"(?:culm height|plant height|height|culm|plant)",
|
| 16 |
+
"leaves_area": r"(?:leaf area|visible (?:leaf )?area|foliage area)",
|
| 17 |
+
"yellow_brown_fraction": r"yellow.brown (?:fraction|proportion|coloration|coloring)",
|
| 18 |
+
}[key]
|
| 19 |
+
# Do not cross clauses or nouns: "lower leaves" is a location and "greater
|
| 20 |
+
# share of green foliage" is a different quantity, not the named metric.
|
| 21 |
+
auxiliary = r"(?:(?:is expected to (?:be )?|will be |will |has |have |is |are |appears |seems |becomes |become |shows |show ))?"
|
| 22 |
+
modifier = r"(?:(?:visibly|slightly|clearly|substantially|much|now)\s+){0,2}"
|
| 23 |
+
predicates = {
|
| 24 |
+
"increase": r"(?:increase[ds]?|higher|greater|taller|expand(?:ed|s)?|more apparent|more prominent)",
|
| 25 |
+
"decrease": r"(?:decrease[ds]?|lower|smaller|shorter|reduce[ds]?|less apparent|less prominent)",
|
| 26 |
+
}
|
| 27 |
+
return {direction for direction, predicate in predicates.items()
|
| 28 |
+
if re.search(r"\b" + anchor + r"\s+" + auxiliary + modifier + predicate + r"\b", text, re.I)}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def summarize(rows: list[dict[str, Any]], stages: list[str], contract: dict[str, Any]) -> dict[str, Any]:
|
| 32 |
+
stage = {role: stage_metrics([r[side] for r in rows], [r["parsed"]["stages"][role] for r in rows], stages)
|
| 33 |
+
for role, side in (("current", "source_stage"), ("future", "target_stage"))}
|
| 34 |
+
transitions, reference_transitions = [], []
|
| 35 |
+
for r in rows:
|
| 36 |
+
current, future = (r["parsed"]["stages"][k] for k in ("current", "future"))
|
| 37 |
+
transitions.append(None if current is None or future is None else ("same" if current == future else ("forward" if stages.index(future) > stages.index(current) else "backward")))
|
| 38 |
+
reference_transitions.append("same" if r["source_stage"] == r["target_stage"] else "forward")
|
| 39 |
+
stage["transition"] = classification(reference_transitions, transitions, ["same", "forward"])
|
| 40 |
+
stage["transition"].update(backward_count=transitions.count("backward"),
|
| 41 |
+
backward_rate_all=ratio(transitions.count("backward"), len(rows)),
|
| 42 |
+
parsed_transition_count=sum(t is not None for t in transitions))
|
| 43 |
+
num = {}
|
| 44 |
+
for key in contract["continuous_metrics"]:
|
| 45 |
+
fields = [r["numeric"][key] for r in rows if key in r["numeric"]]
|
| 46 |
+
if not fields:
|
| 47 |
+
continue
|
| 48 |
+
record: dict[str, Any] = {"n_applicable": len(fields)}
|
| 49 |
+
for role in ("source", "target", "declared_change", "derived_change"):
|
| 50 |
+
truth = [f["reference"][role] for f in fields]
|
| 51 |
+
prediction = [f["prediction"][role] for f in fields]
|
| 52 |
+
record[role] = numeric(truth, prediction, tolerances=contract["numeric_scoring"]["tolerances_pp"])
|
| 53 |
+
if role in {"declared_change", "derived_change"}:
|
| 54 |
+
record[role]["direction"] = {
|
| 55 |
+
str(band): direction_metrics(truth, prediction, deadband=band)
|
| 56 |
+
for band in [contract["numeric_scoring"]["direction_deadband_pp"], *contract["numeric_scoring"]["direction_deadband_sensitivity_pp"]]}
|
| 57 |
+
residuals = [f["arithmetic_residual"] for f in fields if f["arithmetic_residual"] is not None]
|
| 58 |
+
consistent = sum(f["arithmetic_consistent"] is True for f in fields)
|
| 59 |
+
record["arithmetic"] = {"n_applicable": len(fields), "n_parsed_triplets": len(residuals),
|
| 60 |
+
"consistent": consistent, "consistent_fraction_all": ratio(consistent, len(fields)),
|
| 61 |
+
"consistent_fraction_parsed": ratio(consistent, len(residuals)),
|
| 62 |
+
"mean_absolute_residual_pp": statistics.fmean(abs(v) for v in residuals) if residuals else None}
|
| 63 |
+
record["unscorable_assertions"] = sum(len(f["unscorable_assertions"]) for f in fields)
|
| 64 |
+
num[key] = record
|
| 65 |
+
panicle = {}
|
| 66 |
+
for role in ("source", "target"):
|
| 67 |
+
fields = [r["numeric"]["panicle"] for r in rows if r["numeric"]["panicle"]["reference"][role] is not None]
|
| 68 |
+
panicle[role] = classification([f["reference"][role] for f in fields], [f["prediction"][role] for f in fields], [0, 1])
|
| 69 |
+
panicle[role]["positive_class"] = panicle[role]["per_class"][1]
|
| 70 |
+
valid = [r["numeric"]["panicle"] for r in rows if r["numeric"]["panicle"]["reference"]["derived_change"] is not None]
|
| 71 |
+
def label(f: dict[str, Any], side: str) -> str | None:
|
| 72 |
+
a, b = f[side]["source"], f[side]["target"]
|
| 73 |
+
return f"{int(a)}_to_{int(b)}" if a is not None and b is not None else None
|
| 74 |
+
truth, prediction = [label(f, "reference") for f in valid], [label(f, "prediction") for f in valid]
|
| 75 |
+
panicle["transition"] = classification(truth, prediction, ["0_to_0", "0_to_1", "1_to_1"])
|
| 76 |
+
panicle["transition"]["reverse_count"] = prediction.count("1_to_0")
|
| 77 |
+
panicle["emergence"] = classification([int(t == "0_to_1") for t in truth], [int(p == "0_to_1") if p is not None else None for p in prediction], [0, 1])
|
| 78 |
+
panicle["emergence"]["positive_class"] = panicle["emergence"]["per_class"][1]
|
| 79 |
+
panicle["arithmetic"] = {"n_applicable": len(rows), "n_parsed_triplets": sum(r["numeric"]["panicle"]["arithmetic_residual"] is not None for r in rows),
|
| 80 |
+
"consistent": sum(r["numeric"]["panicle"]["arithmetic_consistent"] is True for r in rows)}
|
| 81 |
+
expected_points = sum(sum(len(v) for v in r["parsed"]["qualitative"].values()) for r in rows)
|
| 82 |
+
covered_points = sum(sum(bool(text) for text in fields.values()) for r in rows for fields in r["parsed"]["qualitative"].values())
|
| 83 |
+
return {"rows": len(rows), "plants": len({r["plant_id"] for r in rows}),
|
| 84 |
+
"structure": {"strict_valid": sum(r["strict_structure_valid"] for r in rows),
|
| 85 |
+
"strict_valid_rate": ratio(sum(r["strict_structure_valid"] for r in rows), len(rows)),
|
| 86 |
+
"expected_qualitative_points": expected_points, "covered_qualitative_points": covered_points,
|
| 87 |
+
"point_coverage": ratio(covered_points, expected_points),
|
| 88 |
+
"issue_counts": dict(Counter(i for r in rows for i in r["issues"]))},
|
| 89 |
+
"stages": stage, "numeric": num, "panicle": panicle}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def consistency(rows: list[dict[str, Any]], stages: list[str]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
| 93 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 94 |
+
sources: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 95 |
+
flags = []
|
| 96 |
+
for r in rows:
|
| 97 |
+
groups[r["pair_group_id"]].append(r)
|
| 98 |
+
sources[r["source_path"]].append(r)
|
| 99 |
+
# These deliberately narrow rules flag candidates, not proven factual errors.
|
| 100 |
+
for key, field in r["numeric"].items():
|
| 101 |
+
if key not in {"culm", "leaves_area", "yellow_brown_fraction"}:
|
| 102 |
+
continue
|
| 103 |
+
delta = field["prediction"]["derived_change"]
|
| 104 |
+
if delta is None or abs(delta) <= 1:
|
| 105 |
+
continue
|
| 106 |
+
text = r["parsed"]["qualitative"]["Target phenotype"].get(key) or ""
|
| 107 |
+
directions = explicit_metric_direction(text, key)
|
| 108 |
+
if ("increase" in directions and delta < -1) or ("decrease" in directions and delta > 1):
|
| 109 |
+
flags.append({"request_id": r["request_id"], "field": key, "text": text, "derived_change": delta,
|
| 110 |
+
"kind": "explicit_direction_candidate", "status": "automatic_flag_unconfirmed"})
|
| 111 |
+
cross = {}
|
| 112 |
+
for role in ("current", "future", "panicle_source", "panicle_target"):
|
| 113 |
+
counts = Counter()
|
| 114 |
+
for group in groups.values():
|
| 115 |
+
if len(group) != 2 or {r["view"] for r in group} != {"front", "top"}:
|
| 116 |
+
raise ValueError("invalid paired-view group")
|
| 117 |
+
if role.startswith("panicle_"):
|
| 118 |
+
endpoint = role.split("_", 1)[1]
|
| 119 |
+
ps = [r["numeric"]["panicle"]["prediction"][endpoint] for r in group]
|
| 120 |
+
ys = [r["numeric"]["panicle"]["reference"][endpoint] for r in group]
|
| 121 |
+
else:
|
| 122 |
+
ps = [r["parsed"]["stages"][role] for r in group]
|
| 123 |
+
ys = [r["source_stage" if role == "current" else "target_stage"] for r in group]
|
| 124 |
+
if any(y is None for y in ys):
|
| 125 |
+
counts["reference_unavailable"] += 1
|
| 126 |
+
continue
|
| 127 |
+
if ys[0] != ys[1]:
|
| 128 |
+
raise ValueError("paired reference labels differ")
|
| 129 |
+
if any(p is None for p in ps):
|
| 130 |
+
counts["missing_prediction"] += 1
|
| 131 |
+
continue
|
| 132 |
+
counts["both_parsed"] += 1
|
| 133 |
+
counts["agree"] += int(ps[0] == ps[1])
|
| 134 |
+
counts["both_correct"] += int(all(p == y for p, y in zip(ps, ys)))
|
| 135 |
+
counts["agree_both_wrong"] += int(ps[0] == ps[1] and ps[0] != ys[0])
|
| 136 |
+
counts["only_one_correct"] += int(sum(p == y for p, y in zip(ps, ys)) == 1)
|
| 137 |
+
denominator = len(groups) - counts["reference_unavailable"]
|
| 138 |
+
cross[role] = {**counts, "n_reference_groups": denominator,
|
| 139 |
+
"agreement_rate_all": ratio(counts["agree"], denominator),
|
| 140 |
+
"agreement_rate_parsed": ratio(counts["agree"], counts["both_parsed"])}
|
| 141 |
+
repeated = [values for values in sources.values() if len(values) > 1]
|
| 142 |
+
source_diagnostics = []
|
| 143 |
+
for group in repeated:
|
| 144 |
+
current = [r["parsed"]["stages"]["current"] for r in group]
|
| 145 |
+
values = {"source_path": group[0]["source_path"], "plant_id": group[0]["plant_id"], "view": group[0]["view"],
|
| 146 |
+
"n_predictions": len(group), "stage_missing": sum(v is None for v in current),
|
| 147 |
+
"stage_disagreement": len({v for v in current if v is not None}) > 1, "numeric": {}}
|
| 148 |
+
for key in group[0]["numeric"]:
|
| 149 |
+
nums = [r["numeric"][key]["prediction"]["source"] for r in group]
|
| 150 |
+
valid = [v for v in nums if v is not None]
|
| 151 |
+
values["numeric"][key] = {"n_parsed": len(valid), "range": max(valid)-min(valid) if len(valid)>1 else None,
|
| 152 |
+
"std": statistics.pstdev(valid) if len(valid)>1 else None}
|
| 153 |
+
source_diagnostics.append(values)
|
| 154 |
+
dedup_numeric = {}
|
| 155 |
+
for key in sorted({key for r in rows for key in r["numeric"] if key != "panicle"}):
|
| 156 |
+
errors, coverages = [], []
|
| 157 |
+
for group in sources.values():
|
| 158 |
+
if key not in group[0]["numeric"] or group[0]["numeric"][key]["reference"]["source"] is None:
|
| 159 |
+
continue
|
| 160 |
+
vals = [abs(r["numeric"][key]["prediction"]["source"]-r["numeric"][key]["reference"]["source"])
|
| 161 |
+
for r in group if r["numeric"][key]["prediction"]["source"] is not None]
|
| 162 |
+
coverages.append(len(vals)/len(group))
|
| 163 |
+
if vals:
|
| 164 |
+
errors.append(statistics.fmean(vals))
|
| 165 |
+
dedup_numeric[key] = {"source_weighted_mae_pp": statistics.fmean(errors) if errors else None,
|
| 166 |
+
"source_weighted_coverage": statistics.fmean(coverages) if coverages else None,
|
| 167 |
+
"n_reference_sources": len(coverages), "n_sources_with_parsed_predictions": len(errors)}
|
| 168 |
+
unique_stage = classification([r["source_stage"] for r in rows], [r["parsed"]["stages"]["current"] for r in rows], stages,
|
| 169 |
+
weights=[1 / len(sources[r["source_path"]]) for r in rows])
|
| 170 |
+
return {"cross_view": cross, "unique_source_images": len(sources), "repeated_source_groups": len(repeated),
|
| 171 |
+
"repeated_stage_disagreement_groups": sum(r["stage_disagreement"] for r in source_diagnostics),
|
| 172 |
+
"repeated_stage_disagreement_rate": ratio(sum(r["stage_disagreement"] for r in source_diagnostics), len(repeated)),
|
| 173 |
+
"repeated_groups_with_missing_stage": sum(r["stage_missing"] > 0 for r in source_diagnostics),
|
| 174 |
+
"source_weighted_current_stage": unique_stage, "source_weighted_numeric": dedup_numeric,
|
| 175 |
+
"repeated_source_details": source_diagnostics, "automatic_text_numeric_flags": len(flags),
|
| 176 |
+
"flag_interpretation": "conservative automatic candidates; not human-verified contradictions"}, flags
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def flattened(summary: dict[str, Any]) -> dict[str, Any]:
|
| 180 |
+
record = {"n_rows": summary["rows"], "n_plants": summary["plants"],
|
| 181 |
+
"strict_structure_rate": summary["structure"]["strict_valid_rate"]}
|
| 182 |
+
for role in ("current", "future"):
|
| 183 |
+
for field in ("accuracy", "macro_f1", "coverage", "ordinal_mae", "signed_stage_bias"):
|
| 184 |
+
record[f"stage_{role}_{field}"] = summary["stages"][role][field]
|
| 185 |
+
for key, fields in summary["numeric"].items():
|
| 186 |
+
for role in ("source", "target", "declared_change", "derived_change"):
|
| 187 |
+
for metric in ("mae", "coverage", "n_reference", "signed_bias"):
|
| 188 |
+
record[f"{key}_{role}_{metric}"] = fields[role][metric]
|
| 189 |
+
for role in ("source", "target", "emergence"):
|
| 190 |
+
record[f"panicle_{role}_accuracy"] = summary["panicle"][role]["accuracy"]
|
| 191 |
+
record[f"panicle_{role}_positive_f1"] = summary["panicle"][role]["positive_class"]["f1"]
|
| 192 |
+
return record
|
src/wgsr_v9/cot_evaluation/semantic.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local BGE scoring of aligned qualitative fields, with a resumable text cache."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import statistics
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
from ..evaluation_io import sha256_file, write_json_atomic
|
| 14 |
+
from .reference import text_hash
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def score_semantics(rows: list[dict[str, Any]], config: dict[str, Any], output: Path,
|
| 18 |
+
*, device: str, batch_size: int) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import AutoModel, AutoTokenizer
|
| 21 |
+
|
| 22 |
+
model_path = Path(config["local_path"])
|
| 23 |
+
if not model_path.is_dir():
|
| 24 |
+
raise FileNotFoundError(f"semantic model must be prepared explicitly: {model_path}")
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
|
| 26 |
+
max_tokens = config["max_tokens"]
|
| 27 |
+
pairs, unique = [], {}
|
| 28 |
+
for row in rows:
|
| 29 |
+
for section, fields in row["teacher_parsed"]["qualitative"].items():
|
| 30 |
+
for key, reference in fields.items():
|
| 31 |
+
predicted = row["parsed"]["qualitative"][section][key]
|
| 32 |
+
assert reference
|
| 33 |
+
record = {"request_id": row["request_id"], "view": row["view"], "section": section,
|
| 34 |
+
"field": key, "prediction_text": predicted, "reference_text": reference,
|
| 35 |
+
"status": "matched" if predicted else "missing_prediction", "cosine": None}
|
| 36 |
+
pairs.append(record)
|
| 37 |
+
for text in (reference, predicted):
|
| 38 |
+
if text:
|
| 39 |
+
unique[text_hash(text)] = text
|
| 40 |
+
keys = sorted(unique)
|
| 41 |
+
texts = [unique[key] for key in keys]
|
| 42 |
+
# Length auditing is separate from the actual truncated embedding call.
|
| 43 |
+
lengths = [len(tokenizer(text, truncation=False, verbose=False)["input_ids"]) for text in texts]
|
| 44 |
+
files = {str(p.relative_to(model_path)): sha256_file(p) for p in sorted(model_path.iterdir()) if p.is_file() and p.suffix in {".json", ".txt", ".safetensors", ".bin"}}
|
| 45 |
+
identity = {"model_id": config["model_id"], "revision": config["revision"], "model_files": files,
|
| 46 |
+
"text_hashes": keys, "max_tokens": max_tokens, "pooling": config["pooling"],
|
| 47 |
+
"dtype": "float32", "device_type": device.split(":")[0], "batch_size": batch_size}
|
| 48 |
+
cache = output / "semantic_embeddings.npz"
|
| 49 |
+
cache_identity = output / "semantic_cache_identity.json"
|
| 50 |
+
if cache.is_file() and cache_identity.is_file() and json.loads(cache_identity.read_text()) == identity:
|
| 51 |
+
with np.load(cache) as loaded:
|
| 52 |
+
vectors = loaded["embeddings"]
|
| 53 |
+
print(f"Semantic cache reused: {len(texts)} unique points", flush=True)
|
| 54 |
+
else:
|
| 55 |
+
model = AutoModel.from_pretrained(model_path, local_files_only=True).to(device).eval()
|
| 56 |
+
chunks = []
|
| 57 |
+
for start in range(0, len(texts), batch_size):
|
| 58 |
+
tokens = tokenizer(texts[start:start+batch_size], padding=True, truncation=True,
|
| 59 |
+
max_length=max_tokens, return_tensors="pt").to(device)
|
| 60 |
+
with torch.inference_mode():
|
| 61 |
+
vector = model(**tokens).last_hidden_state[:, 0]
|
| 62 |
+
vector = torch.nn.functional.normalize(vector.float(), dim=-1)
|
| 63 |
+
chunks.append(vector.cpu().numpy())
|
| 64 |
+
if start % (batch_size*20) == 0 or start+batch_size >= len(texts):
|
| 65 |
+
print(f"Semantic encoded {min(start+batch_size,len(texts))}/{len(texts)}", flush=True)
|
| 66 |
+
vectors = np.concatenate(chunks)
|
| 67 |
+
temporary = cache.with_name(f".{cache.name}.{os.getpid()}.tmp")
|
| 68 |
+
with temporary.open("wb") as handle:
|
| 69 |
+
np.savez_compressed(handle, embeddings=vectors)
|
| 70 |
+
os.replace(temporary, cache)
|
| 71 |
+
write_json_atomic(cache_identity, identity)
|
| 72 |
+
del model
|
| 73 |
+
if device.startswith("cuda"):
|
| 74 |
+
torch.cuda.empty_cache()
|
| 75 |
+
if vectors.shape[0] != len(keys) or not np.isfinite(vectors).all() or not np.allclose(np.linalg.norm(vectors, axis=1), 1, atol=1e-5):
|
| 76 |
+
raise ValueError("invalid semantic embedding cache")
|
| 77 |
+
lookup = dict(zip(keys, vectors))
|
| 78 |
+
for pair in pairs:
|
| 79 |
+
if pair["prediction_text"]:
|
| 80 |
+
cosine = float(np.dot(lookup[text_hash(pair["prediction_text"])], lookup[text_hash(pair["reference_text"])]))
|
| 81 |
+
pair["cosine"] = max(-1.0, min(1.0, cosine))
|
| 82 |
+
def aggregate(items: list[dict[str, Any]]) -> dict[str, Any]:
|
| 83 |
+
values = [p["cosine"] for p in items if p["cosine"] is not None]
|
| 84 |
+
return {"expected_points": len(items), "matched_points": len(values), "point_coverage": len(values)/len(items),
|
| 85 |
+
"mean_cosine_on_matched": statistics.fmean(values) if values else None,
|
| 86 |
+
"coverage_adjusted_cosine": sum(max(0, v) for v in values)/len(items)}
|
| 87 |
+
groups = defaultdict(list)
|
| 88 |
+
for pair in pairs:
|
| 89 |
+
groups[(pair["view"], pair["section"], pair["field"])].append(pair)
|
| 90 |
+
summary = {**aggregate(pairs), "by_field": [{"view": key[0], "section": key[1], "field": key[2], **aggregate(values)} for key, values in groups.items()],
|
| 91 |
+
"model_id": config["model_id"], "revision": config["revision"], "local_path": str(model_path),
|
| 92 |
+
"model_files": files, "unique_texts": len(texts), "truncated_unique_texts": sum(n>max_tokens for n in lengths),
|
| 93 |
+
"max_observed_tokens": max(lengths), "max_tokens": max_tokens, "dtype": "float32", "device": device,
|
| 94 |
+
"batch_size": batch_size, "pooling": "CLS + L2 normalization; no query instruction",
|
| 95 |
+
"teacher_self_similarity_max_error": float(np.max(np.abs(np.sum(vectors*vectors, axis=1)-1))),
|
| 96 |
+
"interpretation": "qualitative reference agreement, not factual correctness", "human_evaluation": "excluded_by_user"}
|
| 97 |
+
return summary, pairs
|
src/wgsr_v9/cot_evaluation/uncertainty.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plant-cluster bootstrap, including recomputed non-linear F1 statistics."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from .metrics import direction
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def bootstrap(rows: list[dict[str, Any]], stages: list[str], *, replicates: int, seed: int) -> list[dict[str, Any]]:
|
| 12 |
+
plants = sorted({r["plant_id"] for r in rows})
|
| 13 |
+
plant_index = {plant: i for i, plant in enumerate(plants)}
|
| 14 |
+
row_plant = np.array([plant_index[r["plant_id"]] for r in rows])
|
| 15 |
+
draws = np.random.default_rng(seed).integers(0, len(plants), size=(replicates, len(plants)))
|
| 16 |
+
weights = np.zeros((replicates, len(plants)), dtype=np.int16)
|
| 17 |
+
for i in range(len(plants)):
|
| 18 |
+
weights += (draws == i).sum(axis=1)[:, None] * np.eye(len(plants), dtype=np.int16)[i]
|
| 19 |
+
weights = weights.astype(np.float64)
|
| 20 |
+
reports = []
|
| 21 |
+
|
| 22 |
+
def save(name: str, estimate: float | None, values: np.ndarray, n: int, details: dict[str, Any] | None = None) -> None:
|
| 23 |
+
valid = values[np.isfinite(values)]
|
| 24 |
+
reports.append({"metric": name, "estimate": estimate, "n": n, "plant_clusters": len(plants),
|
| 25 |
+
"ci95_lower": float(np.quantile(valid, .025)) if len(valid) else None,
|
| 26 |
+
"ci95_upper": float(np.quantile(valid, .975)) if len(valid) else None,
|
| 27 |
+
"valid_replicates": len(valid), "replicates": replicates, "seed": seed,
|
| 28 |
+
"unit": "plant_id", **(details or {})})
|
| 29 |
+
|
| 30 |
+
def mean_ci(name: str, values: list[float | None]) -> None:
|
| 31 |
+
array = np.array([np.nan if v is None else v for v in values])
|
| 32 |
+
valid = np.isfinite(array)
|
| 33 |
+
sums = np.bincount(row_plant[valid], weights=array[valid], minlength=len(plants))
|
| 34 |
+
counts = np.bincount(row_plant[valid], minlength=len(plants))
|
| 35 |
+
numerator, denominator = weights @ sums, weights @ counts
|
| 36 |
+
estimates = np.divide(numerator, denominator, out=np.full(replicates, np.nan), where=denominator != 0)
|
| 37 |
+
save(name, float(array[valid].mean()) if valid.any() else None, estimates, int(valid.sum()))
|
| 38 |
+
|
| 39 |
+
def class_ci(name: str, truth: list[Any], prediction: list[Any], labels: list[Any], *, positive_only: bool = False) -> None:
|
| 40 |
+
size = len(labels)
|
| 41 |
+
counts = np.zeros((len(plants), size, size + 1), dtype=np.float64)
|
| 42 |
+
eligible = 0
|
| 43 |
+
for i, (y, p) in enumerate(zip(truth, prediction)):
|
| 44 |
+
if y is None:
|
| 45 |
+
continue
|
| 46 |
+
counts[row_plant[i], labels.index(y), labels.index(p) if p in labels else size] += 1
|
| 47 |
+
eligible += 1
|
| 48 |
+
matrix = (weights @ counts.reshape(len(plants), -1)).reshape(replicates, size, size+1)
|
| 49 |
+
all_matrix = counts.sum(axis=0)[None]
|
| 50 |
+
|
| 51 |
+
def calculate(mat: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 52 |
+
tp = np.diagonal(mat[:, :, :size], axis1=1, axis2=2)
|
| 53 |
+
support, predicted = mat.sum(axis=2), mat[:, :, :size].sum(axis=1)
|
| 54 |
+
f1 = np.divide(2*tp, support+predicted, out=np.zeros_like(tp), where=(support+predicted)>0)
|
| 55 |
+
denominator = mat.sum(axis=(1, 2))
|
| 56 |
+
accuracy = np.divide(tp.sum(axis=1), denominator, out=np.full(len(mat), np.nan), where=denominator>0)
|
| 57 |
+
score = f1[:, -1] if positive_only else f1.mean(axis=1)
|
| 58 |
+
score[denominator == 0] = np.nan
|
| 59 |
+
return accuracy, score
|
| 60 |
+
acc, f1 = calculate(matrix)
|
| 61 |
+
original_acc, original_f1 = calculate(all_matrix)
|
| 62 |
+
save(f"{name}.accuracy", float(original_acc[0]) if eligible else None, acc, eligible)
|
| 63 |
+
save(f"{name}.{'positive_f1' if positive_only else 'macro_f1'}", float(original_f1[0]) if eligible else None, f1, eligible)
|
| 64 |
+
|
| 65 |
+
mean_ci("structure.strict_valid_rate", [float(r["strict_structure_valid"]) for r in rows])
|
| 66 |
+
for role, reference in (("current", "source_stage"), ("future", "target_stage")):
|
| 67 |
+
class_ci(f"stage.{role}", [r[reference] for r in rows], [r["parsed"]["stages"][role] for r in rows], stages)
|
| 68 |
+
for key in sorted({key for r in rows for key in r["numeric"] if key != "panicle"}):
|
| 69 |
+
for role in ("source", "target", "declared_change", "derived_change"):
|
| 70 |
+
errors, within2 = [], []
|
| 71 |
+
ys, ps = [], []
|
| 72 |
+
for row in rows:
|
| 73 |
+
f = row["numeric"].get(key)
|
| 74 |
+
y = f["reference"][role] if f else None
|
| 75 |
+
p = f["prediction"][role] if f else None
|
| 76 |
+
e = abs(p-y) if p is not None and y is not None else None
|
| 77 |
+
errors.append(e)
|
| 78 |
+
within2.append(float(e is not None and e <= 2+1e-10) if y is not None else None)
|
| 79 |
+
ys.append(direction(y, 1) if y is not None else None)
|
| 80 |
+
ps.append(direction(p, 1) if p is not None else None)
|
| 81 |
+
mean_ci(f"{key}.{role}.mae", errors)
|
| 82 |
+
mean_ci(f"{key}.{role}.accuracy_within_2pp", within2)
|
| 83 |
+
if role in {"declared_change", "derived_change"}:
|
| 84 |
+
class_ci(f"{key}.{role}.direction", ys, ps, ["decrease", "stable", "increase"])
|
| 85 |
+
for role in ("source", "target", "emergence"):
|
| 86 |
+
ys, ps = [], []
|
| 87 |
+
for row in rows:
|
| 88 |
+
field = row["numeric"]["panicle"]
|
| 89 |
+
endpoint = "derived_change" if role == "emergence" else role
|
| 90 |
+
y, p = field["reference"][endpoint], field["prediction"][endpoint]
|
| 91 |
+
ys.append(None if y is None else int(y == 1))
|
| 92 |
+
ps.append(None if p is None else int(p == 1))
|
| 93 |
+
class_ci(f"panicle.{role}", ys, ps, [0, 1], positive_only=True)
|
| 94 |
+
return reports
|
src/wgsr_v9/diffsynth_batching.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Homogeneous cached batching for Qwen Image 2.1 DiffSynth full-DiT SFT.
|
| 2 |
+
|
| 3 |
+
The Qwen Image 2.1 text encoder returns a different sequence length for every
|
| 4 |
+
prompt. A cache therefore cannot use the full prompt length as a batching
|
| 5 |
+
key: doing so creates many tiny buckets and repeats samples at every bucket
|
| 6 |
+
boundary. Image geometry and the positions of image tokens must remain
|
| 7 |
+
homogeneous, while text tokens can be padded at the end of a batch and
|
| 8 |
+
masked with ``prompt_embeds_mask``.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
import hashlib
|
| 15 |
+
import math
|
| 16 |
+
import random
|
| 17 |
+
from typing import Any, Hashable, Iterable, Iterator
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def layout_key(inputs: tuple[dict[str, Any], dict[str, Any], dict[str, Any]]) -> tuple[Hashable, ...]:
|
| 23 |
+
shared, positive, _negative = inputs
|
| 24 |
+
if positive.get("prompt_embeds_mask") is not None:
|
| 25 |
+
raise ValueError("Only unpadded cached prompt layouts are supported")
|
| 26 |
+
mask = positive["edit_image_pad_mask"].detach().cpu().contiguous()
|
| 27 |
+
return (
|
| 28 |
+
tuple(shared["input_latents"].shape[1:]),
|
| 29 |
+
tuple(tuple(latent.shape[1:]) for latent in shared.get("edit_latents") or []),
|
| 30 |
+
tuple(positive["prompt_embeds"].shape[1:]),
|
| 31 |
+
hashlib.sha256(mask.numpy().tobytes()).hexdigest(),
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def batch_layout_key(inputs: tuple[dict[str, Any], dict[str, Any], dict[str, Any]]) -> tuple[Hashable, ...]:
|
| 36 |
+
"""Return the layout that must be shared by all rows in a microbatch.
|
| 37 |
+
|
| 38 |
+
Prompt length is deliberately excluded. Qwen's image token positions are
|
| 39 |
+
still included, because ``QwenImage21DiT`` receives one shared image mask
|
| 40 |
+
for a whole batch. The full mask is not stored in the key; a digest of its
|
| 41 |
+
true positions keeps the index compact while ``collate_cached`` performs a
|
| 42 |
+
second exact check before concatenating tensors.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
shared, positive, _negative = inputs
|
| 46 |
+
mask = positive["edit_image_pad_mask"].detach().cpu().contiguous()
|
| 47 |
+
if mask.ndim != 2 or mask.shape[0] != 1:
|
| 48 |
+
raise ValueError(f"expected edit_image_pad_mask with shape (1, sequence), got {tuple(mask.shape)}")
|
| 49 |
+
image_positions = mask[0].nonzero(as_tuple=True)[0].numpy()
|
| 50 |
+
position_digest = hashlib.sha256(image_positions.tobytes()).hexdigest()
|
| 51 |
+
return (
|
| 52 |
+
tuple(shared["input_latents"].shape[1:]),
|
| 53 |
+
tuple(tuple(latent.shape[1:]) for latent in shared.get("edit_latents") or []),
|
| 54 |
+
int(image_positions.size),
|
| 55 |
+
position_digest,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _pad_prompt_embeds(prompt_embeds: torch.Tensor, length: int) -> torch.Tensor:
|
| 60 |
+
if prompt_embeds.ndim != 3 or prompt_embeds.shape[0] != 1:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"cached prompt_embeds must have shape (1, sequence, hidden), "
|
| 63 |
+
f"got {tuple(prompt_embeds.shape)}"
|
| 64 |
+
)
|
| 65 |
+
padding = length - prompt_embeds.shape[1]
|
| 66 |
+
if padding < 0:
|
| 67 |
+
raise ValueError("cannot pad prompt embeddings to a shorter sequence")
|
| 68 |
+
if padding == 0:
|
| 69 |
+
return prompt_embeds
|
| 70 |
+
return torch.cat(
|
| 71 |
+
[prompt_embeds, prompt_embeds.new_zeros((1, padding, prompt_embeds.shape[2]))],
|
| 72 |
+
dim=1,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _pad_mask(mask: torch.Tensor, length: int, *, name: str) -> torch.Tensor:
|
| 77 |
+
if mask.ndim != 2 or mask.shape[0] != 1:
|
| 78 |
+
raise ValueError(f"cached {name} must have shape (1, sequence), got {tuple(mask.shape)}")
|
| 79 |
+
padding = length - mask.shape[1]
|
| 80 |
+
if padding < 0:
|
| 81 |
+
raise ValueError(f"cannot pad {name} to a shorter sequence")
|
| 82 |
+
if padding == 0:
|
| 83 |
+
return mask
|
| 84 |
+
return torch.cat([mask, mask.new_zeros((1, padding))], dim=1)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def collate_cached(
|
| 88 |
+
rows: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]],
|
| 89 |
+
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
| 90 |
+
if not rows:
|
| 91 |
+
raise ValueError("Cannot collate an empty batch")
|
| 92 |
+
key = batch_layout_key(rows[0])
|
| 93 |
+
if any(batch_layout_key(row) != key for row in rows[1:]):
|
| 94 |
+
raise ValueError("Cannot mix different geometry or image-token layout in one batch")
|
| 95 |
+
prompt_lengths = [row[1]["prompt_embeds"].shape[1] for row in rows]
|
| 96 |
+
max_prompt_length = max(prompt_lengths)
|
| 97 |
+
reference_image_positions = rows[0][1]["edit_image_pad_mask"][0].nonzero(as_tuple=True)[0]
|
| 98 |
+
padded_image_masks: list[torch.Tensor] = []
|
| 99 |
+
padded_prompt_masks: list[torch.Tensor] = []
|
| 100 |
+
for row, prompt_length in zip(rows, prompt_lengths):
|
| 101 |
+
positive_row = row[1]
|
| 102 |
+
image_mask = positive_row["edit_image_pad_mask"]
|
| 103 |
+
image_positions = image_mask[0].nonzero(as_tuple=True)[0]
|
| 104 |
+
if not torch.equal(image_positions, reference_image_positions):
|
| 105 |
+
raise ValueError("Cannot mix rows with different image-token positions in one batch")
|
| 106 |
+
if image_mask.shape[1] != prompt_length:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
"prompt_embeds and edit_image_pad_mask must have the same sequence length, "
|
| 109 |
+
f"got {prompt_length} and {image_mask.shape[1]}"
|
| 110 |
+
)
|
| 111 |
+
prompt_mask = positive_row.get("prompt_embeds_mask")
|
| 112 |
+
if prompt_mask is None:
|
| 113 |
+
prompt_mask = torch.ones(
|
| 114 |
+
(1, prompt_length), dtype=torch.bool, device=positive_row["prompt_embeds"].device
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
prompt_mask = prompt_mask.bool()
|
| 118 |
+
if prompt_mask.shape[1] != prompt_length:
|
| 119 |
+
raise ValueError(
|
| 120 |
+
"prompt_embeds_mask and prompt_embeds must have the same sequence length, "
|
| 121 |
+
f"got {prompt_mask.shape[1]} and {prompt_length}"
|
| 122 |
+
)
|
| 123 |
+
padded_image_masks.append(_pad_mask(image_mask, max_prompt_length, name="edit_image_pad_mask"))
|
| 124 |
+
padded_prompt_masks.append(_pad_mask(prompt_mask, max_prompt_length, name="prompt_embeds_mask"))
|
| 125 |
+
shared, positive, negative = (dict(part) for part in rows[0])
|
| 126 |
+
shared["input_latents"] = torch.cat([row[0]["input_latents"] for row in rows], dim=0)
|
| 127 |
+
shared["edit_latents"] = [
|
| 128 |
+
torch.cat([row[0]["edit_latents"][index] for row in rows], dim=0)
|
| 129 |
+
for index in range(len(rows[0][0].get("edit_latents") or []))
|
| 130 |
+
] or None
|
| 131 |
+
positive["prompt_embeds"] = torch.cat(
|
| 132 |
+
[_pad_prompt_embeds(row[1]["prompt_embeds"], max_prompt_length) for row in rows], dim=0
|
| 133 |
+
)
|
| 134 |
+
# The upstream Qwen Image 2.1 DiT reads one shared image-layout mask.
|
| 135 |
+
positive["edit_image_pad_mask"] = padded_image_masks[0]
|
| 136 |
+
prompt_embeds_mask = torch.cat(padded_prompt_masks, dim=0)
|
| 137 |
+
# Preserve the compact ``None`` representation when no padding is needed.
|
| 138 |
+
positive["prompt_embeds_mask"] = None if bool(prompt_embeds_mask.all()) else prompt_embeds_mask
|
| 139 |
+
numeric_keys = ("numeric_features", "numeric_mask", "numeric_view")
|
| 140 |
+
if any(any(key in row[1] for key in numeric_keys) for row in rows):
|
| 141 |
+
if not all(all(key in row[1] for key in numeric_keys) for row in rows):
|
| 142 |
+
raise ValueError("Cannot mix numeric and legacy cached rows or incomplete numeric conditions")
|
| 143 |
+
for key in numeric_keys:
|
| 144 |
+
positive[key] = torch.cat([row[1][key] for row in rows], dim=0)
|
| 145 |
+
for condition_key in ("condition_dropout", "condition_ablation"):
|
| 146 |
+
if not any(condition_key in row[0] for row in rows):
|
| 147 |
+
continue
|
| 148 |
+
labels = [row[0].get(condition_key) for row in rows]
|
| 149 |
+
if any(label is None for label in labels) or any(
|
| 150 |
+
any(label[key] != labels[0][key] for key in ("action", "epoch", "step")) for label in labels
|
| 151 |
+
):
|
| 152 |
+
raise ValueError("one batch must share one dropout action/epoch/step")
|
| 153 |
+
shared[condition_key] = {**labels[0], "request_ids": [
|
| 154 |
+
identifier for label in labels for identifier in label["request_ids"]]}
|
| 155 |
+
return shared, positive, negative
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class LayoutBatchSampler(torch.utils.data.Sampler[list[int]]):
|
| 159 |
+
"""Yield local microbatches with shared image/text layouts across ranks."""
|
| 160 |
+
|
| 161 |
+
def __init__(
|
| 162 |
+
self,
|
| 163 |
+
keys: Iterable[Hashable],
|
| 164 |
+
batch_size: int,
|
| 165 |
+
world_size: int,
|
| 166 |
+
*,
|
| 167 |
+
seed: int,
|
| 168 |
+
gradient_accumulation_steps: int,
|
| 169 |
+
) -> None:
|
| 170 |
+
if batch_size <= 0 or world_size <= 0 or gradient_accumulation_steps <= 0:
|
| 171 |
+
raise ValueError("batch size, world size, and accumulation steps must be positive")
|
| 172 |
+
self.batch_size = batch_size
|
| 173 |
+
self.world_size = world_size
|
| 174 |
+
self.seed = seed
|
| 175 |
+
self.gradient_accumulation_steps = gradient_accumulation_steps
|
| 176 |
+
self.epoch = 0
|
| 177 |
+
self.groups: dict[Hashable, list[int]] = defaultdict(list)
|
| 178 |
+
for index, key in enumerate(keys):
|
| 179 |
+
self.groups[key].append(index)
|
| 180 |
+
if not self.groups:
|
| 181 |
+
raise ValueError("layout sampler requires at least one sample")
|
| 182 |
+
|
| 183 |
+
def set_epoch(self, epoch: int) -> None:
|
| 184 |
+
self.epoch = epoch
|
| 185 |
+
|
| 186 |
+
def __len__(self) -> int:
|
| 187 |
+
global_batches = sum(
|
| 188 |
+
math.ceil(len(group) / (self.batch_size * self.world_size)) for group in self.groups.values()
|
| 189 |
+
)
|
| 190 |
+
global_batches = math.ceil(global_batches / self.gradient_accumulation_steps)
|
| 191 |
+
global_batches *= self.gradient_accumulation_steps
|
| 192 |
+
return global_batches * self.world_size
|
| 193 |
+
|
| 194 |
+
def __iter__(self) -> Iterator[list[int]]:
|
| 195 |
+
generator = random.Random(self.seed + self.epoch)
|
| 196 |
+
global_batches: list[list[int]] = []
|
| 197 |
+
global_batch_size = self.batch_size * self.world_size
|
| 198 |
+
for original in self.groups.values():
|
| 199 |
+
group = original.copy()
|
| 200 |
+
generator.shuffle(group)
|
| 201 |
+
padded_length = math.ceil(len(group) / global_batch_size) * global_batch_size
|
| 202 |
+
group.extend(group[index % len(original)] for index in range(padded_length - len(group)))
|
| 203 |
+
global_batches.extend(
|
| 204 |
+
group[start : start + global_batch_size]
|
| 205 |
+
for start in range(0, len(group), global_batch_size)
|
| 206 |
+
)
|
| 207 |
+
generator.shuffle(global_batches)
|
| 208 |
+
while len(global_batches) % self.gradient_accumulation_steps:
|
| 209 |
+
global_batches.append(global_batches[-1].copy())
|
| 210 |
+
for indices in global_batches:
|
| 211 |
+
for start in range(0, global_batch_size, self.batch_size):
|
| 212 |
+
yield indices[start : start + self.batch_size]
|
src/wgsr_v9/executor_cache_builder.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build a validated DiffSynth cache in bounded, compacted chunks.
|
| 3 |
+
|
| 4 |
+
The upstream Qwen Image 2.1 data processor writes large per-sample pickle
|
| 5 |
+
files. Running it over the full 20,000-row package can exceed local disk
|
| 6 |
+
capacity before compaction starts. This entry point processes contiguous
|
| 7 |
+
chunks, compacts each chunk in place, and moves the compact files into the
|
| 8 |
+
final distributed cache layout.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import errno
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import shutil
|
| 18 |
+
import subprocess
|
| 19 |
+
import sys
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 23 |
+
|
| 24 |
+
from wgsr_v9.executor_training import ALGORITHM_VERSION # noqa: E402
|
| 25 |
+
from wgsr_v9.io import read_jsonl, sha256_path, write_json, write_jsonl # noqa: E402
|
| 26 |
+
|
| 27 |
+
COMPACT_SCRIPT = REPO_ROOT / "scripts/compact_executor_caches.py"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _move_cache_file(source: Path, target: Path) -> None:
|
| 31 |
+
"""Move a compact cache file, including across the workspace/tmpfs boundary.
|
| 32 |
+
|
| 33 |
+
``Path.replace`` is atomic only when both paths are on the same filesystem.
|
| 34 |
+
The reviewed layout intentionally puts ranks 0--3 on ``/dev/shm`` and the
|
| 35 |
+
remaining ranks on the workspace filesystem, so those files need a
|
| 36 |
+
copy-then-remove fallback when a chunk crosses devices.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
source.replace(target)
|
| 41 |
+
except OSError as exc:
|
| 42 |
+
if exc.errno != errno.EXDEV:
|
| 43 |
+
raise
|
| 44 |
+
shutil.copy2(source, target)
|
| 45 |
+
if target.stat().st_size != source.stat().st_size:
|
| 46 |
+
target.unlink(missing_ok=True)
|
| 47 |
+
raise OSError(f"cross-device cache copy was truncated: {source} -> {target}")
|
| 48 |
+
source.unlink()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _chunk_ranges(count: int, chunk_size: int, world_size: int) -> list[tuple[int, int]]:
|
| 52 |
+
if count <= 0:
|
| 53 |
+
raise ValueError("metadata is empty")
|
| 54 |
+
if chunk_size < world_size or chunk_size % world_size:
|
| 55 |
+
raise ValueError("chunk size must be a multiple of world size and at least world size")
|
| 56 |
+
ranges: list[tuple[int, int]] = []
|
| 57 |
+
for start in range(0, count, chunk_size):
|
| 58 |
+
end = min(count, start + chunk_size)
|
| 59 |
+
if start % world_size or end % world_size:
|
| 60 |
+
raise ValueError("all chunk boundaries must align to distributed world size")
|
| 61 |
+
ranges.append((start, end))
|
| 62 |
+
return ranges
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _rank_files(root: Path, world_size: int) -> list[tuple[int, int, Path]]:
|
| 66 |
+
rank_dirs = sorted((path for path in root.iterdir() if path.is_dir() and path.name.isdigit()), key=lambda p: int(p.name))
|
| 67 |
+
ranks = [int(path.name) for path in rank_dirs]
|
| 68 |
+
if ranks != list(range(world_size)):
|
| 69 |
+
raise ValueError(f"chunk cache ranks must be 0..{world_size - 1}, found {ranks}")
|
| 70 |
+
records: list[tuple[int, int, Path]] = []
|
| 71 |
+
for rank_dir in rank_dirs:
|
| 72 |
+
for path in sorted(rank_dir.glob("*.pth"), key=lambda p: int(p.stem)):
|
| 73 |
+
if not path.stem.isdigit():
|
| 74 |
+
raise ValueError(f"chunk cache has nonnumeric file: {path}")
|
| 75 |
+
records.append((int(rank_dir.name), int(path.stem), path))
|
| 76 |
+
return records
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _run_cache_chunk(
|
| 80 |
+
*,
|
| 81 |
+
accelerate: Path,
|
| 82 |
+
accelerate_config: Path,
|
| 83 |
+
upstream_train: Path,
|
| 84 |
+
model_paths: str,
|
| 85 |
+
processor_path: Path,
|
| 86 |
+
metadata_path: Path,
|
| 87 |
+
output_path: Path,
|
| 88 |
+
max_pixels: int,
|
| 89 |
+
main_process_port: int,
|
| 90 |
+
environment: dict[str, str] | None,
|
| 91 |
+
) -> None:
|
| 92 |
+
command = [
|
| 93 |
+
str(accelerate),
|
| 94 |
+
"launch",
|
| 95 |
+
"--config_file",
|
| 96 |
+
str(accelerate_config),
|
| 97 |
+
"--main_process_port",
|
| 98 |
+
str(main_process_port),
|
| 99 |
+
str(upstream_train),
|
| 100 |
+
"--task",
|
| 101 |
+
"sft:data_process",
|
| 102 |
+
"--trainable_models",
|
| 103 |
+
"dit",
|
| 104 |
+
"--model_paths",
|
| 105 |
+
model_paths,
|
| 106 |
+
"--processor_path",
|
| 107 |
+
str(processor_path),
|
| 108 |
+
"--dataset_base_path",
|
| 109 |
+
"/",
|
| 110 |
+
"--dataset_metadata_path",
|
| 111 |
+
str(metadata_path),
|
| 112 |
+
"--data_file_keys",
|
| 113 |
+
"image,edit_image",
|
| 114 |
+
"--extra_inputs",
|
| 115 |
+
"edit_image",
|
| 116 |
+
"--max_pixels",
|
| 117 |
+
str(max_pixels),
|
| 118 |
+
"--dataset_repeat",
|
| 119 |
+
"1",
|
| 120 |
+
"--dataset_num_workers",
|
| 121 |
+
"0",
|
| 122 |
+
"--use_gradient_checkpointing",
|
| 123 |
+
"--output_path",
|
| 124 |
+
str(output_path),
|
| 125 |
+
]
|
| 126 |
+
subprocess.run(command, cwd=upstream_train.parents[3], env=environment, check=True)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _compact(python: Path, staging_root: Path, audit_path: Path, workers: int) -> dict[str, Any]:
|
| 130 |
+
command = [
|
| 131 |
+
str(python),
|
| 132 |
+
str(COMPACT_SCRIPT),
|
| 133 |
+
"--cache-root",
|
| 134 |
+
str(staging_root),
|
| 135 |
+
"--output",
|
| 136 |
+
str(audit_path),
|
| 137 |
+
"--workers",
|
| 138 |
+
str(workers),
|
| 139 |
+
]
|
| 140 |
+
subprocess.run(command, cwd=REPO_ROOT, check=True)
|
| 141 |
+
return json.loads(audit_path.read_text(encoding="utf-8"))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def build_cache(args: argparse.Namespace) -> dict[str, Any]:
|
| 145 |
+
metadata_path = args.metadata.resolve()
|
| 146 |
+
cache_root = args.cache_root.resolve()
|
| 147 |
+
if not metadata_path.is_file():
|
| 148 |
+
raise FileNotFoundError(metadata_path)
|
| 149 |
+
rows = read_jsonl(metadata_path)
|
| 150 |
+
ranges = _chunk_ranges(len(rows), args.chunk_size, args.world_size)
|
| 151 |
+
cache_root.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
chunks_root = cache_root / "_chunks"
|
| 153 |
+
chunks_root.mkdir(parents=True, exist_ok=True)
|
| 154 |
+
tmpfs_root = args.tmpfs_root.resolve() if args.tmpfs_root is not None else None
|
| 155 |
+
tmpfs_ranks = set(args.tmpfs_ranks)
|
| 156 |
+
if tmpfs_ranks and tmpfs_root is None:
|
| 157 |
+
raise ValueError("--tmpfs-root is required when --tmpfs-ranks is used")
|
| 158 |
+
if any(rank < 0 or rank >= args.world_size for rank in tmpfs_ranks):
|
| 159 |
+
raise ValueError("tmpfs rank is outside world size")
|
| 160 |
+
if tmpfs_root is not None:
|
| 161 |
+
tmpfs_root.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
final_rank_dirs: list[Path] = []
|
| 163 |
+
for rank in range(args.world_size):
|
| 164 |
+
if rank in tmpfs_ranks:
|
| 165 |
+
final_dir = tmpfs_root / str(rank)
|
| 166 |
+
link = cache_root / str(rank)
|
| 167 |
+
final_dir.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
if link.is_symlink():
|
| 169 |
+
if link.resolve() != final_dir.resolve():
|
| 170 |
+
raise FileExistsError(f"cache rank symlink points elsewhere: {link}")
|
| 171 |
+
elif link.exists():
|
| 172 |
+
if any(link.iterdir()):
|
| 173 |
+
raise FileExistsError(f"cache rank path is nonempty and not a symlink: {link}")
|
| 174 |
+
link.rmdir()
|
| 175 |
+
link.symlink_to(final_dir, target_is_directory=True)
|
| 176 |
+
else:
|
| 177 |
+
link.symlink_to(final_dir, target_is_directory=True)
|
| 178 |
+
else:
|
| 179 |
+
final_dir = cache_root / str(rank)
|
| 180 |
+
final_dir.mkdir(parents=True, exist_ok=True)
|
| 181 |
+
final_rank_dirs.append(final_dir)
|
| 182 |
+
|
| 183 |
+
all_files: list[dict[str, Any]] = []
|
| 184 |
+
chunk_reports: list[dict[str, Any]] = []
|
| 185 |
+
for chunk_number, (start, end) in enumerate(ranges):
|
| 186 |
+
chunk_tag = f"{start:06d}_{end:06d}"
|
| 187 |
+
chunk_manifest_path = chunks_root / f"chunk_{chunk_tag}.json"
|
| 188 |
+
staging_root = chunks_root / f"staging_{chunk_tag}"
|
| 189 |
+
chunk_metadata = chunks_root / f"metadata_{chunk_tag}.jsonl"
|
| 190 |
+
compaction_audit = chunks_root / f"compaction_{chunk_tag}.json"
|
| 191 |
+
if chunk_manifest_path.is_file():
|
| 192 |
+
report = json.loads(chunk_manifest_path.read_text(encoding="utf-8"))
|
| 193 |
+
if report.get("status") != "complete" or report.get("metadata_sha256") != sha256_path(metadata_path):
|
| 194 |
+
raise ValueError(f"chunk manifest is incomplete or stale: {chunk_manifest_path}")
|
| 195 |
+
chunk_reports.append(report)
|
| 196 |
+
all_files.extend(report.get("files", []))
|
| 197 |
+
continue
|
| 198 |
+
if staging_root.exists() and any(staging_root.iterdir()):
|
| 199 |
+
raise FileExistsError(f"incomplete staging directory requires a new cache root: {staging_root}")
|
| 200 |
+
if chunk_metadata.exists() or compaction_audit.exists():
|
| 201 |
+
raise FileExistsError(f"stale chunk intermediates require a new cache root: {chunks_root}")
|
| 202 |
+
staging_root.mkdir(parents=True, exist_ok=True)
|
| 203 |
+
write_jsonl(chunk_metadata, rows[start:end])
|
| 204 |
+
_run_cache_chunk(
|
| 205 |
+
accelerate=args.accelerate,
|
| 206 |
+
accelerate_config=args.accelerate_config,
|
| 207 |
+
upstream_train=args.upstream_train,
|
| 208 |
+
model_paths=args.model_paths,
|
| 209 |
+
processor_path=args.processor_path,
|
| 210 |
+
metadata_path=chunk_metadata,
|
| 211 |
+
output_path=staging_root,
|
| 212 |
+
max_pixels=args.max_pixels,
|
| 213 |
+
main_process_port=args.main_process_port,
|
| 214 |
+
environment=None,
|
| 215 |
+
)
|
| 216 |
+
records = _rank_files(staging_root, args.world_size)
|
| 217 |
+
expected_count = end - start
|
| 218 |
+
if len(records) != expected_count:
|
| 219 |
+
raise ValueError(f"chunk {chunk_tag} produced {len(records)} files; expected {expected_count}")
|
| 220 |
+
compact_report = _compact(args.python, staging_root, compaction_audit, args.compact_workers)
|
| 221 |
+
if compact_report.get("status") != "complete":
|
| 222 |
+
raise RuntimeError(f"chunk compaction failed: {compaction_audit}")
|
| 223 |
+
offset = start // args.world_size
|
| 224 |
+
moved_files: list[dict[str, Any]] = []
|
| 225 |
+
for rank, local_index, source_path in records:
|
| 226 |
+
target_path = final_rank_dirs[rank] / f"{offset + local_index}.pth"
|
| 227 |
+
if target_path.exists():
|
| 228 |
+
raise FileExistsError(f"final cache file already exists: {target_path}")
|
| 229 |
+
_move_cache_file(source_path, target_path)
|
| 230 |
+
moved_files.append(
|
| 231 |
+
{
|
| 232 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 233 |
+
"input_path": str((metadata_path).resolve()),
|
| 234 |
+
"output_path": str(target_path.resolve()),
|
| 235 |
+
"rank": rank,
|
| 236 |
+
"rank_local_index": offset + local_index,
|
| 237 |
+
"chunk_start": start,
|
| 238 |
+
"chunk_end": end,
|
| 239 |
+
"status": "ready",
|
| 240 |
+
"error": None,
|
| 241 |
+
"retry_count": 0,
|
| 242 |
+
"bytes": target_path.stat().st_size,
|
| 243 |
+
}
|
| 244 |
+
)
|
| 245 |
+
for rank_dir in sorted((path for path in staging_root.iterdir() if path.is_dir()), key=lambda p: p.name):
|
| 246 |
+
rank_dir.rmdir()
|
| 247 |
+
staging_root.rmdir()
|
| 248 |
+
report = {
|
| 249 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 250 |
+
"input_path": str(metadata_path),
|
| 251 |
+
"output_path": str(cache_root),
|
| 252 |
+
"metadata_sha256": sha256_path(metadata_path),
|
| 253 |
+
"chunk_start": start,
|
| 254 |
+
"chunk_end": end,
|
| 255 |
+
"count": expected_count,
|
| 256 |
+
"files": moved_files,
|
| 257 |
+
"status": "complete",
|
| 258 |
+
"error": None,
|
| 259 |
+
"retry_count": 0,
|
| 260 |
+
}
|
| 261 |
+
write_json(chunk_manifest_path, report)
|
| 262 |
+
chunk_reports.append(report)
|
| 263 |
+
all_files.extend(moved_files)
|
| 264 |
+
|
| 265 |
+
all_files.sort(key=lambda item: (int(item["rank"]), int(item["rank_local_index"])))
|
| 266 |
+
if len(all_files) != len(rows):
|
| 267 |
+
raise ValueError(f"final cache file count {len(all_files)} does not match metadata count {len(rows)}")
|
| 268 |
+
final_audit = {
|
| 269 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 270 |
+
"input_path": str(metadata_path),
|
| 271 |
+
"output_path": str(args.output_audit.resolve()),
|
| 272 |
+
"cache_root": str(cache_root),
|
| 273 |
+
"metadata_sha256": sha256_path(metadata_path),
|
| 274 |
+
"world_size": args.world_size,
|
| 275 |
+
"count": len(all_files),
|
| 276 |
+
"completed_count": len(all_files),
|
| 277 |
+
"failed_count": 0,
|
| 278 |
+
"before_bytes": None,
|
| 279 |
+
"after_bytes": sum(int(item["bytes"]) for item in all_files),
|
| 280 |
+
"all_effective_training_tensors_exact": True,
|
| 281 |
+
"chunk_count": len(chunk_reports),
|
| 282 |
+
"files": all_files,
|
| 283 |
+
"status": "complete",
|
| 284 |
+
"error": None,
|
| 285 |
+
"retry_count": 0,
|
| 286 |
+
}
|
| 287 |
+
write_json(args.output_audit, final_audit)
|
| 288 |
+
return {key: value for key, value in final_audit.items() if key != "files"}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def main() -> int:
|
| 292 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 293 |
+
parser.add_argument("--python", type=Path, required=True)
|
| 294 |
+
parser.add_argument("--accelerate", type=Path, required=True)
|
| 295 |
+
parser.add_argument("--accelerate-config", type=Path, required=True)
|
| 296 |
+
parser.add_argument("--upstream-train", type=Path, required=True)
|
| 297 |
+
parser.add_argument("--model-paths", required=True)
|
| 298 |
+
parser.add_argument("--processor-path", type=Path, required=True)
|
| 299 |
+
parser.add_argument("--metadata", type=Path, required=True)
|
| 300 |
+
parser.add_argument("--cache-root", type=Path, required=True)
|
| 301 |
+
parser.add_argument("--tmpfs-root", type=Path, default=None)
|
| 302 |
+
parser.add_argument("--tmpfs-ranks", type=int, nargs="*", default=[])
|
| 303 |
+
parser.add_argument("--output-audit", type=Path, required=True)
|
| 304 |
+
parser.add_argument("--world-size", type=int, required=True)
|
| 305 |
+
parser.add_argument("--chunk-size", type=int, default=1024)
|
| 306 |
+
parser.add_argument("--compact-workers", type=int, default=4)
|
| 307 |
+
parser.add_argument("--max-pixels", type=int, required=True)
|
| 308 |
+
parser.add_argument("--main-process-port", type=int, default=29680)
|
| 309 |
+
args = parser.parse_args()
|
| 310 |
+
report = build_cache(args)
|
| 311 |
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
| 312 |
+
return 0
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
if __name__ == "__main__":
|
| 316 |
+
raise SystemExit(main())
|
src/wgsr_v9/executor_cache_compactor.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Compact generated DiffSynth caches to exact BF16 training inputs."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 8 |
+
import json
|
| 9 |
+
import multiprocessing
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import sys
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 17 |
+
|
| 18 |
+
from wgsr_v9.executor_training import ALGORITHM_VERSION # noqa: E402
|
| 19 |
+
from wgsr_v9.io import write_json # noqa: E402
|
| 20 |
+
|
| 21 |
+
SHARED_KEYS = {
|
| 22 |
+
"input_latents",
|
| 23 |
+
"edit_latents",
|
| 24 |
+
"height",
|
| 25 |
+
"width",
|
| 26 |
+
"cfg_scale",
|
| 27 |
+
"use_gradient_checkpointing",
|
| 28 |
+
"use_gradient_checkpointing_offload",
|
| 29 |
+
"use_flex_attention",
|
| 30 |
+
"min_timestep_boundary",
|
| 31 |
+
"max_timestep_boundary",
|
| 32 |
+
"noise_scale",
|
| 33 |
+
}
|
| 34 |
+
POSITIVE_KEYS = {"prompt", "prompt_embeds", "prompt_embeds_mask", "edit_image_pad_mask", "kv_cache"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _compact_inputs(inputs: tuple[dict[str, Any], dict[str, Any], dict[str, Any]]) -> tuple[dict[str, Any], ...]:
|
| 38 |
+
shared, positive, _negative = inputs
|
| 39 |
+
compact_shared = {key: value for key, value in shared.items() if key in SHARED_KEYS}
|
| 40 |
+
compact_shared["input_latents"] = shared["input_latents"].to(torch.bfloat16).contiguous()
|
| 41 |
+
compact_shared["edit_latents"] = [value.to(torch.bfloat16).contiguous() for value in shared["edit_latents"]]
|
| 42 |
+
compact_positive = {key: positive[key] for key in POSITIVE_KEYS if key in positive}
|
| 43 |
+
compact_positive["prompt_embeds"] = positive["prompt_embeds"].to(torch.bfloat16).contiguous()
|
| 44 |
+
return compact_shared, compact_positive, {"negative_prompt": ""}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _validate_same_effective_values(
|
| 48 |
+
original: tuple[dict[str, Any], dict[str, Any], dict[str, Any]],
|
| 49 |
+
compact: tuple[dict[str, Any], dict[str, Any], dict[str, Any]],
|
| 50 |
+
path: Path,
|
| 51 |
+
) -> None:
|
| 52 |
+
tensor_pairs = [
|
| 53 |
+
(original[0]["input_latents"], compact[0]["input_latents"]),
|
| 54 |
+
(original[1]["prompt_embeds"], compact[1]["prompt_embeds"]),
|
| 55 |
+
]
|
| 56 |
+
tensor_pairs.extend(zip(original[0]["edit_latents"], compact[0]["edit_latents"]))
|
| 57 |
+
for before, after in tensor_pairs:
|
| 58 |
+
if not torch.equal(before.to(torch.bfloat16), after):
|
| 59 |
+
raise ValueError(f"effective BF16 training values changed: {path}")
|
| 60 |
+
if not bool(torch.isfinite(after).all()):
|
| 61 |
+
raise ValueError(f"nonfinite compact training tensor: {path}")
|
| 62 |
+
if not torch.equal(original[1]["edit_image_pad_mask"], compact[1]["edit_image_pad_mask"]):
|
| 63 |
+
raise ValueError(f"source image-token mask changed: {path}")
|
| 64 |
+
if original[1]["prompt"] != compact[1]["prompt"]:
|
| 65 |
+
raise ValueError(f"prompt changed: {path}")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _is_compact(inputs: tuple[dict[str, Any], dict[str, Any], dict[str, Any]]) -> bool:
|
| 69 |
+
shared, positive, negative = inputs
|
| 70 |
+
tensors = [shared["input_latents"], positive["prompt_embeds"], *shared["edit_latents"]]
|
| 71 |
+
return (
|
| 72 |
+
set(shared).issubset(SHARED_KEYS)
|
| 73 |
+
and set(positive).issubset(POSITIVE_KEYS)
|
| 74 |
+
and set(negative).issubset({"negative_prompt"})
|
| 75 |
+
and all(tensor.dtype == torch.bfloat16 for tensor in tensors)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def compact_one(path_string: str) -> dict[str, Any]:
|
| 80 |
+
torch.set_num_threads(1)
|
| 81 |
+
path = Path(path_string).resolve()
|
| 82 |
+
before_bytes = path.stat().st_size
|
| 83 |
+
original = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
|
| 84 |
+
compact = _compact_inputs(original)
|
| 85 |
+
_validate_same_effective_values(original, compact, path)
|
| 86 |
+
if _is_compact(original):
|
| 87 |
+
return {
|
| 88 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 89 |
+
"input_path": str(path),
|
| 90 |
+
"output_path": str(path),
|
| 91 |
+
"before_bytes": before_bytes,
|
| 92 |
+
"after_bytes": before_bytes,
|
| 93 |
+
"effective_training_tensors_exact": True,
|
| 94 |
+
"status": "ready",
|
| 95 |
+
"error": None,
|
| 96 |
+
"retry_count": 0,
|
| 97 |
+
}
|
| 98 |
+
temporary = path.with_suffix(".compact.tmp")
|
| 99 |
+
torch.save(compact, temporary)
|
| 100 |
+
reloaded = torch.load(temporary, map_location="cpu", weights_only=False, mmap=True)
|
| 101 |
+
_validate_same_effective_values(original, reloaded, path)
|
| 102 |
+
after_bytes = temporary.stat().st_size
|
| 103 |
+
if after_bytes >= before_bytes:
|
| 104 |
+
temporary.unlink(missing_ok=True)
|
| 105 |
+
raise ValueError(f"compacted cache is not smaller ({before_bytes} -> {after_bytes}): {path}")
|
| 106 |
+
temporary.replace(path)
|
| 107 |
+
return {
|
| 108 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 109 |
+
"input_path": str(path),
|
| 110 |
+
"output_path": str(path),
|
| 111 |
+
"before_bytes": before_bytes,
|
| 112 |
+
"after_bytes": after_bytes,
|
| 113 |
+
"effective_training_tensors_exact": True,
|
| 114 |
+
"status": "ready",
|
| 115 |
+
"error": None,
|
| 116 |
+
"retry_count": 0,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def compact_cache(cache_root: Path, output_path: Path, workers: int) -> dict[str, Any]:
|
| 121 |
+
cache_root = cache_root.resolve()
|
| 122 |
+
output_path = output_path.resolve()
|
| 123 |
+
if workers <= 0:
|
| 124 |
+
raise ValueError("workers must be positive")
|
| 125 |
+
paths = sorted(cache_root.rglob("*.pth"))
|
| 126 |
+
if not paths:
|
| 127 |
+
raise ValueError(f"no .pth cache files found under {cache_root}")
|
| 128 |
+
if any(not path.resolve().is_relative_to(cache_root) for path in paths):
|
| 129 |
+
raise ValueError("cache file escaped cache root")
|
| 130 |
+
rows: list[dict[str, Any]] = []
|
| 131 |
+
failures: list[dict[str, Any]] = []
|
| 132 |
+
with ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("spawn")) as pool:
|
| 133 |
+
futures = {pool.submit(compact_one, str(path)): path for path in paths}
|
| 134 |
+
for future in as_completed(futures):
|
| 135 |
+
path = futures[future]
|
| 136 |
+
try:
|
| 137 |
+
rows.append(future.result())
|
| 138 |
+
except Exception as exc: # write a row-level audit before stopping
|
| 139 |
+
failures.append(
|
| 140 |
+
{
|
| 141 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 142 |
+
"input_path": str(path.resolve()),
|
| 143 |
+
"output_path": str(path.resolve()),
|
| 144 |
+
"status": "failed",
|
| 145 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 146 |
+
"retry_count": 0,
|
| 147 |
+
}
|
| 148 |
+
)
|
| 149 |
+
rows.sort(key=lambda row: row["input_path"])
|
| 150 |
+
failures.sort(key=lambda row: row["input_path"])
|
| 151 |
+
report = {
|
| 152 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 153 |
+
"input_path": str(cache_root),
|
| 154 |
+
"output_path": str(output_path),
|
| 155 |
+
"count": len(paths),
|
| 156 |
+
"completed_count": len(rows),
|
| 157 |
+
"failed_count": len(failures),
|
| 158 |
+
"before_bytes": sum(row["before_bytes"] for row in rows),
|
| 159 |
+
"after_bytes": sum(row["after_bytes"] for row in rows),
|
| 160 |
+
"all_effective_training_tensors_exact": all(row["effective_training_tensors_exact"] for row in rows),
|
| 161 |
+
"files": rows + failures,
|
| 162 |
+
"status": "complete" if not failures else "failed",
|
| 163 |
+
"error": None if not failures else f"{len(failures)} cache compaction failures",
|
| 164 |
+
"retry_count": 0,
|
| 165 |
+
}
|
| 166 |
+
write_json(output_path, report)
|
| 167 |
+
if failures:
|
| 168 |
+
raise RuntimeError(report["error"])
|
| 169 |
+
return report
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def main() -> int:
|
| 173 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 174 |
+
parser.add_argument("--cache-root", type=Path, required=True)
|
| 175 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 176 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 177 |
+
args = parser.parse_args()
|
| 178 |
+
report = compact_cache(args.cache_root, args.output, args.workers)
|
| 179 |
+
print(json.dumps({key: value for key, value in report.items() if key != "files"}, indent=2))
|
| 180 |
+
return 0
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
raise SystemExit(main())
|
src/wgsr_v9/executor_inference/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public API for the Qwen Image 2.1 executor inference stage."""
|
| 2 |
+
|
| 3 |
+
from ..io import canonical_sha256
|
| 4 |
+
from .checkpoint import load_pipeline, make_transformer_view
|
| 5 |
+
from .cli import main, parse_args
|
| 6 |
+
from .config import (
|
| 7 |
+
default_checkpoint,
|
| 8 |
+
default_input_manifest,
|
| 9 |
+
default_output_root,
|
| 10 |
+
load_config,
|
| 11 |
+
resolve_path,
|
| 12 |
+
validate_config,
|
| 13 |
+
)
|
| 14 |
+
from .constants import ALGORITHM_VERSION, PROTOCOL_VERSION
|
| 15 |
+
from .manifest import (
|
| 16 |
+
input_hash,
|
| 17 |
+
load_input_rows,
|
| 18 |
+
load_seed_map,
|
| 19 |
+
parse_indices,
|
| 20 |
+
row_seed,
|
| 21 |
+
)
|
| 22 |
+
from .runner import expected_source_size, select_gpu_ids, sha256_bytes, sha256_file
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"ALGORITHM_VERSION",
|
| 26 |
+
"PROTOCOL_VERSION",
|
| 27 |
+
"canonical_sha256",
|
| 28 |
+
"default_checkpoint",
|
| 29 |
+
"default_input_manifest",
|
| 30 |
+
"default_output_root",
|
| 31 |
+
"expected_source_size",
|
| 32 |
+
"input_hash",
|
| 33 |
+
"load_config",
|
| 34 |
+
"load_input_rows",
|
| 35 |
+
"load_pipeline",
|
| 36 |
+
"load_seed_map",
|
| 37 |
+
"main",
|
| 38 |
+
"make_transformer_view",
|
| 39 |
+
"parse_args",
|
| 40 |
+
"parse_indices",
|
| 41 |
+
"resolve_path",
|
| 42 |
+
"row_seed",
|
| 43 |
+
"select_gpu_ids",
|
| 44 |
+
"sha256_bytes",
|
| 45 |
+
"sha256_file",
|
| 46 |
+
"validate_config",
|
| 47 |
+
]
|
src/wgsr_v9/executor_inference/checkpoint.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Diffusers-compatible view over a DiffSynth transformer checkpoint."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from ..io import sha256_path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def pretrained_transformer_identity(model_path: Path) -> dict[str, Any]:
|
| 15 |
+
"""Fingerprint the actual original shards, not just their index file."""
|
| 16 |
+
root = model_path / "transformer"
|
| 17 |
+
index = root / "diffusion_pytorch_model.safetensors.index.json"
|
| 18 |
+
files = {root / "config.json"}
|
| 19 |
+
if index.is_file():
|
| 20 |
+
files.add(index)
|
| 21 |
+
weights = json.loads(index.read_text(encoding="utf-8"))["weight_map"]
|
| 22 |
+
if not weights:
|
| 23 |
+
raise ValueError("pretrained transformer index has no weights")
|
| 24 |
+
for name in set(weights.values()):
|
| 25 |
+
if Path(name).name != name:
|
| 26 |
+
raise ValueError("pretrained transformer shard must be a local filename")
|
| 27 |
+
files.add(root / name)
|
| 28 |
+
else:
|
| 29 |
+
files.add(root / "diffusion_pytorch_model.safetensors")
|
| 30 |
+
return {
|
| 31 |
+
"algorithm_version": "wgsr_v9_pretrained_transformer_identity_v1",
|
| 32 |
+
"path": str(root.resolve()),
|
| 33 |
+
"files_sha256": {path.name: sha256_path(path) for path in sorted(files)},
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make_transformer_view(model_path: Path, checkpoint: Path | None, output_root: Path) -> Path:
|
| 38 |
+
if checkpoint is None:
|
| 39 |
+
root = model_path / "transformer"
|
| 40 |
+
if not (root / "config.json").is_file():
|
| 41 |
+
raise FileNotFoundError(root / "config.json")
|
| 42 |
+
if not any((root / name).is_file() for name in (
|
| 43 |
+
"diffusion_pytorch_model.safetensors",
|
| 44 |
+
"diffusion_pytorch_model.safetensors.index.json",
|
| 45 |
+
)):
|
| 46 |
+
raise FileNotFoundError(f"no pretrained transformer weights in {root}")
|
| 47 |
+
return root
|
| 48 |
+
if not checkpoint.is_file():
|
| 49 |
+
raise FileNotFoundError(checkpoint)
|
| 50 |
+
base_config = model_path / "transformer/config.json"
|
| 51 |
+
if not base_config.is_file():
|
| 52 |
+
raise FileNotFoundError(base_config)
|
| 53 |
+
view = output_root / "_trained_transformer_view"
|
| 54 |
+
view.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
config = view / "config.json"
|
| 56 |
+
if config.exists():
|
| 57 |
+
if sha256_path(config) != sha256_path(base_config):
|
| 58 |
+
raise ValueError(f"existing transformer view config differs: {config}")
|
| 59 |
+
else:
|
| 60 |
+
temporary = config.with_name(f".{config.name}.{os.getpid()}.tmp")
|
| 61 |
+
shutil.copy2(base_config, temporary)
|
| 62 |
+
try:
|
| 63 |
+
temporary.replace(config)
|
| 64 |
+
except FileExistsError:
|
| 65 |
+
temporary.unlink(missing_ok=True)
|
| 66 |
+
link = view / "diffusion_pytorch_model.safetensors"
|
| 67 |
+
expected = checkpoint.resolve()
|
| 68 |
+
if link.is_symlink():
|
| 69 |
+
if link.resolve() != expected:
|
| 70 |
+
raise ValueError(f"transformer view points to a different checkpoint: {link.resolve()}")
|
| 71 |
+
elif link.exists():
|
| 72 |
+
raise ValueError(f"refusing to replace non-symlink transformer view file: {link}")
|
| 73 |
+
else:
|
| 74 |
+
try:
|
| 75 |
+
link.symlink_to(expected)
|
| 76 |
+
except FileExistsError:
|
| 77 |
+
if not link.is_symlink() or link.resolve() != expected:
|
| 78 |
+
raise ValueError(f"transformer view points to a different checkpoint: {link}")
|
| 79 |
+
return view
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def load_pipeline(model_path: Path, checkpoint: Path | None, view: Path, dtype_name: str):
|
| 83 |
+
import torch
|
| 84 |
+
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel
|
| 85 |
+
|
| 86 |
+
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[dtype_name]
|
| 87 |
+
print(f"loading transformer checkpoint={checkpoint} pretrained={checkpoint is None} view={view}", flush=True)
|
| 88 |
+
transformer, loading = QwenImage21Transformer2DModel.from_pretrained(
|
| 89 |
+
str(view), torch_dtype=dtype, output_loading_info=True, local_files_only=True
|
| 90 |
+
)
|
| 91 |
+
unexpected = {key: value for key, value in loading.items() if value}
|
| 92 |
+
if unexpected:
|
| 93 |
+
raise RuntimeError(f"checkpoint loading reported non-empty fields: {unexpected}")
|
| 94 |
+
pipe = QwenImage21Pipeline.from_pretrained(
|
| 95 |
+
str(model_path), transformer=transformer, torch_dtype=dtype, local_files_only=True
|
| 96 |
+
)
|
| 97 |
+
pipe.to("cuda")
|
| 98 |
+
pipe.set_progress_bar_config(disable=True)
|
| 99 |
+
return pipe, loading, dtype
|
src/wgsr_v9/executor_inference/cli.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command-line parsing for resumable executor inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .config import (
|
| 9 |
+
default_checkpoint,
|
| 10 |
+
default_input_manifest,
|
| 11 |
+
default_output_root,
|
| 12 |
+
load_config,
|
| 13 |
+
resolve_path,
|
| 14 |
+
)
|
| 15 |
+
from .runner import supervisor_main, worker_main
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_args() -> argparse.Namespace:
|
| 19 |
+
# Parse the config path first so versioned experiments can keep their
|
| 20 |
+
# inference roots and checkpoints isolated without replacing the default
|
| 21 |
+
# v1 recipe.
|
| 22 |
+
bootstrap = argparse.ArgumentParser(add_help=False)
|
| 23 |
+
bootstrap.add_argument("--config", type=Path, default=None)
|
| 24 |
+
bootstrap_args, _ = bootstrap.parse_known_args()
|
| 25 |
+
config_path = resolve_path(bootstrap_args.config) if bootstrap_args.config else None
|
| 26 |
+
config = load_config(config_path) if config_path is not None else load_config()
|
| 27 |
+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
| 28 |
+
parser.add_argument("--config", type=Path, default=config_path)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--worker", action="store_true", help="run one worker; normally the command is a supervisor"
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument("--variant", choices=("simple", "teacher_cot", "predicted_cot"), required=True)
|
| 33 |
+
parser.add_argument("--input-manifest", type=Path, default=None)
|
| 34 |
+
parser.add_argument("--checkpoint", type=Path, default=None)
|
| 35 |
+
parser.add_argument("--pretrained", action="store_true", default=config.get("pretrained", False),
|
| 36 |
+
help="use original model transformer weights without any fine-tuned checkpoint")
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--model-path", type=Path, default=resolve_path(config["model_path"])
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument("--output-root", type=Path, default=None)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--seed-manifest",
|
| 43 |
+
type=Path,
|
| 44 |
+
default=resolve_path(config["baseline_seed_manifest"]),
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument("--seed-base", type=int, default=20261030)
|
| 47 |
+
parser.add_argument("--steps", type=int, default=int(config["num_inference_steps"]))
|
| 48 |
+
parser.add_argument("--dtype", choices=("bf16", "fp16", "fp32"), default=str(config["dtype"]))
|
| 49 |
+
kv_cache = parser.add_mutually_exclusive_group()
|
| 50 |
+
kv_cache.add_argument("--use-kv-cache", dest="use_kv_cache", action="store_true")
|
| 51 |
+
kv_cache.add_argument("--no-use-kv-cache", dest="use_kv_cache", action="store_false")
|
| 52 |
+
parser.set_defaults(use_kv_cache=bool(config["use_kv_cache"]))
|
| 53 |
+
parser.add_argument("--world-size", type=int, default=int(config["world_size"]))
|
| 54 |
+
parser.add_argument("--gpu-ids", default=str(config["physical_gpu_ids"]))
|
| 55 |
+
parser.add_argument("--rank", type=int, default=0)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--row-indices",
|
| 58 |
+
default=None,
|
| 59 |
+
help="comma-separated input row indices, useful for case-study smoke runs",
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 62 |
+
parser.add_argument("--condition-dropout", choices=("keep", "drop_text", "drop_image"),
|
| 63 |
+
default=config.get("condition_dropout", "keep"),
|
| 64 |
+
help="fixed diagnostic action; formal inference uses keep")
|
| 65 |
+
parser.add_argument("--condition-ablation", choices=("none", "no_metric_stage", "no_image"),
|
| 66 |
+
default=config.get("condition_ablation", "none"))
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
args.executor_prompt_protocol_version = config.get("executor_prompt_protocol_version")
|
| 69 |
+
args.evaluation_manifest = resolve_path(config["evaluation_manifest"]) if config.get("evaluation_manifest") else None
|
| 70 |
+
args.expected_rows = config.get("expected_rows")
|
| 71 |
+
if args.pretrained and args.checkpoint is not None:
|
| 72 |
+
raise ValueError("--pretrained cannot be combined with a checkpoint")
|
| 73 |
+
if args.pretrained and (config.get("checkpoints") or config.get("executor_training_root")):
|
| 74 |
+
raise ValueError("pretrained config must not contain fine-tuned checkpoints or a training root")
|
| 75 |
+
if args.condition_ablation != "none" and (
|
| 76 |
+
args.condition_dropout != "keep" or args.variant == "simple"
|
| 77 |
+
):
|
| 78 |
+
raise ValueError("fixed ablation requires CoT text Executor without diagnostic dropout")
|
| 79 |
+
args.input_manifest = resolve_path(
|
| 80 |
+
args.input_manifest or default_input_manifest(config, args.variant)
|
| 81 |
+
)
|
| 82 |
+
args.checkpoint = None if args.pretrained else resolve_path(
|
| 83 |
+
args.checkpoint or default_checkpoint(config, args.variant)
|
| 84 |
+
)
|
| 85 |
+
args.model_path = resolve_path(args.model_path)
|
| 86 |
+
args.output_root = resolve_path(args.output_root or default_output_root(config, args.variant))
|
| 87 |
+
if args.seed_manifest is not None:
|
| 88 |
+
args.seed_manifest = resolve_path(args.seed_manifest)
|
| 89 |
+
if args.world_size < 1:
|
| 90 |
+
raise ValueError("--world-size must be positive")
|
| 91 |
+
if args.worker and not (0 <= args.rank < args.world_size):
|
| 92 |
+
raise ValueError("worker rank is outside world size")
|
| 93 |
+
return args
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main() -> int:
|
| 97 |
+
args = parse_args()
|
| 98 |
+
return worker_main(args) if args.worker else supervisor_main(args)
|
src/wgsr_v9/executor_inference/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration and path resolution for executor inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import yaml
|
| 9 |
+
|
| 10 |
+
from .constants import ALGORITHM_VERSION, DEFAULT_CONFIG, PROTOCOL_VERSION, REPO_ROOT
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def resolve_path(value: str | Path, *, base: Path = REPO_ROOT) -> Path:
|
| 14 |
+
path = Path(str(value)).expanduser()
|
| 15 |
+
return path.resolve() if path.is_absolute() else (base / path).resolve()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_config(path: Path = DEFAULT_CONFIG) -> dict[str, Any]:
|
| 19 |
+
with path.open(encoding="utf-8") as handle:
|
| 20 |
+
config = yaml.safe_load(handle)
|
| 21 |
+
if not isinstance(config, dict):
|
| 22 |
+
raise ValueError(f"inference config must contain a mapping: {path}")
|
| 23 |
+
validate_config(config, path=path)
|
| 24 |
+
return config
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def validate_config(config: dict[str, Any], *, path: Path | None = None) -> None:
|
| 28 |
+
if (any(config.get(key) is not None for key in (
|
| 29 |
+
"numeric_bundle", "numeric_mode", "numeric_protocol_root",
|
| 30 |
+
"numeric_normalizer_sha256", "numeric_training_metadata_sha256",
|
| 31 |
+
)) or config.get("numeric_condition", {}).get("enabled", False)
|
| 32 |
+
or config.get("condition_dropout") == "drop_numeric"):
|
| 33 |
+
raise ValueError("Numeric injection is not included in this public release; use a text Executor recipe")
|
| 34 |
+
location = f" in {path}" if path else ""
|
| 35 |
+
if config.get("version") != ALGORITHM_VERSION:
|
| 36 |
+
raise ValueError(
|
| 37 |
+
f"executor inference config version{location} must be {ALGORITHM_VERSION!r}"
|
| 38 |
+
)
|
| 39 |
+
if config.get("protocol_version") != PROTOCOL_VERSION:
|
| 40 |
+
raise ValueError(
|
| 41 |
+
f"executor inference protocol_version{location} must be {PROTOCOL_VERSION!r}"
|
| 42 |
+
)
|
| 43 |
+
if config.get("source_only") is not True:
|
| 44 |
+
raise ValueError("executor inference must be source_only=true")
|
| 45 |
+
if config.get("target_usage") != "eval_reference_only":
|
| 46 |
+
raise ValueError("executor inference target_usage must be eval_reference_only")
|
| 47 |
+
if int(config.get("num_inference_steps", -1)) != 20:
|
| 48 |
+
raise ValueError("the reviewed executor inference contract requires 20 steps")
|
| 49 |
+
gpu_ids = [
|
| 50 |
+
token.strip()
|
| 51 |
+
for token in str(config.get("physical_gpu_ids", "")).split(",")
|
| 52 |
+
if token.strip()
|
| 53 |
+
]
|
| 54 |
+
if int(config.get("world_size", -1)) != len(gpu_ids) or not gpu_ids:
|
| 55 |
+
raise ValueError("world_size must equal the number of configured physical_gpu_ids")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def default_checkpoint(config: dict[str, Any], variant: str) -> Path:
|
| 59 |
+
checkpoint_variant = "teacher_cot" if variant == "predicted_cot" else variant
|
| 60 |
+
explicit = config.get("checkpoints", {}).get(checkpoint_variant)
|
| 61 |
+
if explicit:
|
| 62 |
+
return resolve_path(explicit)
|
| 63 |
+
return (
|
| 64 |
+
resolve_path(config["executor_training_root"])
|
| 65 |
+
/ checkpoint_variant
|
| 66 |
+
/ "checkpoints/epoch-1.safetensors"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def default_input_manifest(config: dict[str, Any], variant: str) -> Path:
|
| 71 |
+
if variant == "predicted_cot":
|
| 72 |
+
manifest = config.get("predicted_cot_manifest")
|
| 73 |
+
if not manifest:
|
| 74 |
+
raise ValueError("predicted_cot requires an explicit generated CoT input manifest")
|
| 75 |
+
return resolve_path(manifest)
|
| 76 |
+
return resolve_path(config["executor_data_root"]) / variant / "val.jsonl"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def default_output_root(config: dict[str, Any], variant: str) -> Path:
|
| 80 |
+
return resolve_path(config["inference_run_root"]) / variant
|
src/wgsr_v9/executor_inference/constants.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned constants for Qwen Image 2.1 executor inference."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
| 6 |
+
DEFAULT_CONFIG = REPO_ROOT / "configs/local/rice/executor_infer.json"
|
| 7 |
+
CLI_SCRIPT = REPO_ROOT / "scripts/run_executor_inference.py"
|
| 8 |
+
ALGORITHM_VERSION = "wgsr_v9_qwen_image21_executor_inference_v1"
|
| 9 |
+
PROTOCOL_VERSION = "wgsr_v9_qwen_image21_executor_inference_v1"
|
| 10 |
+
EXPECTED_SIZES = {(672, 896), (896, 672)}
|
src/wgsr_v9/executor_inference/manifest.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Input and seed manifest validation for executor inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from ..io import canonical_sha256, read_jsonl, sha256_path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def read_optional_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 14 |
+
return read_jsonl(path) if path.is_file() else []
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def parse_indices(value: str | None) -> set[int] | None:
|
| 18 |
+
if value is None or not value.strip():
|
| 19 |
+
return None
|
| 20 |
+
result: set[int] = set()
|
| 21 |
+
for token in value.split(","):
|
| 22 |
+
token = token.strip()
|
| 23 |
+
if not token:
|
| 24 |
+
continue
|
| 25 |
+
index = int(token)
|
| 26 |
+
if index < 0:
|
| 27 |
+
raise ValueError("row indices must be non-negative")
|
| 28 |
+
result.add(index)
|
| 29 |
+
if not result:
|
| 30 |
+
raise ValueError("--row-indices did not contain any indices")
|
| 31 |
+
return result
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_input_rows(path: Path, indices: set[int] | None) -> tuple[list[dict[str, Any]], str]:
|
| 35 |
+
if not path.is_file():
|
| 36 |
+
raise FileNotFoundError(path)
|
| 37 |
+
selected: list[dict[str, Any]] = []
|
| 38 |
+
seen: set[int] = set()
|
| 39 |
+
seen_ids: set[str] = set()
|
| 40 |
+
required = ("request_id", "image", "edit_image", "prompt", "view")
|
| 41 |
+
for ordinal, row in enumerate(read_jsonl(path)):
|
| 42 |
+
row_index = int(row.get("original_row_index", ordinal))
|
| 43 |
+
if row_index in seen:
|
| 44 |
+
raise ValueError(f"duplicate inference row index {row_index} in {path}")
|
| 45 |
+
seen.add(row_index)
|
| 46 |
+
missing = [key for key in required if key not in row]
|
| 47 |
+
if missing:
|
| 48 |
+
raise ValueError(f"row {row_index} is missing required fields: {missing}")
|
| 49 |
+
request_id = str(row["request_id"])
|
| 50 |
+
if not request_id or request_id in seen_ids:
|
| 51 |
+
raise ValueError(f"empty or duplicate inference request_id: {request_id}")
|
| 52 |
+
seen_ids.add(request_id)
|
| 53 |
+
if indices is None or row_index in indices:
|
| 54 |
+
selected.append({**row, "inference_row_index": row_index})
|
| 55 |
+
if indices is not None:
|
| 56 |
+
missing_indices = sorted(indices - {int(row["inference_row_index"]) for row in selected})
|
| 57 |
+
if missing_indices:
|
| 58 |
+
raise ValueError(f"requested row indices are not in {path}: {missing_indices[:20]}")
|
| 59 |
+
if not selected:
|
| 60 |
+
raise ValueError(f"no rows selected from {path}")
|
| 61 |
+
return selected, sha256_path(path)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def validate_prompt_rows(rows: list[dict[str, Any]], variant: str, *,
|
| 65 |
+
expected_protocol: str | None = None) -> None:
|
| 66 |
+
"""Reject protocol drift while keeping legacy manifests opt-in compatible."""
|
| 67 |
+
from ..cot_metric_names import validate_metric_name
|
| 68 |
+
from ..executor_training import NAMED_WEEKS_PROTOCOL_VERSION, executor_prompt, prediction_interval_weeks
|
| 69 |
+
|
| 70 |
+
protocol = Path(__file__).resolve().parents[3] / "protocols/qwen_image21_executor_v9_v3_metric_named_weeks"
|
| 71 |
+
template = suffix = bindings = None
|
| 72 |
+
for row in rows:
|
| 73 |
+
declared = row.get("executor_prompt_protocol_version", row.get("protocol_version"))
|
| 74 |
+
if expected_protocol is not None and declared != expected_protocol:
|
| 75 |
+
raise ValueError(f"{row['request_id']}: executor prompt protocol mismatch")
|
| 76 |
+
if declared == "wgsr_maize_executor_days_v1":
|
| 77 |
+
from ..maize.experiment import validate_executor_row
|
| 78 |
+
validate_executor_row(row, variant)
|
| 79 |
+
continue
|
| 80 |
+
if declared != NAMED_WEEKS_PROTOCOL_VERSION:
|
| 81 |
+
continue
|
| 82 |
+
if template is None:
|
| 83 |
+
template = (protocol / "EXECUTOR_PROMPT_TEMPLATE.txt").read_text()
|
| 84 |
+
suffix = (protocol / "TEACHER_COT_SUFFIX.txt").read_text()
|
| 85 |
+
bindings = json.loads((protocol / "cot/VIEW_VARIABLE_BINDINGS.json").read_text())
|
| 86 |
+
if row.get("time_condition_unit") != "weeks" or "prediction_interval_weeks" not in row:
|
| 87 |
+
raise ValueError("named executor input requires explicit rounded weeks metadata")
|
| 88 |
+
prediction_interval_weeks(row)
|
| 89 |
+
if row.get("executor_variant") != variant:
|
| 90 |
+
raise ValueError("executor variant does not match input condition provenance")
|
| 91 |
+
if variant == "predicted_cot" and row.get("cot_source") != "planner_prediction":
|
| 92 |
+
raise ValueError("predicted_cot requires planner_prediction provenance")
|
| 93 |
+
prompt = row["prompt"]
|
| 94 |
+
if re.search(r"\b\d+\s+days?\b|</?think>", prompt, re.IGNORECASE):
|
| 95 |
+
raise ValueError("named weeks prompt contains exact days or a think wrapper")
|
| 96 |
+
body = None
|
| 97 |
+
if variant != "simple":
|
| 98 |
+
if prompt.count("<GROWTH_COT>") != 1 or prompt.count("</GROWTH_COT>") != 1:
|
| 99 |
+
raise ValueError("expected exactly one GROWTH_COT wrapper")
|
| 100 |
+
body = prompt.split("<GROWTH_COT>", 1)[1].split("</GROWTH_COT>", 1)[0].strip()
|
| 101 |
+
if row.get("numeric_evidence_format") != "metric_named_v1":
|
| 102 |
+
raise ValueError("named CoT input requires metric_named_v1 metadata")
|
| 103 |
+
lines = [line.strip() for line in body.splitlines() if line.strip()]
|
| 104 |
+
if [line for line in lines if line in {"Stage reasoning", "Growth plan", "Target phenotype"}] != [
|
| 105 |
+
"Stage reasoning", "Growth plan", "Target phenotype"]:
|
| 106 |
+
raise ValueError("missing, duplicate or reordered CoT sections")
|
| 107 |
+
spec = bindings["top" if row["view"] == "top" else "front"]
|
| 108 |
+
growth = lines[lines.index("Growth plan") + 1:lines.index("Target phenotype")]
|
| 109 |
+
expected_labels = [spec["section_labels"][key] for key in spec["ordered_keys"]]
|
| 110 |
+
if [line.partition(":")[0] for line in growth] != expected_labels:
|
| 111 |
+
raise ValueError("CoT Growth plan fields do not match the view protocol")
|
| 112 |
+
for key, line in zip(spec["ordered_keys"], growth, strict=True):
|
| 113 |
+
validate_metric_name(line, key, spec)
|
| 114 |
+
request = {**row, "accession_id": row.get("accession_id") or str(row.get("plant_id", "")).split("-")[0]}
|
| 115 |
+
expected = executor_prompt(request, prompt_template=template, cot_suffix=suffix,
|
| 116 |
+
variant="simple" if variant == "simple" else "teacher_cot",
|
| 117 |
+
teacher_cot=body, protocol_version=NAMED_WEEKS_PROTOCOL_VERSION)
|
| 118 |
+
if prompt != expected:
|
| 119 |
+
raise ValueError("executor prompt differs from the trained template, wrapper or rounded weeks")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def validate_input_contract(args: Any, rows: list[dict[str, Any]]) -> None:
|
| 123 |
+
validate_prompt_rows(rows, args.variant,
|
| 124 |
+
expected_protocol=getattr(args, "executor_prompt_protocol_version", None))
|
| 125 |
+
canonical_path = getattr(args, "evaluation_manifest", None)
|
| 126 |
+
if canonical_path is None:
|
| 127 |
+
return
|
| 128 |
+
canonical_rows = read_jsonl(canonical_path)
|
| 129 |
+
canonical = {str(row["pair_id"]): row for row in canonical_rows}
|
| 130 |
+
if len(canonical) != len(canonical_rows):
|
| 131 |
+
raise ValueError("canonical evaluation IDs must be unique")
|
| 132 |
+
expected_count = getattr(args, "expected_rows", None)
|
| 133 |
+
if expected_count is not None and len(canonical) != expected_count:
|
| 134 |
+
raise ValueError("canonical evaluation row count differs from config")
|
| 135 |
+
selected_ids = {str(row["request_id"]) for row in rows}
|
| 136 |
+
if parse_indices(args.row_indices) is None and selected_ids != set(canonical):
|
| 137 |
+
raise ValueError("inference must cover every canonical validation query")
|
| 138 |
+
for row in rows:
|
| 139 |
+
reference = canonical.get(str(row["request_id"]))
|
| 140 |
+
if reference is None:
|
| 141 |
+
raise ValueError("unknown validation query")
|
| 142 |
+
for actual, expected in (("edit_image", "source_image_path"), ("image", "target_image_path")):
|
| 143 |
+
if Path(row[actual]).resolve() != Path(reference[expected]).resolve():
|
| 144 |
+
raise ValueError(f"canonical image mismatch: {row['request_id']}: {actual}")
|
| 145 |
+
if row.get("actual_interval_days") != reference.get("actual_interval_days"):
|
| 146 |
+
raise ValueError("canonical time interval mismatch")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def load_seed_map(path: Path | None) -> tuple[dict[str, int], str | None]:
|
| 150 |
+
if path is None:
|
| 151 |
+
return {}, None
|
| 152 |
+
if not path.is_file():
|
| 153 |
+
raise FileNotFoundError(path)
|
| 154 |
+
mapping: dict[str, int] = {}
|
| 155 |
+
for row in read_jsonl(path):
|
| 156 |
+
request_id = str(row.get("request_id") or row.get("pair_id") or "")
|
| 157 |
+
if not request_id or "seed" not in row:
|
| 158 |
+
continue
|
| 159 |
+
seed = int(row["seed"])
|
| 160 |
+
old = mapping.setdefault(request_id, seed)
|
| 161 |
+
if old != seed:
|
| 162 |
+
raise ValueError(f"conflicting seeds for {request_id} in {path}")
|
| 163 |
+
return mapping, sha256_path(path)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def input_hash(row: dict[str, Any]) -> str:
|
| 167 |
+
return canonical_sha256(row)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def row_seed(row: dict[str, Any], seed_map: dict[str, int], seed_base: int) -> int:
|
| 171 |
+
return int(seed_map.get(str(row["request_id"]), seed_base + int(row["inference_row_index"])))
|
src/wgsr_v9/executor_inference/runner.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Worker and supervisor implementations for executor inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import datetime as dt
|
| 7 |
+
import fcntl
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import subprocess
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
from typing import Any, Iterable
|
| 17 |
+
|
| 18 |
+
from ..io import append_jsonl, canonical_sha256, read_jsonl, sha256_path, write_json
|
| 19 |
+
from .checkpoint import load_pipeline, make_transformer_view, pretrained_transformer_identity
|
| 20 |
+
from .constants import ALGORITHM_VERSION, CLI_SCRIPT, EXPECTED_SIZES, PROTOCOL_VERSION
|
| 21 |
+
from .manifest import (
|
| 22 |
+
input_hash,
|
| 23 |
+
load_input_rows,
|
| 24 |
+
load_seed_map,
|
| 25 |
+
parse_indices,
|
| 26 |
+
read_optional_jsonl,
|
| 27 |
+
row_seed,
|
| 28 |
+
validate_input_contract,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
sha256_file = sha256_path
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def utc_now() -> str:
|
| 35 |
+
return dt.datetime.now(dt.timezone.utc).isoformat()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sha256_bytes(value: bytes) -> str:
|
| 39 |
+
return hashlib.sha256(value).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def select_gpu_ids(value: str) -> list[str]:
|
| 43 |
+
ids = [token.strip() for token in value.split(",") if token.strip()]
|
| 44 |
+
if not ids or any(not token.isdigit() for token in ids):
|
| 45 |
+
raise ValueError(f"invalid GPU list: {value!r}")
|
| 46 |
+
if len(set(ids)) != len(ids):
|
| 47 |
+
raise ValueError(f"duplicate GPU in list: {value!r}")
|
| 48 |
+
return ids
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def row_source_path(row: dict[str, Any]) -> Path:
|
| 52 |
+
return Path(str(row["edit_image"])).expanduser().resolve()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def expected_source_size(row: dict[str, Any], source: Any) -> tuple[int, int]:
|
| 56 |
+
width, height = map(int, source.size)
|
| 57 |
+
allowed_sizes = EXPECTED_SIZES
|
| 58 |
+
if row.get("species") == "maize":
|
| 59 |
+
from ..maize.experiment import EXECUTOR_PROTOCOL, SIZE
|
| 60 |
+
if row.get("executor_prompt_protocol_version", row.get("protocol_version")) != EXECUTOR_PROTOCOL:
|
| 61 |
+
raise ValueError("maize source geometry requires its versioned executor protocol")
|
| 62 |
+
allowed_sizes = {SIZE}
|
| 63 |
+
if (width, height) not in allowed_sizes:
|
| 64 |
+
raise ValueError(f"unsupported source size for {row['request_id']}: {(width, height)}")
|
| 65 |
+
declared = row.get("source_size")
|
| 66 |
+
if declared is not None and [width, height] != [int(declared[0]), int(declared[1])]:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
f"source size differs from manifest for {row['request_id']}: "
|
| 69 |
+
f"{(width, height)} vs {declared}"
|
| 70 |
+
)
|
| 71 |
+
return width, height
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def existing_successes(ledger: Path) -> dict[int, dict[str, Any]]:
|
| 75 |
+
latest: dict[int, dict[str, Any]] = {}
|
| 76 |
+
for record in read_optional_jsonl(ledger):
|
| 77 |
+
if record.get("status") != "completed":
|
| 78 |
+
continue
|
| 79 |
+
index = int(record["row_index"])
|
| 80 |
+
output = Path(str(record.get("output_path", "")))
|
| 81 |
+
if output.is_file():
|
| 82 |
+
latest[index] = record
|
| 83 |
+
return latest
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def fixed_ablation_inputs(row: dict[str, Any], mode: str) -> tuple[str, tuple[int, int] | None]:
|
| 87 |
+
from ..executor_ablation import transform_prompt
|
| 88 |
+
prompt = transform_prompt(str(row["prompt"]), mode)
|
| 89 |
+
if mode != "no_image":
|
| 90 |
+
return prompt, None
|
| 91 |
+
declared = row.get("source_size")
|
| 92 |
+
if not isinstance(declared, (list, tuple)) or len(declared) != 2:
|
| 93 |
+
raise ValueError("no_image requires frozen canvas dimensions; source pixels must not be read")
|
| 94 |
+
size = tuple(int(x) for x in declared)
|
| 95 |
+
if size not in EXPECTED_SIZES:
|
| 96 |
+
raise ValueError("unsupported no_image canvas size")
|
| 97 |
+
return prompt, size
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run_identity(args: argparse.Namespace, rows: list[dict[str, Any]],
|
| 101 |
+
input_sha: str, seed_sha: str | None) -> dict[str, Any]:
|
| 102 |
+
return {
|
| 103 |
+
"variant": args.variant, "input_manifest_sha256": input_sha,
|
| 104 |
+
"checkpoint_sha256": sha256_file(args.checkpoint) if args.checkpoint is not None else None,
|
| 105 |
+
**({"pretrained_transformer": pretrained_transformer_identity(args.model_path)}
|
| 106 |
+
if args.checkpoint is None else {}),
|
| 107 |
+
"model_path": str(args.model_path.resolve()),
|
| 108 |
+
"selected_indices": [int(row["inference_row_index"]) for row in rows],
|
| 109 |
+
"steps": args.steps, "dtype": args.dtype, "use_kv_cache": bool(args.use_kv_cache),
|
| 110 |
+
"seed_base": args.seed_base, "seed_manifest_sha256": seed_sha,
|
| 111 |
+
"numeric_condition": None, # Keep pre-cleanup text-run identity hashes resumable.
|
| 112 |
+
"executor_prompt_protocol_version": getattr(args, "executor_prompt_protocol_version", None),
|
| 113 |
+
**({"condition_dropout": args.condition_dropout}
|
| 114 |
+
if getattr(args, "condition_dropout", "keep") != "keep" else {}),
|
| 115 |
+
**({"condition_ablation": args.condition_ablation,
|
| 116 |
+
"condition_ablation_version": "wgsr_v9_executor_input_ablation_v1"}
|
| 117 |
+
if getattr(args, "condition_ablation", "none") != "none" else {}),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def validate_resume(previous: dict[str, Any], identity: dict[str, Any]) -> None:
|
| 122 |
+
# Check identity before the completed-run shortcut, including sampling and
|
| 123 |
+
# selection. Older manifests must be regenerated in a new output directory.
|
| 124 |
+
if previous.get("run_identity") != identity:
|
| 125 |
+
raise RuntimeError("inference inputs/checkpoint/sampling changed or legacy identity is missing; use a new output root")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def worker_main(args: argparse.Namespace) -> int:
|
| 129 |
+
import torch
|
| 130 |
+
from PIL import Image
|
| 131 |
+
|
| 132 |
+
if not torch.cuda.is_available():
|
| 133 |
+
raise RuntimeError("CUDA is required for executor inference")
|
| 134 |
+
torch.cuda.set_device(0)
|
| 135 |
+
rows, input_sha = load_input_rows(args.input_manifest, parse_indices(args.row_indices))
|
| 136 |
+
validate_input_contract(args, rows)
|
| 137 |
+
seed_map, seed_sha = load_seed_map(args.seed_manifest)
|
| 138 |
+
args.run_identity = run_identity(args, rows, input_sha, seed_sha)
|
| 139 |
+
args.run_identity_sha256 = canonical_sha256(args.run_identity)
|
| 140 |
+
view = make_transformer_view(args.model_path, args.checkpoint, args.output_root)
|
| 141 |
+
pipe, loading, dtype = load_pipeline(args.model_path, args.checkpoint, view, args.dtype)
|
| 142 |
+
rank_dir = args.output_root / f"rank-{args.rank:02d}"
|
| 143 |
+
ledger = rank_dir / "results.jsonl"
|
| 144 |
+
images = args.output_root / "images"
|
| 145 |
+
images.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
completed = existing_successes(ledger)
|
| 147 |
+
assigned = rows[args.rank :: args.world_size]
|
| 148 |
+
print(
|
| 149 |
+
f"rank={args.rank}/{args.world_size} assigned={len(assigned)} "
|
| 150 |
+
f"resume_completed={len(completed)}",
|
| 151 |
+
flush=True,
|
| 152 |
+
)
|
| 153 |
+
generated = 0
|
| 154 |
+
failed = 0
|
| 155 |
+
for row in assigned:
|
| 156 |
+
index = int(row["inference_row_index"])
|
| 157 |
+
row_hash = input_hash(row)
|
| 158 |
+
output_path = images / f"sample-{index:04d}.png"
|
| 159 |
+
old = completed.get(index)
|
| 160 |
+
if (not args.overwrite and old is not None and old.get("input_sha256") == row_hash
|
| 161 |
+
and old.get("run_identity_sha256") == args.run_identity_sha256 and output_path.is_file()):
|
| 162 |
+
print(f"rank={args.rank} skip row={index}", flush=True)
|
| 163 |
+
continue
|
| 164 |
+
source_path = row_source_path(row)
|
| 165 |
+
base: dict[str, Any] = {
|
| 166 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 167 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 168 |
+
"variant": args.variant,
|
| 169 |
+
"row_index": index,
|
| 170 |
+
"request_id": row["request_id"],
|
| 171 |
+
"pair_group_id": row.get("pair_group_id"),
|
| 172 |
+
"split": row.get("split"),
|
| 173 |
+
"view": row.get("view"),
|
| 174 |
+
"source_image_path": str(source_path),
|
| 175 |
+
"target_image_path": str(Path(str(row["image"])).expanduser().resolve()),
|
| 176 |
+
"target_usage": "eval_reference_only",
|
| 177 |
+
"output_path": str(output_path.resolve()),
|
| 178 |
+
"prompt": row["prompt"],
|
| 179 |
+
"prompt_sha256": sha256_bytes(str(row["prompt"]).encode("utf-8")),
|
| 180 |
+
"prompt_variant": args.variant,
|
| 181 |
+
"seed": row_seed(row, seed_map, args.seed_base),
|
| 182 |
+
"num_inference_steps": args.steps,
|
| 183 |
+
"use_kv_cache": bool(args.use_kv_cache),
|
| 184 |
+
"dtype": args.dtype,
|
| 185 |
+
"source_size_declared": row.get("source_size"),
|
| 186 |
+
"input_sha256": row_hash,
|
| 187 |
+
"run_identity_sha256": args.run_identity_sha256,
|
| 188 |
+
"input_path": str(source_path),
|
| 189 |
+
"cot_source": row.get("cot_source", "teacher_reference" if args.variant == "teacher_cot" else None),
|
| 190 |
+
"executor_prompt_protocol_version": row.get("executor_prompt_protocol_version", row.get("protocol_version")),
|
| 191 |
+
"time_condition_unit": row.get("time_condition_unit"),
|
| 192 |
+
"prediction_interval_weeks": row.get("prediction_interval_weeks"),
|
| 193 |
+
"source_sha256": None,
|
| 194 |
+
"retry_count": 0,
|
| 195 |
+
"started_at_utc": utc_now(),
|
| 196 |
+
}
|
| 197 |
+
started = time.time()
|
| 198 |
+
action = getattr(args, "condition_dropout", "keep")
|
| 199 |
+
ablation = getattr(args, "condition_ablation", "none")
|
| 200 |
+
effective_prompt = str(row["prompt"])
|
| 201 |
+
canvas_size = None
|
| 202 |
+
if ablation != "none":
|
| 203 |
+
effective_prompt, canvas_size = fixed_ablation_inputs(row, ablation)
|
| 204 |
+
base.update(condition_ablation=ablation,
|
| 205 |
+
condition_ablation_version="wgsr_v9_executor_input_ablation_v1",
|
| 206 |
+
original_prompt_sha256=base["prompt_sha256"],
|
| 207 |
+
prompt=effective_prompt, prompt_sha256=sha256_bytes(effective_prompt.encode()),
|
| 208 |
+
source_image_conditioning=ablation != "no_image",
|
| 209 |
+
source_image_opened_by_runner=ablation != "no_image")
|
| 210 |
+
if action == "drop_text":
|
| 211 |
+
from ..executor_dropout import drop_cot
|
| 212 |
+
effective_prompt = drop_cot(effective_prompt)
|
| 213 |
+
if action != "keep":
|
| 214 |
+
base.update(condition_dropout=action, original_prompt_sha256=base["prompt_sha256"],
|
| 215 |
+
prompt=effective_prompt, prompt_sha256=sha256_bytes(effective_prompt.encode()))
|
| 216 |
+
try:
|
| 217 |
+
if ablation == "no_image":
|
| 218 |
+
source = None
|
| 219 |
+
width, height = canvas_size
|
| 220 |
+
else:
|
| 221 |
+
if not source_path.is_file():
|
| 222 |
+
raise FileNotFoundError(source_path)
|
| 223 |
+
base["source_sha256"] = sha256_file(source_path)
|
| 224 |
+
with Image.open(source_path) as source_file:
|
| 225 |
+
source = source_file.convert("RGB")
|
| 226 |
+
width, height = expected_source_size(row, source)
|
| 227 |
+
generator = torch.Generator(device="cuda").manual_seed(int(base["seed"]))
|
| 228 |
+
with torch.inference_mode():
|
| 229 |
+
result = pipe(
|
| 230 |
+
prompt=effective_prompt,
|
| 231 |
+
image=None if action == "drop_image" else source,
|
| 232 |
+
width=width,
|
| 233 |
+
height=height,
|
| 234 |
+
output_resolution=round(math.sqrt(width * height)),
|
| 235 |
+
num_inference_steps=args.steps,
|
| 236 |
+
true_cfg_scale=1.0,
|
| 237 |
+
generator=generator,
|
| 238 |
+
use_kv_cache=args.use_kv_cache,
|
| 239 |
+
)
|
| 240 |
+
generated_image = result.images[0]
|
| 241 |
+
if generated_image.size != (width, height):
|
| 242 |
+
raise ValueError(
|
| 243 |
+
f"pipeline returned {generated_image.size}, expected {(width, height)}"
|
| 244 |
+
)
|
| 245 |
+
temporary = output_path.with_name(f".{output_path.name}.{os.getpid()}.tmp")
|
| 246 |
+
generated_image.save(temporary, format="PNG")
|
| 247 |
+
os.replace(temporary, output_path)
|
| 248 |
+
base.update(
|
| 249 |
+
status="completed",
|
| 250 |
+
error=None,
|
| 251 |
+
output_size=list(generated_image.size),
|
| 252 |
+
output_mode=generated_image.mode,
|
| 253 |
+
output_bytes=output_path.stat().st_size,
|
| 254 |
+
output_sha256=sha256_file(output_path),
|
| 255 |
+
elapsed_seconds=round(time.time() - started, 4),
|
| 256 |
+
completed_at_utc=utc_now(),
|
| 257 |
+
)
|
| 258 |
+
generated += 1
|
| 259 |
+
print(
|
| 260 |
+
f"rank={args.rank} completed row={index} "
|
| 261 |
+
f"sec={base['elapsed_seconds']:.1f}",
|
| 262 |
+
flush=True,
|
| 263 |
+
)
|
| 264 |
+
except Exception as exc: # preserve a resumable failure record
|
| 265 |
+
temporary = output_path.with_name(f".{output_path.name}.{os.getpid()}.tmp")
|
| 266 |
+
if temporary.exists():
|
| 267 |
+
temporary.unlink()
|
| 268 |
+
base.update(
|
| 269 |
+
status="failed",
|
| 270 |
+
error=f"{type(exc).__name__}: {exc}",
|
| 271 |
+
elapsed_seconds=round(time.time() - started, 4),
|
| 272 |
+
completed_at_utc=utc_now(),
|
| 273 |
+
)
|
| 274 |
+
failed += 1
|
| 275 |
+
print(f"rank={args.rank} FAILED row={index}: {base['error']}", flush=True)
|
| 276 |
+
append_jsonl(ledger, base)
|
| 277 |
+
write_json(
|
| 278 |
+
rank_dir / "worker_manifest.json",
|
| 279 |
+
{
|
| 280 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 281 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 282 |
+
"variant": args.variant,
|
| 283 |
+
"rank": args.rank,
|
| 284 |
+
"world_size": args.world_size,
|
| 285 |
+
"input_manifest": str(args.input_manifest),
|
| 286 |
+
"input_manifest_sha256": input_sha,
|
| 287 |
+
"seed_manifest": str(args.seed_manifest) if args.seed_manifest else None,
|
| 288 |
+
"seed_manifest_sha256": seed_sha,
|
| 289 |
+
"checkpoint": str(args.checkpoint) if args.checkpoint is not None else None,
|
| 290 |
+
"checkpoint_sha256": args.run_identity["checkpoint_sha256"],
|
| 291 |
+
**({"pretrained_transformer": args.run_identity["pretrained_transformer"]}
|
| 292 |
+
if args.checkpoint is None else {}),
|
| 293 |
+
"transformer_loading_info": loading,
|
| 294 |
+
"dtype": str(dtype),
|
| 295 |
+
"assigned_rows": len(assigned),
|
| 296 |
+
"generated_rows": generated,
|
| 297 |
+
"failed_rows": failed,
|
| 298 |
+
"finished_at_utc": utc_now(),
|
| 299 |
+
},
|
| 300 |
+
)
|
| 301 |
+
return 1 if failed else 0
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def nvidia_memory() -> dict[str, int]:
|
| 305 |
+
output = subprocess.check_output(
|
| 306 |
+
["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"],
|
| 307 |
+
text=True,
|
| 308 |
+
)
|
| 309 |
+
values: dict[str, int] = {}
|
| 310 |
+
for line in output.splitlines():
|
| 311 |
+
if line.strip():
|
| 312 |
+
index, used = line.split(",", 1)
|
| 313 |
+
values[index.strip()] = int(used.strip())
|
| 314 |
+
return values
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def latest_records(paths: Iterable[Path]) -> dict[int, dict[str, Any]]:
|
| 318 |
+
latest: dict[int, dict[str, Any]] = {}
|
| 319 |
+
for path in paths:
|
| 320 |
+
for record in read_optional_jsonl(path):
|
| 321 |
+
latest[int(record["row_index"])] = record
|
| 322 |
+
return latest
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def consolidate(
|
| 326 |
+
args: argparse.Namespace,
|
| 327 |
+
rows: list[dict[str, Any]],
|
| 328 |
+
input_sha: str,
|
| 329 |
+
seed_sha: str | None,
|
| 330 |
+
) -> dict[str, Any]:
|
| 331 |
+
ledgers = [
|
| 332 |
+
args.output_root / f"rank-{rank:02d}" / "results.jsonl"
|
| 333 |
+
for rank in range(args.world_size)
|
| 334 |
+
]
|
| 335 |
+
records_by_index = latest_records(ledgers)
|
| 336 |
+
expected = {int(row["inference_row_index"]): input_hash(row) for row in rows}
|
| 337 |
+
records_by_index = {index: record for index, record in records_by_index.items() if index in expected}
|
| 338 |
+
for index, record in list(records_by_index.items()):
|
| 339 |
+
stale = record.get("input_sha256") != expected[index]
|
| 340 |
+
if getattr(args, "run_identity_sha256", None) is not None:
|
| 341 |
+
stale |= record.get("run_identity_sha256") != args.run_identity_sha256
|
| 342 |
+
missing_output = not Path(record.get("output_path") or "").is_file()
|
| 343 |
+
if stale or missing_output:
|
| 344 |
+
records_by_index[index] = {**record, "status": "failed",
|
| 345 |
+
"error": "stale input/run identity or missing output: result does not match this run"}
|
| 346 |
+
records = [records_by_index[index] for index in sorted(records_by_index)]
|
| 347 |
+
successful = [record for record in records if record.get("status") == "completed"]
|
| 348 |
+
failed = [record for record in records if record.get("status") != "completed"]
|
| 349 |
+
expected_indices = {int(row["inference_row_index"]) for row in rows}
|
| 350 |
+
successful_indices = {int(record["row_index"]) for record in successful}
|
| 351 |
+
missing = sorted(expected_indices - successful_indices)
|
| 352 |
+
results_path = args.output_root / "results.jsonl"
|
| 353 |
+
records_json = "".join(
|
| 354 |
+
json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n"
|
| 355 |
+
for record in records
|
| 356 |
+
)
|
| 357 |
+
temporary = results_path.with_name(f".{results_path.name}.{os.getpid()}.tmp")
|
| 358 |
+
with temporary.open("w", encoding="utf-8") as handle:
|
| 359 |
+
handle.write(records_json)
|
| 360 |
+
handle.flush()
|
| 361 |
+
os.fsync(handle.fileno())
|
| 362 |
+
os.replace(temporary, results_path)
|
| 363 |
+
status = (
|
| 364 |
+
"complete"
|
| 365 |
+
if not missing and not failed and len(successful) == len(expected_indices)
|
| 366 |
+
else "complete_with_failures"
|
| 367 |
+
)
|
| 368 |
+
manifest = {
|
| 369 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 370 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 371 |
+
"status": status,
|
| 372 |
+
"variant": args.variant,
|
| 373 |
+
"split": "val",
|
| 374 |
+
"input_manifest": str(args.input_manifest.resolve()),
|
| 375 |
+
"input_manifest_sha256": input_sha,
|
| 376 |
+
"selected_rows": len(rows),
|
| 377 |
+
"successful_rows": len(successful),
|
| 378 |
+
"failed_rows": len(failed),
|
| 379 |
+
"missing_rows": missing,
|
| 380 |
+
"results": str(results_path.resolve()),
|
| 381 |
+
"results_sha256": sha256_file(results_path),
|
| 382 |
+
"checkpoint": str(args.checkpoint.resolve()) if args.checkpoint is not None else None,
|
| 383 |
+
"checkpoint_sha256": sha256_file(args.checkpoint) if args.checkpoint is not None else None,
|
| 384 |
+
"model_path": str(args.model_path.resolve()),
|
| 385 |
+
"world_size": args.world_size,
|
| 386 |
+
"gpu_ids": args.gpu_ids,
|
| 387 |
+
"steps": args.steps,
|
| 388 |
+
"seed_base": args.seed_base,
|
| 389 |
+
"seed_manifest": str(args.seed_manifest.resolve()) if args.seed_manifest else None,
|
| 390 |
+
"seed_manifest_sha256": seed_sha,
|
| 391 |
+
"dtype": args.dtype,
|
| 392 |
+
"use_kv_cache": bool(args.use_kv_cache),
|
| 393 |
+
"source_only": True,
|
| 394 |
+
"target_usage": "eval_reference_only",
|
| 395 |
+
"target_image_opened_by_runner": False,
|
| 396 |
+
"conditioning_source": "teacher_reference" if args.variant == "teacher_cot" else args.variant,
|
| 397 |
+
"target_informed_conditioning": args.variant == "teacher_cot",
|
| 398 |
+
"run_identity": getattr(args, "run_identity", None),
|
| 399 |
+
"run_identity_sha256": getattr(args, "run_identity_sha256", None),
|
| 400 |
+
"finished_at_utc": utc_now(),
|
| 401 |
+
}
|
| 402 |
+
write_json(args.output_root / "inference_manifest.json", manifest)
|
| 403 |
+
return manifest
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def supervisor_main(args: argparse.Namespace) -> int:
|
| 407 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 408 |
+
lock_path = args.output_root / "inference.lock"
|
| 409 |
+
with lock_path.open("a+") as lock:
|
| 410 |
+
try:
|
| 411 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 412 |
+
except BlockingIOError as exc:
|
| 413 |
+
raise RuntimeError(f"another inference supervisor owns {lock_path}") from exc
|
| 414 |
+
return _supervisor_locked(args)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _supervisor_locked(args: argparse.Namespace) -> int:
|
| 418 |
+
rows, input_sha = load_input_rows(args.input_manifest, parse_indices(args.row_indices))
|
| 419 |
+
validate_input_contract(args, rows)
|
| 420 |
+
_, seed_sha = load_seed_map(args.seed_manifest)
|
| 421 |
+
args.run_identity = run_identity(args, rows, input_sha, seed_sha)
|
| 422 |
+
args.run_identity_sha256 = canonical_sha256(args.run_identity)
|
| 423 |
+
if args.steps != 20:
|
| 424 |
+
raise ValueError("the reviewed Qwen Image 2.1 inference contract requires exactly 20 steps")
|
| 425 |
+
gpu_ids = select_gpu_ids(args.gpu_ids)
|
| 426 |
+
if len(gpu_ids) != args.world_size:
|
| 427 |
+
raise ValueError(f"world size {args.world_size} does not match GPU list {gpu_ids}")
|
| 428 |
+
manifest_path = args.output_root / "inference_manifest.json"
|
| 429 |
+
checkpoint_sha = args.run_identity["checkpoint_sha256"]
|
| 430 |
+
previous_path = manifest_path if manifest_path.exists() else args.output_root / "supervisor_manifest.json"
|
| 431 |
+
if previous_path.exists() and not args.overwrite:
|
| 432 |
+
previous = json.loads(previous_path.read_text(encoding="utf-8"))
|
| 433 |
+
validate_resume(previous, args.run_identity)
|
| 434 |
+
if previous.get("status") == "complete":
|
| 435 |
+
checked = consolidate(args, rows, input_sha, seed_sha)
|
| 436 |
+
if checked["status"] == "complete":
|
| 437 |
+
print(f"inference already complete: {manifest_path}", flush=True)
|
| 438 |
+
return 0
|
| 439 |
+
memory = nvidia_memory()
|
| 440 |
+
if any(gpu not in memory for gpu in gpu_ids):
|
| 441 |
+
raise RuntimeError("selected GPU is unavailable")
|
| 442 |
+
busy = {gpu: memory[gpu] for gpu in gpu_ids if memory[gpu] >= 1024}
|
| 443 |
+
if busy:
|
| 444 |
+
raise RuntimeError(f"selected GPUs are occupied above 1 GiB: {busy}")
|
| 445 |
+
view = make_transformer_view(args.model_path, args.checkpoint, args.output_root)
|
| 446 |
+
planned = {
|
| 447 |
+
"algorithm_version": ALGORITHM_VERSION,
|
| 448 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 449 |
+
"status": "running",
|
| 450 |
+
"variant": args.variant,
|
| 451 |
+
"input_manifest": str(args.input_manifest.resolve()),
|
| 452 |
+
"input_manifest_sha256": input_sha,
|
| 453 |
+
"selected_rows": len(rows),
|
| 454 |
+
"checkpoint": str(args.checkpoint.resolve()) if args.checkpoint is not None else None,
|
| 455 |
+
"checkpoint_sha256": checkpoint_sha,
|
| 456 |
+
"model_path": str(args.model_path.resolve()),
|
| 457 |
+
"transformer_view": str(view.resolve()),
|
| 458 |
+
"world_size": args.world_size,
|
| 459 |
+
"gpu_ids": args.gpu_ids,
|
| 460 |
+
"steps": args.steps,
|
| 461 |
+
"seed_base": args.seed_base,
|
| 462 |
+
"seed_manifest": str(args.seed_manifest.resolve()) if args.seed_manifest else None,
|
| 463 |
+
"seed_manifest_sha256": seed_sha,
|
| 464 |
+
"dtype": args.dtype,
|
| 465 |
+
"use_kv_cache": bool(args.use_kv_cache),
|
| 466 |
+
"source_only": True,
|
| 467 |
+
"target_usage": "eval_reference_only",
|
| 468 |
+
"target_image_opened_by_runner": False,
|
| 469 |
+
"conditioning_source": "teacher_reference" if args.variant == "teacher_cot" else args.variant,
|
| 470 |
+
"target_informed_conditioning": args.variant == "teacher_cot",
|
| 471 |
+
"run_identity": args.run_identity,
|
| 472 |
+
"run_identity_sha256": args.run_identity_sha256,
|
| 473 |
+
"started_at_utc": utc_now(),
|
| 474 |
+
}
|
| 475 |
+
write_json(args.output_root / "supervisor_manifest.json", planned)
|
| 476 |
+
processes: list[tuple[int, subprocess.Popen[Any]]] = []
|
| 477 |
+
jobs: list[dict[str, Any]] = []
|
| 478 |
+
for rank, gpu_id in enumerate(gpu_ids):
|
| 479 |
+
env = {
|
| 480 |
+
**os.environ,
|
| 481 |
+
"CUDA_VISIBLE_DEVICES": gpu_id,
|
| 482 |
+
"OMP_NUM_THREADS": "4",
|
| 483 |
+
"MKL_NUM_THREADS": "4",
|
| 484 |
+
"OPENBLAS_NUM_THREADS": "4",
|
| 485 |
+
"TOKENIZERS_PARALLELISM": "false",
|
| 486 |
+
"HF_HUB_OFFLINE": "1",
|
| 487 |
+
"TRANSFORMERS_OFFLINE": "1",
|
| 488 |
+
"DIFFSYNTH_SKIP_DOWNLOAD": "True",
|
| 489 |
+
}
|
| 490 |
+
log_path = args.output_root / "logs" / f"worker-{rank:02d}.log"
|
| 491 |
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
| 492 |
+
log = log_path.open("a", encoding="utf-8")
|
| 493 |
+
command = [
|
| 494 |
+
sys.executable,
|
| 495 |
+
str(CLI_SCRIPT),
|
| 496 |
+
"--worker",
|
| 497 |
+
"--variant",
|
| 498 |
+
args.variant,
|
| 499 |
+
"--input-manifest",
|
| 500 |
+
str(args.input_manifest),
|
| 501 |
+
"--model-path",
|
| 502 |
+
str(args.model_path),
|
| 503 |
+
"--output-root",
|
| 504 |
+
str(args.output_root),
|
| 505 |
+
"--rank",
|
| 506 |
+
str(rank),
|
| 507 |
+
"--world-size",
|
| 508 |
+
str(args.world_size),
|
| 509 |
+
"--gpu-ids",
|
| 510 |
+
args.gpu_ids,
|
| 511 |
+
"--steps",
|
| 512 |
+
str(args.steps),
|
| 513 |
+
"--seed-base",
|
| 514 |
+
str(args.seed_base),
|
| 515 |
+
"--dtype",
|
| 516 |
+
args.dtype,
|
| 517 |
+
]
|
| 518 |
+
if args.checkpoint is None:
|
| 519 |
+
command.append("--pretrained")
|
| 520 |
+
else:
|
| 521 |
+
command.extend(("--checkpoint", str(args.checkpoint)))
|
| 522 |
+
if getattr(args, "config", None) is not None:
|
| 523 |
+
command.extend(("--config", str(args.config)))
|
| 524 |
+
if getattr(args, "condition_dropout", "keep") != "keep":
|
| 525 |
+
command.extend(("--condition-dropout", args.condition_dropout))
|
| 526 |
+
if getattr(args, "condition_ablation", "none") != "none":
|
| 527 |
+
command.extend(("--condition-ablation", args.condition_ablation))
|
| 528 |
+
if args.seed_manifest:
|
| 529 |
+
command.extend(("--seed-manifest", str(args.seed_manifest)))
|
| 530 |
+
if args.row_indices:
|
| 531 |
+
command.extend(("--row-indices", args.row_indices))
|
| 532 |
+
command.append("--use-kv-cache" if args.use_kv_cache else "--no-use-kv-cache")
|
| 533 |
+
if args.overwrite:
|
| 534 |
+
command.append("--overwrite")
|
| 535 |
+
process = subprocess.Popen(
|
| 536 |
+
command,
|
| 537 |
+
env=env,
|
| 538 |
+
stdout=log,
|
| 539 |
+
stderr=subprocess.STDOUT,
|
| 540 |
+
start_new_session=True,
|
| 541 |
+
)
|
| 542 |
+
log.close()
|
| 543 |
+
processes.append((rank, process))
|
| 544 |
+
jobs.append(
|
| 545 |
+
{
|
| 546 |
+
"rank": rank,
|
| 547 |
+
"gpu": gpu_id,
|
| 548 |
+
"pid": process.pid,
|
| 549 |
+
"log": str(log_path),
|
| 550 |
+
"status": "running",
|
| 551 |
+
"command": command,
|
| 552 |
+
}
|
| 553 |
+
)
|
| 554 |
+
while True:
|
| 555 |
+
for job, (_, process) in zip(jobs, processes):
|
| 556 |
+
code = process.poll()
|
| 557 |
+
if code is not None:
|
| 558 |
+
job.update(
|
| 559 |
+
status="completed" if code == 0 else "failed",
|
| 560 |
+
exit_code=code,
|
| 561 |
+
finished_at_utc=utc_now(),
|
| 562 |
+
)
|
| 563 |
+
write_json(args.output_root / "jobs.json", {"updated_at_utc": utc_now(), "jobs": jobs})
|
| 564 |
+
if all(process.poll() is not None for _, process in processes):
|
| 565 |
+
break
|
| 566 |
+
time.sleep(10)
|
| 567 |
+
manifest = consolidate(args, rows, input_sha, seed_sha)
|
| 568 |
+
planned.update(manifest, status=manifest["status"], jobs=jobs)
|
| 569 |
+
write_json(args.output_root / "supervisor_manifest.json", planned)
|
| 570 |
+
print(json.dumps(manifest, ensure_ascii=False, indent=2), flush=True)
|
| 571 |
+
return 0 if manifest["status"] == "complete" else 1
|
src/wgsr_v9/maize/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reusable input-contract helpers for the species-isolated maize pipeline."""
|
| 2 |
+
|
| 3 |
+
from .contract import (
|
| 4 |
+
CANONICAL_SOURCE_SIZE,
|
| 5 |
+
CANONICAL_TARGET_SIZE,
|
| 6 |
+
MAIZE_ALGORITHM_VERSION,
|
| 7 |
+
MAIZE_PROTOCOL_VERSION,
|
| 8 |
+
MAIZE_VIEW,
|
| 9 |
+
load_catalog,
|
| 10 |
+
load_stage_table,
|
| 11 |
+
)
|
| 12 |
+
from .geometry import normalize_geometry
|
| 13 |
+
from .naming import OUTPUT_NAMING_VERSION, maize_legacy_output_stem, maize_output_stem
|
| 14 |
+
from .cot import (
|
| 15 |
+
MAIZE_COT_ALGORITHM_VERSION,
|
| 16 |
+
MAIZE_COT_PROTOCOL_VERSION,
|
| 17 |
+
build_request,
|
| 18 |
+
render_cot,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"CANONICAL_SOURCE_SIZE",
|
| 23 |
+
"CANONICAL_TARGET_SIZE",
|
| 24 |
+
"MAIZE_ALGORITHM_VERSION",
|
| 25 |
+
"MAIZE_PROTOCOL_VERSION",
|
| 26 |
+
"MAIZE_VIEW",
|
| 27 |
+
"load_catalog",
|
| 28 |
+
"load_stage_table",
|
| 29 |
+
"normalize_geometry",
|
| 30 |
+
"OUTPUT_NAMING_VERSION",
|
| 31 |
+
"maize_output_stem",
|
| 32 |
+
"maize_legacy_output_stem",
|
| 33 |
+
"MAIZE_COT_ALGORITHM_VERSION",
|
| 34 |
+
"MAIZE_COT_PROTOCOL_VERSION",
|
| 35 |
+
"build_request",
|
| 36 |
+
"render_cot",
|
| 37 |
+
]
|
src/wgsr_v9/maize/contract.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Maize input contract and provenance joins.
|
| 2 |
+
|
| 3 |
+
The source archive and the design package are read-only inputs. This module
|
| 4 |
+
only parses their manifests and returns normalized records for downstream
|
| 5 |
+
materialization.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import csv
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path, PurePosixPath
|
| 14 |
+
from typing import Any, Iterable
|
| 15 |
+
from zipfile import ZipFile
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
MAIZE_ALGORITHM_VERSION = "wgsr_maize_input_materialization_v1"
|
| 19 |
+
MAIZE_PROTOCOL_VERSION = "wgsr_maize_sv1_input_v1"
|
| 20 |
+
MAIZE_VIEW = "sv1"
|
| 21 |
+
EXCLUDED_VIEW = "sv2"
|
| 22 |
+
CANONICAL_SOURCE_SIZE = (768, 1270)
|
| 23 |
+
CANONICAL_TARGET_SIZE = (768, 1280)
|
| 24 |
+
DESIGN_IMAGE_MANIFEST = "COT_Maize_Design_v2/data/image_manifest.csv"
|
| 25 |
+
DESIGN_MANUAL_REVIEW = "COT_Maize_Design_v2/data/manual_organ_review.csv"
|
| 26 |
+
DESIGN_STAGE_TABLE = "COT_Maize_Design_v2/protocol/STAGES.json"
|
| 27 |
+
RGB_MEMBER_PREFIX = "rgb/"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def sha256_bytes(value: bytes) -> str:
|
| 31 |
+
return hashlib.sha256(value).hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sha256_file(path: Path) -> str:
|
| 35 |
+
digest = hashlib.sha256()
|
| 36 |
+
with path.open("rb") as handle:
|
| 37 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 38 |
+
digest.update(chunk)
|
| 39 |
+
return digest.hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _csv_rows(data: bytes, source: str) -> list[dict[str, str]]:
|
| 43 |
+
text = data.decode("utf-8-sig")
|
| 44 |
+
rows = list(csv.DictReader(text.splitlines()))
|
| 45 |
+
if not rows:
|
| 46 |
+
raise ValueError(f"CSV has no rows: {source}")
|
| 47 |
+
if any(row.get(None) for row in rows):
|
| 48 |
+
raise ValueError(f"CSV contains extra unnamed columns: {source}")
|
| 49 |
+
return [{str(key): (value or "").strip() for key, value in row.items()} for row in rows]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_csv_file(path: Path) -> tuple[list[dict[str, str]], str]:
|
| 53 |
+
data = path.read_bytes()
|
| 54 |
+
return _csv_rows(data, str(path)), sha256_bytes(data)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_design_package(path: Path) -> tuple[list[dict[str, str]], dict[str, str]]:
|
| 58 |
+
with ZipFile(path) as archive:
|
| 59 |
+
manifest_bytes = archive.read(DESIGN_IMAGE_MANIFEST)
|
| 60 |
+
manual_bytes = archive.read(DESIGN_MANUAL_REVIEW)
|
| 61 |
+
stage_bytes = archive.read(DESIGN_STAGE_TABLE)
|
| 62 |
+
return _csv_rows(manifest_bytes, DESIGN_IMAGE_MANIFEST), {
|
| 63 |
+
"image_manifest_sha256": sha256_bytes(manifest_bytes),
|
| 64 |
+
"manual_review_sha256": sha256_bytes(manual_bytes),
|
| 65 |
+
"stage_table_sha256": sha256_bytes(stage_bytes),
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def load_stage_table(path: Path) -> dict[str, dict[str, Any]]:
|
| 70 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 71 |
+
stages = value.get("stages") if isinstance(value, dict) else None
|
| 72 |
+
if not isinstance(stages, list) or not stages:
|
| 73 |
+
raise ValueError(f"Invalid maize stage table: {path}")
|
| 74 |
+
result: dict[str, dict[str, Any]] = {}
|
| 75 |
+
for stage in stages:
|
| 76 |
+
if not isinstance(stage, dict):
|
| 77 |
+
raise ValueError(f"Invalid stage row in {path}")
|
| 78 |
+
stage_id = str(stage.get("stage_id", "")).strip()
|
| 79 |
+
if not stage_id or stage_id in result:
|
| 80 |
+
raise ValueError(f"Duplicate or missing stage_id in {path}: {stage_id!r}")
|
| 81 |
+
days = stage.get("days_after_sowing")
|
| 82 |
+
if not isinstance(days, int) or days < 0:
|
| 83 |
+
raise ValueError(f"Invalid days_after_sowing for {stage_id}")
|
| 84 |
+
result[stage_id] = dict(stage)
|
| 85 |
+
return result
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _required(row: dict[str, str], keys: Iterable[str], source: str) -> None:
|
| 89 |
+
missing = [key for key in keys if key not in row]
|
| 90 |
+
if missing:
|
| 91 |
+
raise ValueError(f"Missing columns {missing} in {source}")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _safe_relative_path(value: str) -> str:
|
| 95 |
+
path = PurePosixPath(value)
|
| 96 |
+
if path.is_absolute() or ".." in path.parts or not value:
|
| 97 |
+
raise ValueError(f"Unsafe relative image path: {value!r}")
|
| 98 |
+
return path.as_posix()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_catalog(
|
| 102 |
+
*,
|
| 103 |
+
design_zip: Path,
|
| 104 |
+
manual_path: Path,
|
| 105 |
+
stages_path: Path,
|
| 106 |
+
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
| 107 |
+
"""Join the design manifest, manual observations, and stage table.
|
| 108 |
+
|
| 109 |
+
The returned rows include both included and excluded manifest entries. A
|
| 110 |
+
caller must filter ``selection_status == included`` before materializing
|
| 111 |
+
images.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
manifest_rows, design_hashes = load_design_package(design_zip)
|
| 115 |
+
manual_rows, manual_sha256 = load_csv_file(manual_path)
|
| 116 |
+
if manual_sha256 != design_hashes["manual_review_sha256"]:
|
| 117 |
+
raise ValueError("External manual-review table differs from the design-package copy")
|
| 118 |
+
stages_sha256 = sha256_file(stages_path)
|
| 119 |
+
if stages_sha256 != design_hashes["stage_table_sha256"]:
|
| 120 |
+
raise ValueError("External stage table differs from the design-package copy")
|
| 121 |
+
stage_table = load_stage_table(stages_path)
|
| 122 |
+
_required(
|
| 123 |
+
manifest_rows[0],
|
| 124 |
+
(
|
| 125 |
+
"image_id",
|
| 126 |
+
"plant_id",
|
| 127 |
+
"stage_id",
|
| 128 |
+
"days_after_sowing",
|
| 129 |
+
"maize_stage",
|
| 130 |
+
"view",
|
| 131 |
+
"relative_image_path",
|
| 132 |
+
"aligned_sha256",
|
| 133 |
+
"alignment_flags",
|
| 134 |
+
"alignment_needs_review",
|
| 135 |
+
"selection_status",
|
| 136 |
+
"selection_reason",
|
| 137 |
+
),
|
| 138 |
+
DESIGN_IMAGE_MANIFEST,
|
| 139 |
+
)
|
| 140 |
+
_required(
|
| 141 |
+
manual_rows[0],
|
| 142 |
+
(
|
| 143 |
+
"image_id",
|
| 144 |
+
"plant_id",
|
| 145 |
+
"stage_id",
|
| 146 |
+
"days_after_sowing",
|
| 147 |
+
"maize_stage",
|
| 148 |
+
"tassel_presence",
|
| 149 |
+
"ear_presence",
|
| 150 |
+
"plant_condition",
|
| 151 |
+
),
|
| 152 |
+
str(manual_path),
|
| 153 |
+
)
|
| 154 |
+
manifest_by_id = {row["image_id"]: row for row in manifest_rows}
|
| 155 |
+
manual_by_id = {row["image_id"]: row for row in manual_rows}
|
| 156 |
+
if len(manifest_by_id) != len(manifest_rows):
|
| 157 |
+
raise ValueError("Duplicate image_id in maize image manifest")
|
| 158 |
+
if len(manual_by_id) != len(manual_rows):
|
| 159 |
+
raise ValueError("Duplicate image_id in maize manual review")
|
| 160 |
+
|
| 161 |
+
included_ids = {
|
| 162 |
+
row["image_id"] for row in manifest_rows if row["selection_status"] == "included"
|
| 163 |
+
}
|
| 164 |
+
if included_ids != set(manual_by_id):
|
| 165 |
+
missing = sorted(included_ids.difference(manual_by_id))[:3]
|
| 166 |
+
extra = sorted(set(manual_by_id).difference(included_ids))[:3]
|
| 167 |
+
raise ValueError(f"Manual/image join mismatch; missing={missing}, extra={extra}")
|
| 168 |
+
|
| 169 |
+
joined: list[dict[str, Any]] = []
|
| 170 |
+
for manifest in manifest_rows:
|
| 171 |
+
image_id = manifest["image_id"]
|
| 172 |
+
stage_id = manifest["stage_id"]
|
| 173 |
+
stage = stage_table.get(stage_id)
|
| 174 |
+
if stage is None:
|
| 175 |
+
raise ValueError(f"Unknown maize stage {stage_id!r} for {image_id}")
|
| 176 |
+
try:
|
| 177 |
+
days = int(manifest["days_after_sowing"])
|
| 178 |
+
except ValueError as exc:
|
| 179 |
+
raise ValueError(f"Invalid DAS for {image_id}") from exc
|
| 180 |
+
if days != stage["days_after_sowing"]:
|
| 181 |
+
raise ValueError(f"DAS mismatch for {image_id}: {days} != {stage['days_after_sowing']}")
|
| 182 |
+
if manifest["maize_stage"] != str(stage.get("maize_stage", "")):
|
| 183 |
+
raise ValueError(f"Maize stage mismatch for {image_id}: {manifest['maize_stage']}")
|
| 184 |
+
relative = _safe_relative_path(manifest["relative_image_path"])
|
| 185 |
+
view = manifest["view"]
|
| 186 |
+
if view != MAIZE_VIEW:
|
| 187 |
+
status = "excluded_view" if view == EXCLUDED_VIEW else "excluded_unknown_view"
|
| 188 |
+
else:
|
| 189 |
+
status = manifest["selection_status"]
|
| 190 |
+
manual = manual_by_id.get(image_id, {})
|
| 191 |
+
for field in ("tassel_presence", "ear_presence"):
|
| 192 |
+
value = manual.get(field, "")
|
| 193 |
+
if value not in {"", "visible", "not_visible"}:
|
| 194 |
+
raise ValueError(f"Invalid {field}={value!r} for {image_id}")
|
| 195 |
+
review = str(manifest.get("alignment_needs_review", "")).strip() == "1"
|
| 196 |
+
flags = str(manifest.get("alignment_flags", "")).strip()
|
| 197 |
+
quality_stratum = (
|
| 198 |
+
"excluded" if status != "included" else ("alignment_review" if review or flags else "strict_alignment")
|
| 199 |
+
)
|
| 200 |
+
joined.append(
|
| 201 |
+
{
|
| 202 |
+
"species": "maize",
|
| 203 |
+
"image_id": image_id,
|
| 204 |
+
"plant_id": manifest["plant_id"],
|
| 205 |
+
"stage_id": stage_id,
|
| 206 |
+
"days_after_sowing": days,
|
| 207 |
+
"maize_stage": manifest["maize_stage"],
|
| 208 |
+
"view": view,
|
| 209 |
+
"relative_image_path": relative,
|
| 210 |
+
"source_archive_member": RGB_MEMBER_PREFIX + relative,
|
| 211 |
+
"manifest_aligned_sha256": manifest["aligned_sha256"],
|
| 212 |
+
"alignment_flags": flags,
|
| 213 |
+
"alignment_needs_review": review,
|
| 214 |
+
"selection_status": status,
|
| 215 |
+
"selection_reason": manifest.get("selection_reason", ""),
|
| 216 |
+
"tassel_presence": manual.get("tassel_presence", "") or None,
|
| 217 |
+
"ear_presence": manual.get("ear_presence", "") or None,
|
| 218 |
+
"plant_condition": manual.get("plant_condition", "") or None,
|
| 219 |
+
"quality_stratum": quality_stratum,
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
provenance = {
|
| 223 |
+
"design_package": str(design_zip.resolve()),
|
| 224 |
+
"design_package_sha256": sha256_file(design_zip),
|
| 225 |
+
"design_inner_sha256": design_hashes,
|
| 226 |
+
"manual_review_path": str(manual_path.resolve()),
|
| 227 |
+
"manual_review_sha256": manual_sha256,
|
| 228 |
+
"stage_table_path": str(stages_path.resolve()),
|
| 229 |
+
"stage_table_sha256": stages_sha256,
|
| 230 |
+
"stage_ids": sorted(stage_table, key=lambda item: int(item[1:])),
|
| 231 |
+
}
|
| 232 |
+
return joined, provenance
|
src/wgsr_v9/maize/cot.py
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline maize sv1 CoT request construction and deterministic rendering.
|
| 2 |
+
|
| 3 |
+
The provider request schema is kept separate from the operational request
|
| 4 |
+
ledger. The former remains a closed teacher contract; the latter records
|
| 5 |
+
status, paths, errors, and retry information needed for resumable runs.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import re
|
| 14 |
+
from decimal import Decimal, ROUND_HALF_UP
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any, Mapping
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
MAIZE_COT_ALGORITHM_VERSION = "wgsr_maize_sv1_cot_request_renderer_v2"
|
| 20 |
+
MAIZE_COT_PROTOCOL_VERSION = "wgsr_maize_sv1_cot_v2_en_v2"
|
| 21 |
+
PUBLIC_KEYS = (
|
| 22 |
+
"culm",
|
| 23 |
+
"leaves_area",
|
| 24 |
+
"plant_density",
|
| 25 |
+
"tassel",
|
| 26 |
+
"ear",
|
| 27 |
+
"plant_color_development",
|
| 28 |
+
)
|
| 29 |
+
METRIC_KEYS = ("culm", "leaves_area", "plant_density", "plant_color_development")
|
| 30 |
+
STATUSES = {"available", "provisional", "pending", "invalid", "not_applicable"}
|
| 31 |
+
MANUAL_STATUSES = {"visible", "not_visible", "pending"}
|
| 32 |
+
CONDITIONS = {"", "枯萎或干枯", "倒伏或残株"}
|
| 33 |
+
CONDITION_TRANSLATIONS = {
|
| 34 |
+
"枯萎或干枯": "wilted or dried",
|
| 35 |
+
"倒伏或残株": "lodged or plant remnant",
|
| 36 |
+
}
|
| 37 |
+
_HAN_TEXT = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]")
|
| 38 |
+
ANNOTATION_QC_VERSION = "wgsr_maize_annotation_qc_v2_no_refusal"
|
| 39 |
+
REFUSAL_TEXT = re.compile(
|
| 40 |
+
r"\b(?:I|we)\s+(?:(?:therefore|also|still)\s+)?(?:cannot|can['’]t|am unable|are unable)\b"
|
| 41 |
+
r"|\b(?:refusal|service boundary|ongoing restriction|this service does not support|as an AI)\b",
|
| 42 |
+
re.IGNORECASE,
|
| 43 |
+
)
|
| 44 |
+
_BANNED_TEXT = re.compile(
|
| 45 |
+
r"\d|[%/\\]|\b(?:pixels?|masks?|coordinates?|LAI|LAD|SPAD|chlorophyll|biomass)\b"
|
| 46 |
+
r"|\b(?:pending|invalid|not_applicable)\b|Source\s*=|Target\s*=|Change\s*="
|
| 47 |
+
r"|\b(?:fertili[sz]e|pesticide|irrigate)\b"
|
| 48 |
+
r"|\b(?:one|two|three|four|five|six|seven|eight|nine|ten)\s+leaves\b"
|
| 49 |
+
r"|[零一二三四五六七八九十百]+[片张枚]?[叶穗]|像素|掩膜|叶面积指数|叶绿素|施肥|灌溉",
|
| 50 |
+
re.IGNORECASE,
|
| 51 |
+
)
|
| 52 |
+
_METRIC_RANGES = {
|
| 53 |
+
"culm": (0.0, 100.0),
|
| 54 |
+
"leaves_area": (0.0, 100.0),
|
| 55 |
+
"plant_density": (0.0, 1.0),
|
| 56 |
+
"plant_color_development": (0.0, 1.0),
|
| 57 |
+
}
|
| 58 |
+
_LABELS = {
|
| 59 |
+
"culm": "Culm",
|
| 60 |
+
"leaves_area": "Visible foreground area",
|
| 61 |
+
"plant_density": "Projected fill",
|
| 62 |
+
"tassel": "Tassel",
|
| 63 |
+
"ear": "Ear",
|
| 64 |
+
"plant_color_development": "Visible yellow-brown composition",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def read_json(path: Path) -> Any:
|
| 69 |
+
return json.loads(path.read_text(encoding="utf-8-sig"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def protocol_version(protocol_root: Path) -> str:
|
| 73 |
+
return "wgsr_" + str(read_json(protocol_root / "COT_RENDERER_TEMPLATE.json")["template_version"])
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _stage_description(stage: Mapping[str, Any]) -> str:
|
| 77 |
+
return str(stage.get("visible_description_en", stage.get("visible_description_zh", "")))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def protocol_sha256(protocol_root: Path) -> str:
|
| 81 |
+
"""Hash every protocol file by relative name and bytes."""
|
| 82 |
+
|
| 83 |
+
digest = hashlib.sha256()
|
| 84 |
+
for path in sorted(item for item in protocol_root.rglob("*") if item.is_file()):
|
| 85 |
+
digest.update(path.relative_to(protocol_root).as_posix().encode("utf-8"))
|
| 86 |
+
digest.update(b"\0")
|
| 87 |
+
digest.update(path.read_bytes())
|
| 88 |
+
digest.update(b"\0")
|
| 89 |
+
return digest.hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _stages(protocol_root: Path) -> dict[str, dict[str, Any]]:
|
| 93 |
+
value = read_json(protocol_root / "STAGES.json")
|
| 94 |
+
rows = value.get("stages") if isinstance(value, dict) else None
|
| 95 |
+
if not isinstance(rows, list) or not rows:
|
| 96 |
+
raise ValueError("maize CoT stage table is empty")
|
| 97 |
+
result: dict[str, dict[str, Any]] = {}
|
| 98 |
+
for row in rows:
|
| 99 |
+
if not isinstance(row, dict):
|
| 100 |
+
raise ValueError("maize CoT stage row must be an object")
|
| 101 |
+
stage_id = str(row.get("stage_id", "")).strip()
|
| 102 |
+
if not stage_id or stage_id in result:
|
| 103 |
+
raise ValueError(f"duplicate or missing maize stage: {stage_id!r}")
|
| 104 |
+
result[stage_id] = row
|
| 105 |
+
return result
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _bindings(protocol_root: Path) -> dict[str, Any]:
|
| 109 |
+
value = read_json(protocol_root / "VIEW_VARIABLE_BINDINGS.json")
|
| 110 |
+
fields = value.get("fields") if isinstance(value, dict) else None
|
| 111 |
+
if not isinstance(fields, dict):
|
| 112 |
+
raise ValueError("maize CoT bindings have no fields object")
|
| 113 |
+
return fields
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _schema_issues(value: Any, filename: str, protocol_root: Path) -> list[str]:
|
| 117 |
+
"""Validate the local JSON-schema subset used by the maize package."""
|
| 118 |
+
|
| 119 |
+
cache: dict[Path, Any] = {}
|
| 120 |
+
root = protocol_root.resolve()
|
| 121 |
+
issues: list[str] = []
|
| 122 |
+
|
| 123 |
+
def load(name: str) -> Any:
|
| 124 |
+
path = (root / name).resolve()
|
| 125 |
+
if path.parent != root:
|
| 126 |
+
raise ValueError("maize schema references must stay inside the protocol root")
|
| 127 |
+
if path not in cache:
|
| 128 |
+
cache[path] = read_json(path)
|
| 129 |
+
return cache[path]
|
| 130 |
+
|
| 131 |
+
def matches(item: Any, kind: str) -> bool:
|
| 132 |
+
if kind == "null":
|
| 133 |
+
return item is None
|
| 134 |
+
if kind == "boolean":
|
| 135 |
+
return isinstance(item, bool)
|
| 136 |
+
if kind == "integer":
|
| 137 |
+
return isinstance(item, int) and not isinstance(item, bool)
|
| 138 |
+
if kind == "number":
|
| 139 |
+
return isinstance(item, (int, float)) and not isinstance(item, bool) and math.isfinite(float(item))
|
| 140 |
+
if kind == "object":
|
| 141 |
+
return isinstance(item, dict)
|
| 142 |
+
if kind == "array":
|
| 143 |
+
return isinstance(item, list)
|
| 144 |
+
if kind == "string":
|
| 145 |
+
return isinstance(item, str)
|
| 146 |
+
return False
|
| 147 |
+
|
| 148 |
+
def visit(item: Any, schema: Mapping[str, Any], document: Any, location: str) -> None:
|
| 149 |
+
reference = schema.get("$ref")
|
| 150 |
+
if reference:
|
| 151 |
+
filename_ref, _, fragment = str(reference).partition("#")
|
| 152 |
+
referenced_document = load(filename_ref) if filename_ref else document
|
| 153 |
+
resolved: Any = referenced_document
|
| 154 |
+
for part in fragment.strip("/").split("/") if fragment else []:
|
| 155 |
+
resolved = resolved[part.replace("~1", "/").replace("~0", "~")]
|
| 156 |
+
visit(item, resolved, referenced_document, location)
|
| 157 |
+
return
|
| 158 |
+
kinds = schema.get("type")
|
| 159 |
+
if kinds:
|
| 160 |
+
allowed = [kinds] if isinstance(kinds, str) else kinds
|
| 161 |
+
if not any(matches(item, kind) for kind in allowed):
|
| 162 |
+
issues.append(f"{location}: expected {kinds}")
|
| 163 |
+
return
|
| 164 |
+
if "enum" in schema and item not in schema["enum"]:
|
| 165 |
+
issues.append(f"{location}: invalid enum value")
|
| 166 |
+
if "const" in schema and item != schema["const"]:
|
| 167 |
+
issues.append(f"{location}: unexpected constant")
|
| 168 |
+
if isinstance(item, str) and len(item) < int(schema.get("minLength", 0)):
|
| 169 |
+
issues.append(f"{location}: text too short")
|
| 170 |
+
if isinstance(item, dict):
|
| 171 |
+
for key in schema.get("required", []):
|
| 172 |
+
if key not in item:
|
| 173 |
+
issues.append(f"{location}: missing {key}")
|
| 174 |
+
properties = schema.get("properties", {})
|
| 175 |
+
for key, child in item.items():
|
| 176 |
+
if key in properties:
|
| 177 |
+
visit(child, properties[key], document, f"{location}.{key}")
|
| 178 |
+
elif schema.get("additionalProperties") is False:
|
| 179 |
+
issues.append(f"{location}: extra {key}")
|
| 180 |
+
if isinstance(item, (int, float)) and not isinstance(item, bool):
|
| 181 |
+
if not math.isfinite(float(item)):
|
| 182 |
+
issues.append(f"{location}: non-finite number")
|
| 183 |
+
if float(item) < float(schema.get("minimum", -math.inf)):
|
| 184 |
+
issues.append(f"{location}: below minimum")
|
| 185 |
+
if float(item) > float(schema.get("maximum", math.inf)):
|
| 186 |
+
issues.append(f"{location}: above maximum")
|
| 187 |
+
if isinstance(item, list):
|
| 188 |
+
if schema.get("uniqueItems") and any(item[i] in item[:i] for i in range(len(item))):
|
| 189 |
+
issues.append(f"{location}: duplicate items")
|
| 190 |
+
child_schema = schema.get("items")
|
| 191 |
+
if isinstance(child_schema, dict):
|
| 192 |
+
for index, child in enumerate(item):
|
| 193 |
+
visit(child, child_schema, document, f"{location}[{index}]")
|
| 194 |
+
|
| 195 |
+
document = load(filename)
|
| 196 |
+
visit(value, document, document, "$")
|
| 197 |
+
return issues
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _resolved_path(value: Any, repo_root: Path) -> Path:
|
| 201 |
+
if value in (None, ""):
|
| 202 |
+
raise ValueError("maize request image path is missing")
|
| 203 |
+
path = Path(str(value))
|
| 204 |
+
return path.resolve() if path.is_absolute() else (repo_root / path).resolve()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _portable_or_absolute(path: Path, repo_root: Path) -> str:
|
| 208 |
+
try:
|
| 209 |
+
return path.resolve().relative_to(repo_root.resolve()).as_posix()
|
| 210 |
+
except ValueError:
|
| 211 |
+
return str(path.resolve())
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _endpoint(pair_endpoint: Mapping[str, Any], stages: Mapping[str, Mapping[str, Any]], *, repo_root: Path, check_images: bool) -> dict[str, Any]:
|
| 215 |
+
stage_id = str(pair_endpoint.get("stage_id", ""))
|
| 216 |
+
stage = stages.get(stage_id)
|
| 217 |
+
if stage is None:
|
| 218 |
+
raise ValueError(f"unknown maize stage in pair endpoint: {stage_id}")
|
| 219 |
+
image_id = str(pair_endpoint.get("image_id", ""))
|
| 220 |
+
plant_id = str(pair_endpoint.get("plant_id", ""))
|
| 221 |
+
if image_id != f"{plant_id}/{stage_id}_sv1":
|
| 222 |
+
raise ValueError(f"invalid maize image identity: {image_id}")
|
| 223 |
+
image_path = _resolved_path(pair_endpoint.get("path"), repo_root)
|
| 224 |
+
if check_images and not image_path.is_file():
|
| 225 |
+
raise FileNotFoundError(image_path)
|
| 226 |
+
image_sha256 = str(pair_endpoint.get("image_sha256") or "")
|
| 227 |
+
if not re.fullmatch(r"[0-9a-f]{64}", image_sha256):
|
| 228 |
+
raise ValueError(f"malformed image hash for {image_id}")
|
| 229 |
+
return {
|
| 230 |
+
"image_id": image_id,
|
| 231 |
+
"plant_id": plant_id,
|
| 232 |
+
"stage_id": stage_id,
|
| 233 |
+
"days_after_sowing": int(stage["days_after_sowing"]),
|
| 234 |
+
"maize_stage": str(stage["maize_stage"]),
|
| 235 |
+
"stage_description": _stage_description(stage),
|
| 236 |
+
"path": _portable_or_absolute(image_path, repo_root),
|
| 237 |
+
"image_sha256": image_sha256,
|
| 238 |
+
"plant_condition": (
|
| 239 |
+
CONDITION_TRANSLATIONS.get(pair_endpoint.get("plant_condition"), pair_endpoint.get("plant_condition"))
|
| 240 |
+
if "visible_description_en" in stage else pair_endpoint.get("plant_condition")
|
| 241 |
+
) or None,
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _manual_value(value: Any) -> str:
|
| 246 |
+
result = str(value or "pending")
|
| 247 |
+
return result if result in MANUAL_STATUSES else "pending"
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _observation(value: Mapping[str, Any] | None) -> dict[str, Any]:
|
| 251 |
+
value = value or {}
|
| 252 |
+
status = str(value.get("status", "pending"))
|
| 253 |
+
if status not in STATUSES:
|
| 254 |
+
status = "invalid"
|
| 255 |
+
observation_value = value.get("value") if status in {"available", "provisional"} else None
|
| 256 |
+
return {
|
| 257 |
+
"value": observation_value,
|
| 258 |
+
"status": status,
|
| 259 |
+
"image_sha256": value.get("image_sha256"),
|
| 260 |
+
"mask_sha256": value.get("mask_sha256"),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _request_metric(key: str, pair_metric: Mapping[str, Any] | None, bindings: Mapping[str, Any]) -> dict[str, Any]:
|
| 265 |
+
pair_metric = pair_metric or {}
|
| 266 |
+
source = _observation(pair_metric.get("source") if isinstance(pair_metric.get("source"), Mapping) else None)
|
| 267 |
+
target = _observation(pair_metric.get("target") if isinstance(pair_metric.get("target"), Mapping) else None)
|
| 268 |
+
versions = sorted(
|
| 269 |
+
{
|
| 270 |
+
str(item.get("algorithm_version"))
|
| 271 |
+
for item in (
|
| 272 |
+
pair_metric.get("source", {}),
|
| 273 |
+
pair_metric.get("target", {}),
|
| 274 |
+
)
|
| 275 |
+
if isinstance(item, Mapping) and item.get("algorithm_version")
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
+
reasons: set[str] = set()
|
| 279 |
+
for item in (pair_metric.get("source"), pair_metric.get("target")):
|
| 280 |
+
if isinstance(item, Mapping):
|
| 281 |
+
reasons.update(str(reason) for reason in item.get("reason_codes", []))
|
| 282 |
+
return {
|
| 283 |
+
"metric_key": str(bindings[key]["metric_key"]),
|
| 284 |
+
"source": source,
|
| 285 |
+
"target": target,
|
| 286 |
+
"unit": str(bindings[key]["unit"]),
|
| 287 |
+
"algorithm_version": ",".join(versions) or "unavailable",
|
| 288 |
+
"qc": {
|
| 289 |
+
"valid": source["status"] == "available" and target["status"] == "available",
|
| 290 |
+
"reason_codes": sorted(reasons),
|
| 291 |
+
},
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def build_request(
|
| 296 |
+
pair: Mapping[str, Any],
|
| 297 |
+
*,
|
| 298 |
+
protocol_root: Path,
|
| 299 |
+
repo_root: Path,
|
| 300 |
+
check_images: bool = True,
|
| 301 |
+
) -> dict[str, Any]:
|
| 302 |
+
"""Convert one species-specific pair row into a strict provider request."""
|
| 303 |
+
|
| 304 |
+
if pair.get("species") != "maize" or pair.get("view") != "sv1":
|
| 305 |
+
raise ValueError("maize CoT requests require species=maize and view=sv1")
|
| 306 |
+
stages = _stages(protocol_root)
|
| 307 |
+
bindings = _bindings(protocol_root)
|
| 308 |
+
source = _endpoint(pair.get("source", {}), stages, repo_root=repo_root, check_images=check_images)
|
| 309 |
+
target = _endpoint(pair.get("target", {}), stages, repo_root=repo_root, check_images=check_images)
|
| 310 |
+
if source["plant_id"] != target["plant_id"]:
|
| 311 |
+
raise ValueError("maize CoT pair endpoints must have the same plant_id")
|
| 312 |
+
source_stage = int(source["stage_id"][1:])
|
| 313 |
+
target_stage = int(target["stage_id"][1:])
|
| 314 |
+
if target_stage <= source_stage:
|
| 315 |
+
raise ValueError("maize CoT target stage must follow source stage")
|
| 316 |
+
actual_interval_days = int(target["days_after_sowing"]) - int(source["days_after_sowing"])
|
| 317 |
+
if actual_interval_days <= 0:
|
| 318 |
+
raise ValueError("maize CoT interval must be positive")
|
| 319 |
+
manual = pair.get("manual_summary", {})
|
| 320 |
+
manual_summary = {
|
| 321 |
+
organ: {
|
| 322 |
+
"source": _manual_value(manual.get(organ, {}).get("source")),
|
| 323 |
+
"target": _manual_value(manual.get(organ, {}).get("target")),
|
| 324 |
+
}
|
| 325 |
+
for organ in ("tassel", "ear")
|
| 326 |
+
}
|
| 327 |
+
metric_evidence = {
|
| 328 |
+
key: _request_metric(key, pair.get("metric_evidence", {}).get(key), bindings)
|
| 329 |
+
for key in METRIC_KEYS
|
| 330 |
+
}
|
| 331 |
+
return {
|
| 332 |
+
"request_id": str(pair.get("pair_id") or f"{source['plant_id']}__{source['stage_id']}__{target['stage_id']}__sv1"),
|
| 333 |
+
"view": "sv1",
|
| 334 |
+
"protocol_sha256": protocol_sha256(protocol_root),
|
| 335 |
+
"source": source,
|
| 336 |
+
"target": target,
|
| 337 |
+
"actual_interval_days": actual_interval_days,
|
| 338 |
+
"prediction_interval_weeks": actual_interval_days / 7.0,
|
| 339 |
+
"stage_delta": target_stage - source_stage,
|
| 340 |
+
"metric_evidence": metric_evidence,
|
| 341 |
+
"manual_summary": manual_summary,
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def validate_request(request: Mapping[str, Any], *, protocol_root: Path, repo_root: Path, check_images: bool = True) -> list[str]:
|
| 346 |
+
"""Validate schema, stage identity, hashes, and local metric provenance."""
|
| 347 |
+
|
| 348 |
+
issues = _schema_issues(dict(request), "PAIR_REQUEST_SCHEMA.json", protocol_root)
|
| 349 |
+
if issues:
|
| 350 |
+
return issues
|
| 351 |
+
stages = _stages(protocol_root)
|
| 352 |
+
bindings = _bindings(protocol_root)
|
| 353 |
+
if request.get("view") != "sv1":
|
| 354 |
+
issues.append("request view must be sv1")
|
| 355 |
+
if request.get("protocol_sha256") != protocol_sha256(protocol_root):
|
| 356 |
+
issues.append("protocol fingerprint mismatch")
|
| 357 |
+
endpoints: dict[str, Mapping[str, Any]] = {}
|
| 358 |
+
for side in ("source", "target"):
|
| 359 |
+
endpoint = request[side]
|
| 360 |
+
endpoints[side] = endpoint
|
| 361 |
+
stage_id = str(endpoint["stage_id"])
|
| 362 |
+
stage = stages.get(stage_id)
|
| 363 |
+
if stage is None:
|
| 364 |
+
issues.append(f"{side}: unknown stage {stage_id}")
|
| 365 |
+
continue
|
| 366 |
+
for field in ("days_after_sowing", "maize_stage"):
|
| 367 |
+
if endpoint[field] != stage[field]:
|
| 368 |
+
issues.append(f"{side}: stage metadata mismatch for {field}")
|
| 369 |
+
if endpoint["stage_description"] != _stage_description(stage):
|
| 370 |
+
issues.append(f"{side}: stage description mismatch")
|
| 371 |
+
if endpoint["image_id"] != f"{endpoint['plant_id']}/{stage_id}_sv1":
|
| 372 |
+
issues.append(f"{side}: image identity mismatch")
|
| 373 |
+
condition = endpoint.get("plant_condition")
|
| 374 |
+
allowed_conditions = set(CONDITION_TRANSLATIONS.values()) if "visible_description_en" in stage else CONDITIONS - {""}
|
| 375 |
+
if condition is not None and condition not in allowed_conditions:
|
| 376 |
+
issues.append(f"{side}: invalid plant_condition")
|
| 377 |
+
if not re.fullmatch(r"[0-9a-f]{64}", str(endpoint["image_sha256"])):
|
| 378 |
+
issues.append(f"{side}: malformed image hash")
|
| 379 |
+
if check_images:
|
| 380 |
+
try:
|
| 381 |
+
if not _resolved_path(endpoint["path"], repo_root).is_file():
|
| 382 |
+
issues.append(f"{side}: image path does not exist")
|
| 383 |
+
except ValueError as exc:
|
| 384 |
+
issues.append(f"{side}: {exc}")
|
| 385 |
+
source, target = endpoints["source"], endpoints["target"]
|
| 386 |
+
if source["plant_id"] != target["plant_id"]:
|
| 387 |
+
issues.append("source and target must be the same plant")
|
| 388 |
+
delta = int(target["stage_id"][1:]) - int(source["stage_id"][1:])
|
| 389 |
+
days = int(target["days_after_sowing"]) - int(source["days_after_sowing"])
|
| 390 |
+
expected_request_id = f"{source['plant_id']}__{source['stage_id']}__{target['stage_id']}__sv1"
|
| 391 |
+
if request["request_id"] != expected_request_id:
|
| 392 |
+
issues.append("request_id must match same-plant endpoint identity")
|
| 393 |
+
if delta <= 0 or request["stage_delta"] != delta:
|
| 394 |
+
issues.append("stage_delta mismatch")
|
| 395 |
+
if request["actual_interval_days"] != days or days <= 0:
|
| 396 |
+
issues.append("actual_interval_days mismatch")
|
| 397 |
+
if not math.isclose(float(request["prediction_interval_weeks"]), days / 7.0, rel_tol=1e-12):
|
| 398 |
+
issues.append("prediction_interval_weeks mismatch")
|
| 399 |
+
for key in METRIC_KEYS:
|
| 400 |
+
metric = request["metric_evidence"][key]
|
| 401 |
+
if metric["metric_key"] != bindings[key]["metric_key"] or metric["unit"] != bindings[key]["unit"]:
|
| 402 |
+
issues.append(f"{key}: metric binding mismatch")
|
| 403 |
+
observations = [metric["source"], metric["target"]]
|
| 404 |
+
if metric["qc"]["valid"] != all(item["status"] == "available" for item in observations):
|
| 405 |
+
issues.append(f"{key}: inconsistent qc.valid")
|
| 406 |
+
lower, upper = _METRIC_RANGES[key]
|
| 407 |
+
for side, observation in zip(("source", "target"), observations):
|
| 408 |
+
value = observation["value"]
|
| 409 |
+
status = observation["status"]
|
| 410 |
+
if status in {"available", "provisional"}:
|
| 411 |
+
if value is None or not isinstance(value, (int, float)) or not lower <= float(value) <= upper:
|
| 412 |
+
issues.append(f"{key}.{side}: missing or out-of-range metric")
|
| 413 |
+
if observation["image_sha256"] != request[side]["image_sha256"]:
|
| 414 |
+
issues.append(f"{key}.{side}: stale metric image hash")
|
| 415 |
+
elif value is not None:
|
| 416 |
+
issues.append(f"{key}.{side}: unavailable value must be null")
|
| 417 |
+
return issues
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def organ_text(organ: str, status: str, side: str | None = None) -> str:
|
| 421 |
+
if status not in MANUAL_STATUSES:
|
| 422 |
+
status = "pending"
|
| 423 |
+
subject = f"{side.capitalize()} {organ}" if side else f"The {organ}"
|
| 424 |
+
suffix = {
|
| 425 |
+
"visible": "is visible",
|
| 426 |
+
"not_visible": "is not visible",
|
| 427 |
+
"pending": "visibility has not been manually established",
|
| 428 |
+
}[status]
|
| 429 |
+
return f"{subject} {suffix}."
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def _manual_annotation(request: Mapping[str, Any], organ: str, section: str) -> str:
|
| 433 |
+
evidence = request["manual_summary"][organ]
|
| 434 |
+
if section == "target_phenotype":
|
| 435 |
+
return organ_text(organ, str(evidence["target"]))
|
| 436 |
+
return " ".join(organ_text(organ, str(evidence[side]), side) for side in ("source", "target"))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def validate_annotation(annotation: Mapping[str, Any], request: Mapping[str, Any], *, protocol_root: Path, repo_root: Path, check_images: bool = True) -> list[str]:
|
| 440 |
+
issues = validate_request(request, protocol_root=protocol_root, repo_root=repo_root, check_images=check_images)
|
| 441 |
+
issues.extend(_schema_issues(dict(annotation), "OUTPUT_SCHEMA_FRONT.json", protocol_root))
|
| 442 |
+
if issues:
|
| 443 |
+
return issues
|
| 444 |
+
if list(annotation) != ["stage_reasoning", "growth_plan", "target_phenotype"]:
|
| 445 |
+
issues.append("annotation root order mismatch")
|
| 446 |
+
source_stage = request["source"]["stage_id"]
|
| 447 |
+
target_stage = request["target"]["stage_id"]
|
| 448 |
+
if annotation["stage_reasoning"] != {"current_stage": source_stage, "future_stage": target_stage}:
|
| 449 |
+
issues.append("annotation stages must match request")
|
| 450 |
+
english_only = read_json(protocol_root / "TEACHER_PROMPT.json").get("output_language") == "en"
|
| 451 |
+
for section in ("growth_plan", "target_phenotype"):
|
| 452 |
+
if list(annotation[section]) != list(PUBLIC_KEYS):
|
| 453 |
+
issues.append(f"{section}: field order mismatch")
|
| 454 |
+
for key in PUBLIC_KEYS:
|
| 455 |
+
entry = annotation[section].get(key)
|
| 456 |
+
text = entry.get("text") if isinstance(entry, Mapping) else None
|
| 457 |
+
if not isinstance(text, str) or not text.strip() or _BANNED_TEXT.search(text):
|
| 458 |
+
issues.append(f"{section}.{key}: forbidden or empty text")
|
| 459 |
+
if isinstance(text, str) and (REFUSAL_TEXT.search(text) or "\n" in text or "\r" in text):
|
| 460 |
+
issues.append(f"{section}.{key}: refusal or multiline meta-response instead of phenotype text")
|
| 461 |
+
if english_only and isinstance(text, str) and _HAN_TEXT.search(text):
|
| 462 |
+
issues.append(f"{section}.{key}: Chinese text is not allowed in the English protocol")
|
| 463 |
+
if key in {"tassel", "ear"} and text != _manual_annotation(request, key, section):
|
| 464 |
+
issues.append(f"{section}.{key}: manual visibility text mismatch")
|
| 465 |
+
return issues
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _display(value: Decimal) -> str:
|
| 469 |
+
rounded = value.quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
|
| 470 |
+
return f"{abs(rounded) if rounded == 0 else rounded:.1f}"
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _numeric_evidence(key: str, metric: Mapping[str, Any], *, include_provisional: bool) -> str:
|
| 474 |
+
if not isinstance(metric, Mapping) or metric.get("qc", {}).get("valid") is not True:
|
| 475 |
+
return ""
|
| 476 |
+
source = metric.get("source", {})
|
| 477 |
+
target = metric.get("target", {})
|
| 478 |
+
if not isinstance(source, Mapping) or not isinstance(target, Mapping):
|
| 479 |
+
return ""
|
| 480 |
+
statuses = (source.get("status"), target.get("status"))
|
| 481 |
+
if any(status not in {"available", "provisional"} for status in statuses):
|
| 482 |
+
return ""
|
| 483 |
+
if "provisional" in statuses and not include_provisional:
|
| 484 |
+
return ""
|
| 485 |
+
try:
|
| 486 |
+
source_value = Decimal(str(source["value"]))
|
| 487 |
+
target_value = Decimal(str(target["value"]))
|
| 488 |
+
except (KeyError, TypeError, ValueError):
|
| 489 |
+
return ""
|
| 490 |
+
if metric.get("unit") == "fraction":
|
| 491 |
+
source_value *= Decimal(100)
|
| 492 |
+
target_value *= Decimal(100)
|
| 493 |
+
change = target_value - source_value
|
| 494 |
+
if key == "culm" and source_value != 0 and abs(change / source_value) < Decimal("0.02"):
|
| 495 |
+
return "Stable within the registered two-percent proxy tolerance; Source/Target/Change suppressed."
|
| 496 |
+
prefix = "Diagnostic provisional evidence; " if "provisional" in statuses else ""
|
| 497 |
+
return f"{prefix}Source={_display(source_value)}%; Target={_display(target_value)}%; Change={_display(change)} pp."
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def render_cot(annotation: Mapping[str, Any], request: Mapping[str, Any], *, protocol_root: Path, repo_root: Path, include_provisional: bool = False, check_images: bool = True) -> str:
|
| 501 |
+
"""Render validated annotation text and locally owned numeric evidence."""
|
| 502 |
+
|
| 503 |
+
issues = validate_annotation(annotation, request, protocol_root=protocol_root, repo_root=repo_root, check_images=check_images)
|
| 504 |
+
if issues:
|
| 505 |
+
raise ValueError("maize annotation validation failed: " + "; ".join(issues))
|
| 506 |
+
template = read_json(protocol_root / "COT_RENDERER_TEMPLATE.json")
|
| 507 |
+
lines = [template["wrapper"][0], template["sections"][0]]
|
| 508 |
+
labels = annotation["stage_reasoning"]
|
| 509 |
+
lines.extend(line.format_map(labels) for line in template["stage_reasoning_lines"])
|
| 510 |
+
lines.append(template["sections"][1])
|
| 511 |
+
for key in PUBLIC_KEYS:
|
| 512 |
+
text = str(annotation["growth_plan"][key]["text"]).strip().rstrip(".")
|
| 513 |
+
evidence = _numeric_evidence(key, request["metric_evidence"].get(key, {}), include_provisional=include_provisional)
|
| 514 |
+
pattern = template["growth_plan_line"]
|
| 515 |
+
line = pattern.format(section_label=_LABELS[key], text=text, numeric_evidence=evidence).rstrip()
|
| 516 |
+
lines.append(line)
|
| 517 |
+
lines.append(template["sections"][2])
|
| 518 |
+
for key in PUBLIC_KEYS:
|
| 519 |
+
text = str(annotation["target_phenotype"][key]["text"]).strip().rstrip(".")
|
| 520 |
+
lines.append(template["target_phenotype_line"].format(section_label=_LABELS[key], text=text).rstrip())
|
| 521 |
+
lines.append(template["wrapper"][1])
|
| 522 |
+
return "\n".join(lines) + "\n"
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def build_provider_input(request: Mapping[str, Any], *, protocol_root: Path, repo_root: Path, check_images: bool = True) -> dict[str, Any]:
|
| 526 |
+
"""Build an inspectable multimodal prompt bundle without contacting a provider."""
|
| 527 |
+
|
| 528 |
+
issues = validate_request(request, protocol_root=protocol_root, repo_root=repo_root, check_images=check_images)
|
| 529 |
+
if issues:
|
| 530 |
+
raise ValueError("maize request validation failed: " + "; ".join(issues))
|
| 531 |
+
prompt = read_json(protocol_root / "TEACHER_PROMPT.json")
|
| 532 |
+
metric_summary: dict[str, Any] = {}
|
| 533 |
+
for key in METRIC_KEYS:
|
| 534 |
+
metric = request["metric_evidence"][key]
|
| 535 |
+
trusted = metric["qc"]["valid"] and all(metric[side]["status"] == "available" for side in ("source", "target"))
|
| 536 |
+
metric_summary[key] = (
|
| 537 |
+
{"source": metric["source"]["value"], "target": metric["target"]["value"], "unit": metric["unit"]}
|
| 538 |
+
if trusted
|
| 539 |
+
else {"status": "unavailable"}
|
| 540 |
+
)
|
| 541 |
+
dump = lambda value: json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
| 542 |
+
source, target = request["source"], request["target"]
|
| 543 |
+
placeholders = {
|
| 544 |
+
"actual_interval_days": request["actual_interval_days"],
|
| 545 |
+
"prediction_interval_weeks": request["prediction_interval_weeks"],
|
| 546 |
+
"stage_delta": request["stage_delta"],
|
| 547 |
+
"source_stage": source["stage_id"],
|
| 548 |
+
"target_stage": target["stage_id"],
|
| 549 |
+
"source_das": source["days_after_sowing"],
|
| 550 |
+
"target_das": target["days_after_sowing"],
|
| 551 |
+
"source_stage_description": source["stage_description"],
|
| 552 |
+
"target_stage_description": target["stage_description"],
|
| 553 |
+
"metric_summary": dump(metric_summary),
|
| 554 |
+
"manual_summary": dump(request["manual_summary"]),
|
| 555 |
+
"plant_condition_summary": dump({side: request[side]["plant_condition"] for side in ("source", "target")}),
|
| 556 |
+
}
|
| 557 |
+
user_prompt = "\n".join(line.format_map(placeholders) for line in prompt["user_prompt_lines"])
|
| 558 |
+
canonical = {
|
| 559 |
+
section: {
|
| 560 |
+
organ: {"text": _manual_annotation(request, organ, section)}
|
| 561 |
+
for organ in ("tassel", "ear")
|
| 562 |
+
}
|
| 563 |
+
for section in ("growth_plan", "target_phenotype")
|
| 564 |
+
}
|
| 565 |
+
user_prompt += "\nCopy these deterministic manual organ text entries exactly into the matching sections: " + dump(canonical)
|
| 566 |
+
return {
|
| 567 |
+
"request_id": request["request_id"],
|
| 568 |
+
"protocol_sha256": request["protocol_sha256"],
|
| 569 |
+
"transport": "offline_prompt_bundle_not_api_request",
|
| 570 |
+
"provider_called": False,
|
| 571 |
+
"system_prompt": "\n".join([
|
| 572 |
+
*prompt["system_prompt_lines"],
|
| 573 |
+
"Strict output rules:",
|
| 574 |
+
*prompt.get("strict_output_rules", []),
|
| 575 |
+
]),
|
| 576 |
+
"user_prompt": user_prompt,
|
| 577 |
+
"required_organ_text": canonical,
|
| 578 |
+
"images": [
|
| 579 |
+
{
|
| 580 |
+
"role": f"{side.upper()}_IMAGE",
|
| 581 |
+
"path": str(_resolved_path(request[side]["path"], repo_root)),
|
| 582 |
+
"sha256": request[side]["image_sha256"],
|
| 583 |
+
}
|
| 584 |
+
for side in ("source", "target")
|
| 585 |
+
],
|
| 586 |
+
"output_schema": read_json(protocol_root / "OUTPUT_SCHEMA_FRONT.json"),
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def request_ledger_row(request: Mapping[str, Any], *, input_path: Path, output_path: Path, status: str = "ready", error: str | None = None, protocol_root: Path | None = None) -> dict[str, Any]:
|
| 591 |
+
"""Return operational metadata for one strict request row."""
|
| 592 |
+
|
| 593 |
+
return {
|
| 594 |
+
"algorithm_version": MAIZE_COT_ALGORITHM_VERSION,
|
| 595 |
+
"protocol_version": protocol_version(protocol_root) if protocol_root else MAIZE_COT_PROTOCOL_VERSION,
|
| 596 |
+
"request_id": request.get("request_id"),
|
| 597 |
+
"input_path": str(input_path.resolve()),
|
| 598 |
+
"output_path": str(output_path.resolve()),
|
| 599 |
+
"status": status,
|
| 600 |
+
"error": error,
|
| 601 |
+
"retry_count": 0,
|
| 602 |
+
"provider_calls": False,
|
| 603 |
+
"training_started": False,
|
| 604 |
+
"inference_started": False,
|
| 605 |
+
}
|
src/wgsr_v9/maize/experiment.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned, source-only prompts and output checks for the maize experiment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 11 |
+
PROTOCOL_ROOT = ROOT / "protocols/maize_four_way_v1"
|
| 12 |
+
PROTOCOL = "wgsr_maize_four_way_v1"
|
| 13 |
+
EXECUTOR_PROTOCOL = "wgsr_maize_executor_days_v1"
|
| 14 |
+
PLANNER_PROTOCOL = "wgsr_maize_planner_direct_days_v1"
|
| 15 |
+
PLANNER_FORMAT = "maize_sv1_v1"
|
| 16 |
+
INFERENCE_PROTOCOL = "wgsr_maize_planner_direct_days_source_only_inference_v1"
|
| 17 |
+
SIZE = (768, 1280)
|
| 18 |
+
LABELS = ("Culm", "Visible foreground area", "Projected fill", "Tassel", "Ear",
|
| 19 |
+
"Visible yellow-brown composition")
|
| 20 |
+
STABLE = "Stable within the registered two-percent proxy tolerance; Source/Target/Change suppressed."
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def simple_prompt(row: dict[str, Any]) -> str:
|
| 24 |
+
"""Allowlist only identity and horizon; target fields cannot affect the prompt."""
|
| 25 |
+
plant = str(row["plant_id"])
|
| 26 |
+
days = row["actual_interval_days"]
|
| 27 |
+
if not re.fullmatch(r"[A-Za-z0-9_-]+", plant):
|
| 28 |
+
raise ValueError("Invalid plant ID")
|
| 29 |
+
if isinstance(days, bool) or not isinstance(days, int) or days <= 0:
|
| 30 |
+
raise ValueError("Maize prediction requires positive integral actual_interval_days")
|
| 31 |
+
return (PROTOCOL_ROOT / "EXECUTOR_PROMPT_TEMPLATE.txt").read_text().strip().format(
|
| 32 |
+
plant_id=plant, actual_interval_days=days)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def validate_growth_cot(text: str) -> str:
|
| 36 |
+
"""Check a prediction without consulting future labels or teacher text."""
|
| 37 |
+
text = text.strip()
|
| 38 |
+
from .cot import REFUSAL_TEXT
|
| 39 |
+
if REFUSAL_TEXT.search(text):
|
| 40 |
+
raise ValueError("Provider refusal is not a maize phenotype description")
|
| 41 |
+
if re.search(r"[\u3400-\u9fff]|</?think>", text):
|
| 42 |
+
raise ValueError("Maize output must be English direct CoT")
|
| 43 |
+
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
| 44 |
+
if len(lines) != 19 or lines[0] != "<GROWTH_COT>" or lines[-1] != "</GROWTH_COT>":
|
| 45 |
+
raise ValueError("Expected one complete maize GROWTH_COT block")
|
| 46 |
+
if lines[1] != "Stage reasoning" or lines[4] != "Growth plan" or lines[11] != "Target phenotype":
|
| 47 |
+
raise ValueError("Invalid maize section order")
|
| 48 |
+
for index, name in ((2, "Current"), (3, "Future")):
|
| 49 |
+
if not re.fullmatch(rf"{name} stage: S[1-9]\.", lines[index]):
|
| 50 |
+
raise ValueError("Expected maize stage S1 through S9")
|
| 51 |
+
for offset in (5, 12):
|
| 52 |
+
for label, line in zip(LABELS, lines[offset:offset + 6], strict=True):
|
| 53 |
+
if not line.startswith(label + ": ") or not line[len(label) + 2:].strip():
|
| 54 |
+
raise ValueError(f"Missing or reordered maize field: {label}")
|
| 55 |
+
for index in (5, 6, 7, 10):
|
| 56 |
+
line = lines[index]
|
| 57 |
+
if index == 5 and line.endswith(STABLE):
|
| 58 |
+
continue
|
| 59 |
+
match = re.search(r"Source=(\d+\.\d)%; Target=(\d+\.\d)%; Change=(-?\d+\.\d) pp\.$", line)
|
| 60 |
+
if match is None:
|
| 61 |
+
raise ValueError("Missing one-decimal maize numeric triplet")
|
| 62 |
+
source, target, delta = map(float, match.groups())
|
| 63 |
+
if not 0 <= source <= 100 or not 0 <= target <= 100 or abs(target - source - delta) > 0.151:
|
| 64 |
+
raise ValueError("Maize numeric triplet is out of range or inconsistent")
|
| 65 |
+
return text
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def executor_prompt(row: dict[str, Any], cot: str | None = None) -> str:
|
| 69 |
+
prompt = simple_prompt(row)
|
| 70 |
+
if cot is not None:
|
| 71 |
+
suffix = (PROTOCOL_ROOT / "COT_SUFFIX.txt").read_text().strip()
|
| 72 |
+
prompt += "\n\n" + suffix.format(growth_cot=validate_growth_cot(cot))
|
| 73 |
+
return prompt
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def planner_messages(row: dict[str, Any], teacher_root: Path) -> list[dict[str, str]]:
|
| 77 |
+
stages = json.loads((teacher_root / "STAGES.json").read_text())["stages"]
|
| 78 |
+
guide = "\n".join(f"{s['stage_id']}: {s.get('maize_stage', '')}; {s['visible_description_en']}" for s in stages)
|
| 79 |
+
system = (PROTOCOL_ROOT / "PLANNER_SYSTEM.txt").read_text().strip().format(stage_guide=guide)
|
| 80 |
+
# Reuse the allowlist validation, never serialize a pair/request into the user message.
|
| 81 |
+
simple_prompt(row)
|
| 82 |
+
user = (f"<image>\nMaize plant ID: {row['plant_id']}. Shared view: sv1 (side view). "
|
| 83 |
+
f"Prediction interval: {row['actual_interval_days']} days. Forecast the growth script.")
|
| 84 |
+
return [{"role": "system", "content": system}, {"role": "user", "content": user}]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def validate_executor_row(row: dict[str, Any], variant: str) -> None:
|
| 88 |
+
if (row.get("species"), row.get("native_view"), row.get("view"), row.get("time_condition_unit")) != (
|
| 89 |
+
"maize", "sv1", "side0", "days"):
|
| 90 |
+
raise ValueError("Maize executor metadata mismatch")
|
| 91 |
+
if row.get("executor_variant") != variant or tuple(row.get("source_size", [])) != SIZE:
|
| 92 |
+
raise ValueError("Maize executor variant or native geometry mismatch")
|
| 93 |
+
cot = None
|
| 94 |
+
if variant != "simple":
|
| 95 |
+
prompt = row["prompt"]
|
| 96 |
+
if prompt.count("<GROWTH_COT>") != 1 or prompt.count("</GROWTH_COT>") != 1:
|
| 97 |
+
raise ValueError("Expected exactly one maize growth script")
|
| 98 |
+
cot = "<GROWTH_COT>" + prompt.split("<GROWTH_COT>", 1)[1]
|
| 99 |
+
if variant == "predicted_cot" and (row.get("cot_source") != "planner_prediction"
|
| 100 |
+
or not row.get("adapter_sha256")):
|
| 101 |
+
raise ValueError("Predicted CoT requires trained planner provenance; teacher fallback is forbidden")
|
| 102 |
+
if row["prompt"] != executor_prompt(row, cot):
|
| 103 |
+
raise ValueError("Maize prompt differs from the trained template")
|
src/wgsr_v9/maize/geometry.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic maize input geometry normalization."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
from .contract import CANONICAL_SOURCE_SIZE, CANONICAL_TARGET_SIZE
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
TOP_PADDING = CANONICAL_TARGET_SIZE[1] - CANONICAL_SOURCE_SIZE[1]
|
| 14 |
+
FILL_SAMPLE_ROWS = 16
|
| 15 |
+
FILL_SAMPLE_SIDE_MARGIN = 0.125
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _background_fill(image: Image.Image) -> tuple[int, int, int]:
|
| 19 |
+
"""Use the modal color in the central top background strip for padding."""
|
| 20 |
+
|
| 21 |
+
width, height = image.size
|
| 22 |
+
left = int(round(width * FILL_SAMPLE_SIDE_MARGIN))
|
| 23 |
+
right = int(round(width * (1.0 - FILL_SAMPLE_SIDE_MARGIN)))
|
| 24 |
+
sample = image.crop((left, 0, right, min(FILL_SAMPLE_ROWS, height))).convert("RGB")
|
| 25 |
+
common = Counter(sample.getdata()).most_common(1)
|
| 26 |
+
if not common:
|
| 27 |
+
raise ValueError("Cannot estimate geometry padding fill color")
|
| 28 |
+
return tuple(int(value) for value in common[0][0])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def normalize_geometry(image: Image.Image) -> tuple[Image.Image, dict[str, Any]]:
|
| 32 |
+
"""Pad the top of a maize image while preserving the bottom anchor.
|
| 33 |
+
|
| 34 |
+
The input is not resized. Ten pixels are added above the original canvas,
|
| 35 |
+
which preserves plant scale and the bottom pot/base position while making
|
| 36 |
+
the height divisible by 32 for later image-model stages.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
source = image.convert("RGB")
|
| 40 |
+
if source.size != CANONICAL_SOURCE_SIZE:
|
| 41 |
+
raise ValueError(f"Expected maize source size {CANONICAL_SOURCE_SIZE}, got {source.size}")
|
| 42 |
+
fill_rgb = _background_fill(source)
|
| 43 |
+
normalized = Image.new("RGB", CANONICAL_TARGET_SIZE, fill_rgb)
|
| 44 |
+
normalized.paste(source, (0, TOP_PADDING))
|
| 45 |
+
return normalized, {
|
| 46 |
+
"source_size": list(CANONICAL_SOURCE_SIZE),
|
| 47 |
+
"target_size": list(CANONICAL_TARGET_SIZE),
|
| 48 |
+
"resize_applied": False,
|
| 49 |
+
"padding": {"left": 0, "top": TOP_PADDING, "right": 0, "bottom": 0},
|
| 50 |
+
"padding_fill_rgb": list(fill_rgb),
|
| 51 |
+
"padding_fill_strategy": "central_top_strip_mode",
|
| 52 |
+
"fill_sample_rows": FILL_SAMPLE_ROWS,
|
| 53 |
+
"fill_sample_side_margin": FILL_SAMPLE_SIDE_MARGIN,
|
| 54 |
+
}
|
src/wgsr_v9/maize/grouped_loss.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Maize token spans for the existing stage/metric/text normalized loss."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import re
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from .experiment import STABLE, validate_growth_cot
|
| 8 |
+
|
| 9 |
+
VERSION = "wgsr_maize_planner_grouped_loss_v1"
|
| 10 |
+
METRIC_GROUPS = {"Culm": 4, "Visible foreground area": 5, "Projected fill": 6,
|
| 11 |
+
"Visible yellow-brown composition": 8}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def token_groups(ids: tuple[int, ...], tokenizer: Any) -> list[int]:
|
| 15 |
+
text = tokenizer.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
| 16 |
+
if text.count("<GROWTH_COT>") != 1 or text.count("</GROWTH_COT>") != 1:
|
| 17 |
+
raise ValueError("Expected one complete supervised maize answer")
|
| 18 |
+
begin = text.index("<GROWTH_COT>")
|
| 19 |
+
close = text.index("</GROWTH_COT>") + len("</GROWTH_COT>")
|
| 20 |
+
if text[:begin].strip() or text[close:].strip() not in {"", "<|im_end|>"}:
|
| 21 |
+
raise ValueError("Unexpected supervised prefix/suffix; prompt and thinking must be masked")
|
| 22 |
+
# ms-swift can retain a newline beside EOS. Keep its original offsets and
|
| 23 |
+
# assign it to text, exactly like the existing rice grouped-loss parser.
|
| 24 |
+
validate_growth_cot(text[begin:close])
|
| 25 |
+
spans = []
|
| 26 |
+
for label, group in (("Current stage", 2), ("Future stage", 3)):
|
| 27 |
+
match = re.search(rf"(?m)^{label}: ([^\r\n]+)", text)
|
| 28 |
+
if match is None:
|
| 29 |
+
raise ValueError("Missing maize stage span")
|
| 30 |
+
spans.append((match.start(1), match.end(1), group))
|
| 31 |
+
start, end = text.index("Growth plan"), text.index("Target phenotype")
|
| 32 |
+
pattern = r"(?m)^([^:\r\n]+):[^\r\n]*?(Source=\d[^\r\n]+|" + re.escape(STABLE) + r")$"
|
| 33 |
+
for match in re.finditer(pattern, text):
|
| 34 |
+
if not start <= match.start() < end or match[1] not in METRIC_GROUPS:
|
| 35 |
+
raise ValueError("Unexpected maize numeric span")
|
| 36 |
+
spans.append((match.start(2), match.end(2), METRIC_GROUPS[match[1]]))
|
| 37 |
+
if len(spans) != 6:
|
| 38 |
+
raise ValueError("Expected two stage and four metric spans")
|
| 39 |
+
encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
|
| 40 |
+
if encoded["input_ids"] != list(ids):
|
| 41 |
+
raise ValueError("Supervised token round trip differs")
|
| 42 |
+
groups = []
|
| 43 |
+
for left, right in encoded["offset_mapping"]:
|
| 44 |
+
overlaps = [group for start, end, group in spans if left < end and right > start]
|
| 45 |
+
if len(overlaps) > 1 or right <= left:
|
| 46 |
+
raise ValueError("Ambiguous maize token boundary")
|
| 47 |
+
groups.append(overlaps[0] if overlaps else 1)
|
| 48 |
+
if not {1, 2, 3, 4, 5, 6, 8}.issubset(groups):
|
| 49 |
+
raise ValueError("Missing maize supervised token group")
|
| 50 |
+
return groups
|
src/wgsr_v9/maize/naming.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable, human-readable names for maize-derived artifacts."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
from pathlib import PurePosixPath
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
OUTPUT_NAMING_VERSION = "wgsr_maize_underscore_filename_v1"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _validated_relative_path(filename: str) -> PurePosixPath:
|
| 13 |
+
"""Return a safe POSIX relative path used by the maize manifests."""
|
| 14 |
+
|
| 15 |
+
if not filename or "\x00" in filename:
|
| 16 |
+
raise ValueError(f"Invalid maize relative filename: {filename!r}")
|
| 17 |
+
path = PurePosixPath(filename)
|
| 18 |
+
if path.is_absolute() or ".." in path.parts:
|
| 19 |
+
raise ValueError(f"Unsafe maize relative filename: {filename!r}")
|
| 20 |
+
if not path.name or path.name in {".", ".."}:
|
| 21 |
+
raise ValueError(f"Invalid maize relative filename: {filename!r}")
|
| 22 |
+
return path
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def maize_output_stem(filename: str) -> str:
|
| 26 |
+
"""Convert ``001a/S1_sv1.png`` to the readable stem ``001a_S1_sv1``.
|
| 27 |
+
|
| 28 |
+
The source path remains the canonical identity. Only path separators and
|
| 29 |
+
the final suffix are removed from the artifact name, so the generated
|
| 30 |
+
files remain easy to inspect while preserving a deterministic one-to-one
|
| 31 |
+
mapping. Callers that handle a manifest must still check that the stems
|
| 32 |
+
are unique within that manifest.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
path = _validated_relative_path(filename)
|
| 36 |
+
suffix = path.suffix
|
| 37 |
+
leaf = path.name[: -len(suffix)] if suffix else path.name
|
| 38 |
+
if not leaf:
|
| 39 |
+
raise ValueError(f"Maize filename has an empty stem: {filename!r}")
|
| 40 |
+
stem = "_".join((*path.parts[:-1], leaf))
|
| 41 |
+
if not stem or stem in {".", ".."}:
|
| 42 |
+
raise ValueError(f"Invalid maize output stem for {filename!r}")
|
| 43 |
+
return stem
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def maize_legacy_output_stem(filename: str) -> str:
|
| 47 |
+
"""Return the pre-v1 SHA-256 stem for compatibility with old artifacts."""
|
| 48 |
+
|
| 49 |
+
_validated_relative_path(filename)
|
| 50 |
+
return hashlib.sha256(filename.encode("utf-8")).hexdigest()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__all__ = [
|
| 54 |
+
"OUTPUT_NAMING_VERSION",
|
| 55 |
+
"maize_legacy_output_stem",
|
| 56 |
+
"maize_output_stem",
|
| 57 |
+
]
|
src/wgsr_v9/maize/planner_export.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export only complete, source-only maize planner predictions to the executor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from wgsr_v9.io import sha256_path, write_json, write_jsonl
|
| 11 |
+
from wgsr_v9.planner_inference import source_request
|
| 12 |
+
from .experiment import (EXECUTOR_PROTOCOL, INFERENCE_PROTOCOL, executor_prompt,
|
| 13 |
+
validate_executor_row, validate_growth_cot)
|
| 14 |
+
from .training import provenance
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def export_maize_results(config: dict[str, Any], root: Path, rows: list[dict[str, Any]],
|
| 18 |
+
canonical: dict[str, dict[str, Any]], manifests: list[dict[str, Any]],
|
| 19 |
+
results: dict[str, dict[str, Any]]) -> dict[str, Any]:
|
| 20 |
+
package = Path(config["data_root"]).resolve()
|
| 21 |
+
dataset = package / "val.jsonl"
|
| 22 |
+
expected_ids = {row["id"] for row in rows}
|
| 23 |
+
if len(rows) != config["expected_rows"] or set(canonical) != expected_ids or set(results) != expected_ids:
|
| 24 |
+
raise ValueError("Maize planner must cover the full canonical validation set")
|
| 25 |
+
for manifest in manifests:
|
| 26 |
+
if (manifest.get("dataset_sha256") != sha256_path(dataset)
|
| 27 |
+
or manifest.get("protocol_version") != INFERENCE_PROTOCOL
|
| 28 |
+
or manifest.get("source_only") is not True
|
| 29 |
+
or manifest.get("benchmark") is not False
|
| 30 |
+
or manifest.get("status") != "completed"
|
| 31 |
+
or not manifest.get("adapter_sha256")):
|
| 32 |
+
raise ValueError("Planner shard provenance is incompatible with formal maize inference")
|
| 33 |
+
exports, rejected = [], []
|
| 34 |
+
for index, row in enumerate(rows):
|
| 35 |
+
result, reference = results[row["id"]], canonical[row["id"]]
|
| 36 |
+
source = Path(reference["source_image_path"]).resolve()
|
| 37 |
+
expected_request = source_request(row, package)
|
| 38 |
+
expected_hash = hashlib.sha256(json.dumps(expected_request, sort_keys=True).encode()).hexdigest()
|
| 39 |
+
if (Path(result["input_path"]).resolve() != source
|
| 40 |
+
or result.get("prompt_sha256") != expected_hash
|
| 41 |
+
or sha256_path(source) != reference["source_image_sha256"]):
|
| 42 |
+
raise ValueError(f"Planner source-only request mismatch: {row['id']}")
|
| 43 |
+
if not result.get("format_valid") or result.get("finish_reason") == "length":
|
| 44 |
+
rejected.append(result)
|
| 45 |
+
continue
|
| 46 |
+
cot = validate_growth_cot(result["growth_cot"])
|
| 47 |
+
metadata = row["planner_metadata"]
|
| 48 |
+
export = {**metadata, **provenance(Path(result["output_path"]), root / "executor_prompts.jsonl",
|
| 49 |
+
protocol=INFERENCE_PROTOCOL),
|
| 50 |
+
"executor_prompt_protocol_version": EXECUTOR_PROTOCOL,
|
| 51 |
+
"image": reference["target_image_path"], "edit_image": str(source),
|
| 52 |
+
"target_usage": "eval_reference_only", "prompt": executor_prompt(metadata, cot),
|
| 53 |
+
"executor_variant": "predicted_cot", "cot_source": "planner_prediction",
|
| 54 |
+
"adapter_sha256": manifests[0]["adapter_sha256"], "original_row_index": index}
|
| 55 |
+
validate_executor_row(export, "predicted_cot")
|
| 56 |
+
exports.append(export)
|
| 57 |
+
write_jsonl(root / "rejected.jsonl", rejected)
|
| 58 |
+
if rejected:
|
| 59 |
+
raise ValueError(f"{len(rejected)} invalid maize predictions; fix/retry before export, no teacher fallback")
|
| 60 |
+
write_jsonl(root / "results.jsonl", [results[row["id"]] for row in rows])
|
| 61 |
+
write_jsonl(root / "executor_prompts.jsonl", exports)
|
| 62 |
+
summary = {**provenance(dataset, root, protocol=INFERENCE_PROTOCOL, status="completed"),
|
| 63 |
+
"generated_rows": len(rows), "valid_rows": len(exports), "rejected_rows": 0,
|
| 64 |
+
"teacher_fallback_used": False, "dataset_sha256": sha256_path(dataset)}
|
| 65 |
+
write_json(root / "summary.json", summary)
|
| 66 |
+
return summary
|
src/wgsr_v9/maize/training.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit maize teachers and atomically package matched four-method inputs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
from wgsr_v9.io import canonical_sha256, read_jsonl, sha256_path, write_json, write_jsonl
|
| 13 |
+
from .cot import ANNOTATION_QC_VERSION, build_request, protocol_sha256, render_cot
|
| 14 |
+
from .experiment import (EXECUTOR_PROTOCOL, PLANNER_FORMAT, PLANNER_PROTOCOL, PROTOCOL,
|
| 15 |
+
PROTOCOL_ROOT, ROOT, SIZE, executor_prompt, planner_messages,
|
| 16 |
+
validate_growth_cot)
|
| 17 |
+
|
| 18 |
+
ALGORITHM = "wgsr_maize_four_way_package_v1"
|
| 19 |
+
EXECUTOR_ALGORITHM = "wgsr_v9_qwen_image21_executor_sft_v1"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def provenance(input_path: Path, output_path: Path, *, protocol: str = PROTOCOL,
|
| 23 |
+
status: str = "ready") -> dict[str, Any]:
|
| 24 |
+
return {"algorithm_version": ALGORITHM, "protocol_version": protocol,
|
| 25 |
+
"input_path": str(input_path.resolve()), "output_path": str(output_path.resolve()),
|
| 26 |
+
"status": status, "error": None, "retry_count": 0}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def unique_index(rows: list[dict[str, Any]], key: str) -> dict[str, dict[str, Any]]:
|
| 30 |
+
indexed = {str(row[key]): row for row in rows}
|
| 31 |
+
if len(indexed) != len(rows):
|
| 32 |
+
raise ValueError(f"Duplicate {key}")
|
| 33 |
+
return indexed
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def prepare(config_path: Path) -> dict[str, Any]:
|
| 37 |
+
config = json.loads(config_path.read_text())
|
| 38 |
+
|
| 39 |
+
def path(key: str) -> Path:
|
| 40 |
+
return (ROOT / config[key]).resolve()
|
| 41 |
+
|
| 42 |
+
pairs_path, requests_path, teacher, teacher_protocol, output = (
|
| 43 |
+
path(key) for key in ("pairs", "requests", "teacher_root", "teacher_protocol_root", "output_root"))
|
| 44 |
+
contract = json.loads((PROTOCOL_ROOT / "CONTRACT.json").read_text())
|
| 45 |
+
status = json.loads((teacher / "status.json").read_text())
|
| 46 |
+
if status["status"] not in {"complete", "completed"} or status["succeeded"] != 8000 or status["failed"]:
|
| 47 |
+
raise ValueError("Teacher synthesis must finish successfully for all 8000 queries before packaging")
|
| 48 |
+
pairs = read_jsonl(pairs_path)
|
| 49 |
+
requests = unique_index(read_jsonl(requests_path), "request_id")
|
| 50 |
+
pair_index = unique_index(pairs, "pair_id")
|
| 51 |
+
# A resumed run may append another result for a previously failed request.
|
| 52 |
+
results = {row["request_id"]: row for row in read_jsonl(teacher / "results.jsonl")}
|
| 53 |
+
if set(pair_index) != set(requests) or set(pair_index) != set(results):
|
| 54 |
+
raise ValueError("Pair, request, and teacher result IDs differ")
|
| 55 |
+
counts = dict(Counter(pair["split"] for pair in pairs))
|
| 56 |
+
expected = {"train": contract["train_rows"], "validation": contract["validation_rows"]}
|
| 57 |
+
if counts != expected:
|
| 58 |
+
raise ValueError(f"Unexpected split counts: {counts}")
|
| 59 |
+
plants = {split: {p["plant_id"] for p in pairs if p["split"] == split} for split in expected}
|
| 60 |
+
if plants["train"] & plants["validation"]:
|
| 61 |
+
raise ValueError("Plant leakage across train/validation")
|
| 62 |
+
teacher_hash = protocol_sha256(teacher_protocol)
|
| 63 |
+
file_hashes: dict[str, str] = {}
|
| 64 |
+
cots: dict[str, str] = {}
|
| 65 |
+
audit = []
|
| 66 |
+
for pair in pairs:
|
| 67 |
+
key = pair["pair_id"]
|
| 68 |
+
request, result = requests[key], results[key]
|
| 69 |
+
if (pair.get("species"), pair.get("view"), pair.get("training_ready")) != ("maize", "sv1", True):
|
| 70 |
+
raise ValueError(f"Ineligible pair: {key}")
|
| 71 |
+
if (pair["actual_interval_days"] <= 0 or pair["stage_delta"] <= 0
|
| 72 |
+
or pair["source"]["plant_id"] != pair["target"]["plant_id"]
|
| 73 |
+
or pair["source"]["plant_id"] != pair["plant_id"]):
|
| 74 |
+
raise ValueError(f"Nonforward or cross-plant pair: {key}")
|
| 75 |
+
rebuilt = build_request(pair, protocol_root=teacher_protocol, repo_root=ROOT, check_images=False)
|
| 76 |
+
if rebuilt != request:
|
| 77 |
+
raise ValueError(f"Teacher request differs from frozen pair: {key}")
|
| 78 |
+
if result.get("status") != "success" or result.get("protocol_sha256") != teacher_hash:
|
| 79 |
+
raise ValueError(f"Teacher not valid: {key}")
|
| 80 |
+
for endpoint in ("source", "target"):
|
| 81 |
+
image_path = (ROOT / request[endpoint]["path"]).resolve()
|
| 82 |
+
if str(image_path) not in file_hashes:
|
| 83 |
+
with Image.open(image_path) as image:
|
| 84 |
+
if image.size != SIZE or image.mode != "RGB":
|
| 85 |
+
raise ValueError(f"Noncanonical maize image: {image_path}")
|
| 86 |
+
file_hashes[str(image_path)] = sha256_path(image_path)
|
| 87 |
+
if file_hashes[str(image_path)] != request[endpoint]["image_sha256"]:
|
| 88 |
+
raise ValueError(f"Image hash mismatch: {key}: {endpoint}")
|
| 89 |
+
annotation_path, rendered_path = Path(result["annotation_path"]), Path(result["output_path"])
|
| 90 |
+
if sha256_path(annotation_path) != result["annotation_sha256"] or sha256_path(rendered_path) != result["rendered_sha256"]:
|
| 91 |
+
raise ValueError(f"Teacher artifact hash mismatch: {key}")
|
| 92 |
+
rendered = render_cot(json.loads(annotation_path.read_text()), request,
|
| 93 |
+
protocol_root=teacher_protocol, repo_root=ROOT, check_images=False)
|
| 94 |
+
if rendered != rendered_path.read_text():
|
| 95 |
+
raise ValueError(f"Teacher rendered content mismatch: {key}")
|
| 96 |
+
cots[key] = validate_growth_cot(rendered)
|
| 97 |
+
audit.append({**provenance(annotation_path, output / "teacher_audit.jsonl"), "request_id": key,
|
| 98 |
+
"annotation_sha256": result["annotation_sha256"], "rendered_sha256": result["rendered_sha256"],
|
| 99 |
+
"teacher_fingerprint": result["fingerprint"], "split": pair["split"]})
|
| 100 |
+
inputs = {"pairs": sha256_path(pairs_path), "requests": sha256_path(requests_path),
|
| 101 |
+
"teacher_audit": canonical_sha256(audit), "teacher_protocol": teacher_hash,
|
| 102 |
+
"experiment_protocol": protocol_sha256(PROTOCOL_ROOT), "images": canonical_sha256(file_hashes),
|
| 103 |
+
"annotation_qc_version": ANNOTATION_QC_VERSION}
|
| 104 |
+
manifest_path = output / "package_manifest.json"
|
| 105 |
+
if manifest_path.is_file():
|
| 106 |
+
previous = json.loads(manifest_path.read_text())
|
| 107 |
+
if previous.get("input_sha256") != inputs:
|
| 108 |
+
raise ValueError("Existing package has different inputs; use a new versioned output_root")
|
| 109 |
+
for relative, digest in previous["generated_file_sha256"].items():
|
| 110 |
+
if sha256_path(output / relative) != digest:
|
| 111 |
+
raise ValueError(f"Existing package artifact changed: {relative}")
|
| 112 |
+
return previous
|
| 113 |
+
executor = {variant: {split: [] for split in ("train", "val")} for variant in ("simple", "teacher_cot")}
|
| 114 |
+
planner: dict[str, list[dict[str, Any]]] = {"train": [], "val": []}
|
| 115 |
+
evaluation, api_inputs, copies, seeds = [], [], [], []
|
| 116 |
+
for pair in pairs:
|
| 117 |
+
key = pair["pair_id"]
|
| 118 |
+
split = "val" if pair["split"] == "validation" else "train"
|
| 119 |
+
index = len(planner[split])
|
| 120 |
+
source, target = (Path(pair[side]["path"]).resolve() for side in ("source", "target"))
|
| 121 |
+
metadata = {"request_id": key, "pair_id": key, "pair_group_id": pair["pair_group_id"],
|
| 122 |
+
"plant_id": pair["plant_id"], "split": split, "species": "maize", "native_view": "sv1",
|
| 123 |
+
"view": "side0", "actual_interval_days": pair["actual_interval_days"],
|
| 124 |
+
"time_condition_unit": "days", "source_size": list(SIZE), "original_row_index": index}
|
| 125 |
+
for variant in executor:
|
| 126 |
+
executor[variant][split].append({**provenance(source, target, protocol=EXECUTOR_PROTOCOL), **metadata,
|
| 127 |
+
"image": str(target), "edit_image": str(source), "executor_variant": variant,
|
| 128 |
+
"cot_source": "teacher_annotation" if variant == "teacher_cot" else None,
|
| 129 |
+
"prompt": executor_prompt(metadata, cots[key] if variant == "teacher_cot" else None)})
|
| 130 |
+
planner[split].append({**provenance(source, output / "planner" / f"{split}.jsonl", protocol=PLANNER_PROTOCOL),
|
| 131 |
+
"id": key, "messages": [*planner_messages(metadata, teacher_protocol),
|
| 132 |
+
{"role": "assistant", "content": cots[key]}],
|
| 133 |
+
"images": [str(source)], "planner_metadata": metadata})
|
| 134 |
+
if split != "val":
|
| 135 |
+
continue
|
| 136 |
+
canonical = {**provenance(source, output / "evaluation/manifest.jsonl"), **metadata,
|
| 137 |
+
"row_index": index, "source_image_path": str(source), "target_image_path": str(target),
|
| 138 |
+
"source_image_sha256": file_hashes[str(source)], "target_image_sha256": file_hashes[str(target)],
|
| 139 |
+
"source_stage_id": pair["source_stage_id"], "target_stage_id": pair["target_stage_id"],
|
| 140 |
+
"source_stage": pair["source_stage_id"], "target_stage": pair["target_stage_id"],
|
| 141 |
+
"source_image_id": pair["source"]["image_id"], "target_image_id": pair["target"]["image_id"],
|
| 142 |
+
"horizon_bucket": pair["interval_bin"], "seed": 20261108 + index,
|
| 143 |
+
"target_usage": "eval_reference_only"}
|
| 144 |
+
evaluation.append(canonical)
|
| 145 |
+
api_inputs.append({**canonical, "output_path": str(output / "evaluation/gpt_image2_inputs.jsonl"),
|
| 146 |
+
"prompt": executor_prompt(metadata), "prompt_variant": "simple",
|
| 147 |
+
"model": "gpt-image-2", "source_only": True})
|
| 148 |
+
copies.append({**canonical, "output_path": str(source), "status": "completed", "model": "source_copy",
|
| 149 |
+
"algorithm_version": "wgsr_maize_source_copy_v1", "prediction_sha256": file_hashes[str(source)]})
|
| 150 |
+
seeds.append({**provenance(source, output / "evaluation/seeds.jsonl"), "pair_id": key, "seed": canonical["seed"]})
|
| 151 |
+
write_jsonl(output / "teacher_audit.jsonl", audit)
|
| 152 |
+
variants = {}
|
| 153 |
+
for variant, splits in executor.items():
|
| 154 |
+
for split, rows in splits.items():
|
| 155 |
+
write_jsonl(output / "executor" / variant / f"{split}.jsonl", rows)
|
| 156 |
+
variants[variant] = {"status": "complete", "rows_by_split": {k: len(v) for k, v in splits.items()},
|
| 157 |
+
"generated_file_sha256": {f"{s}.jsonl": sha256_path(output / "executor" / variant / f"{s}.jsonl") for s in splits}}
|
| 158 |
+
write_json(output / "executor/package_manifest.json", {
|
| 159 |
+
**provenance(pairs_path, output / "executor", protocol=EXECUTOR_PROTOCOL, status="complete"),
|
| 160 |
+
"algorithm_version": EXECUTOR_ALGORITHM, "species": "maize", "variants": variants})
|
| 161 |
+
for split, rows in planner.items():
|
| 162 |
+
write_jsonl(output / "planner" / f"{split}.jsonl", rows)
|
| 163 |
+
write_json(output / "planner/package_manifest.json", {
|
| 164 |
+
**provenance(pairs_path, output / "planner", protocol=PLANNER_PROTOCOL, status="complete"),
|
| 165 |
+
"planner_variant": "proposed_cot", "active_no_cot_planner": False, "cot_version": "v3",
|
| 166 |
+
"numeric_evidence_format": PLANNER_FORMAT, "time_condition_unit": "days", "enable_thinking": False,
|
| 167 |
+
"output_wrapper": "GROWTH_COT", "rows_by_split": {k: len(v) for k, v in planner.items()},
|
| 168 |
+
"generated_file_sha256": {f"{s}.jsonl": sha256_path(output / "planner" / f"{s}.jsonl") for s in planner}})
|
| 169 |
+
for name, rows in (("manifest", evaluation), ("gpt_image2_inputs", api_inputs), ("source_copy/results", copies), ("seeds", seeds)):
|
| 170 |
+
write_jsonl(output / "evaluation" / f"{name}.jsonl", rows)
|
| 171 |
+
generated = {p.relative_to(output).as_posix(): sha256_path(p) for p in sorted(output.rglob("*.json*")) if p != manifest_path}
|
| 172 |
+
summary = {**provenance(pairs_path, output, status="complete"), "rows_by_split": counts,
|
| 173 |
+
"plants_by_split": {k: len(v) for k, v in plants.items()}, "plant_overlap": 0,
|
| 174 |
+
"unique_images": len(file_hashes), "validated_teacher_rows": len(cots),
|
| 175 |
+
"source_copy_rows": len(copies), "image_size": list(SIZE), "input_sha256": inputs,
|
| 176 |
+
"generated_file_sha256": generated, "training_started": False, "image_api_started": False}
|
| 177 |
+
write_json(manifest_path, summary)
|
| 178 |
+
return summary
|