Fighoh commited on
Commit
bb50b15
·
verified ·
1 Parent(s): d0f9a57

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. assets/growth-script-templates.png +0 -0
  3. assets/method-overview.pdf +0 -0
  4. assets/method-overview.png +0 -0
  5. configs/accelerate_executor_train_8gpu_bs2_ga1.yaml +23 -0
  6. configs/fsdp2_planner_full_state.json +11 -0
  7. configs/local.example.json +18 -0
  8. configs/model_release.json +108 -0
  9. docs/CHECKPOINTS.md +178 -0
  10. docs/DATA.md +116 -0
  11. docs/DEVELOPMENT.md +44 -0
  12. docs/INSTALL.md +95 -0
  13. docs/PROTOCOL.md +71 -0
  14. docs/REPOSITORIES.md +119 -0
  15. docs/RESULTS.md +83 -0
  16. docs/RUNNING.md +200 -0
  17. docs/paper_results.json +126 -0
  18. examples/README.md +23 -0
  19. examples/maize_growth_script.txt +21 -0
  20. examples/rice_front_growth_script.txt +19 -0
  21. examples/rice_top_growth_script.txt +17 -0
  22. protocols/maize_sv1_v1/cot_v2_en_v2/COT_RENDERER_TEMPLATE.json +47 -0
  23. protocols/maize_sv1_v1/cot_v2_en_v2/STAGES.json +79 -0
  24. protocols/maize_sv1_v1/cot_v2_en_v2/TEACHER_PROMPT.json +59 -0
  25. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/COT_RENDERER_TEMPLATE.json +50 -0
  26. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/METRIC_EVIDENCE_SCHEMA.json +44 -0
  27. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/OUTPUT_SCHEMA_FRONT.json +139 -0
  28. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/OUTPUT_SCHEMA_TOP.json +131 -0
  29. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/README.md +7 -0
  30. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/TEACHER_PROMPT.json +66 -0
  31. protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/VIEW_VARIABLE_BINDINGS.json +103 -0
  32. requirements/cpu.txt +4 -0
  33. requirements/planner.txt +19 -0
  34. requirements/renderer.txt +21 -0
  35. src/wgsr_v9/cot_synthesis.py +624 -0
  36. src/wgsr_v9/executor_cache_index.py +162 -0
  37. src/wgsr_v9/executor_dropout.py +158 -0
  38. src/wgsr_v9/executor_training.py +124 -0
  39. src/wgsr_v9/executor_training_runner.py +420 -0
  40. src/wgsr_v9/image_geometry_evaluation.py +94 -0
  41. src/wgsr_v9/planner_adapter.py +53 -0
  42. tests/__init__.py +0 -0
  43. tests/test_dino_checkpoint.py +59 -0
  44. tests/test_evaluation_io.py +27 -0
  45. tests/test_executor_training.py +186 -0
  46. tests/test_image_evaluation_workers.py +67 -0
  47. tests/test_image_geometry_evaluation.py +129 -0
  48. tests/test_mainline_protocols.py +42 -0
  49. tests/test_release_config.py +88 -0
  50. tests/test_text_executor_release.py +179 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* 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
 
 
 
 
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
assets/growth-script-templates.png ADDED
assets/method-overview.pdf ADDED
Binary file (131 Bytes). View file
 
assets/method-overview.png ADDED
configs/accelerate_executor_train_8gpu_bs2_ga1.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ gradient_accumulation_steps: 1
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: true
8
+ zero3_save_16bit_model: true
9
+ zero_stage: 3
10
+ distributed_type: DEEPSPEED
11
+ downcast_bf16: 'no'
12
+ enable_cpu_affinity: false
13
+ machine_rank: 0
14
+ main_training_function: main
15
+ mixed_precision: bf16
16
+ num_machines: 1
17
+ num_processes: 8
18
+ rdzv_backend: static
19
+ same_network: true
20
+ tpu_env: []
21
+ tpu_use_cluster: false
22
+ tpu_use_sudo: false
23
+ use_cpu: false
configs/fsdp2_planner_full_state.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fsdp": "full_shard auto_wrap",
3
+ "fsdp_config": {
4
+ "fsdp_version": 2,
5
+ "reshard_after_forward": true,
6
+ "auto_wrap_policy": "TRANSFORMER_BASED_WRAP",
7
+ "cpu_ram_efficient_loading": true,
8
+ "state_dict_type": "FULL_STATE_DICT",
9
+ "activation_checkpointing": true
10
+ }
11
+ }
configs/local.example.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "data_root": "data",
3
+ "run_root": "runs",
4
+ "planner_model": "models/Qwen3.8-27B",
5
+ "image_model": "models/Qwen-Image-2.1",
6
+ "diffsynth_repo": "third_party/DiffSynth-Studio",
7
+ "planner_env": ".venv-planner",
8
+ "renderer_env": ".venv-renderer",
9
+ "cache_tmpfs_root": "runs/cache-scratch",
10
+ "renderer_train_gpus": "0,1,2,3,4,5,6,7",
11
+ "renderer_infer_gpus": "0",
12
+ "rice_planner_gpus": "0,1",
13
+ "maize_planner_gpus": "0,1,2,3,4,5,6,7",
14
+ "rice_planner_adapter": null,
15
+ "maize_planner_adapter": null,
16
+ "rice_renderer_checkpoint": null,
17
+ "maize_renderer_checkpoint": null
18
+ }
configs/model_release.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "release_id": "agrowm-mainline-2026-11-24",
4
+ "method": "AgroWM",
5
+ "weight_scope": "Ours only",
6
+ "components": [
7
+ {
8
+ "crop": "rice",
9
+ "component": "phenoclock",
10
+ "base_model": "Qwen/Qwen3.8-27B",
11
+ "format": "peft_lora",
12
+ "training_point": {
13
+ "epochs": 2,
14
+ "step": 2500
15
+ },
16
+ "weight_file": "checkpoints/rice/phenoclock/adapter_model.safetensors",
17
+ "size_bytes": 933974032,
18
+ "sha256": "8f02194330f037d6882cc91be2e3bb3dbfc26b3b5843aa01878d93b98150ec3a",
19
+ "tensor_count": 992,
20
+ "parameter_count": 233455616,
21
+ "tensor_dtypes": {
22
+ "F32": 992
23
+ },
24
+ "license": "apache-2.0",
25
+ "weight_bytes_modified_for_release": false
26
+ },
27
+ {
28
+ "crop": "maize",
29
+ "component": "phenoclock",
30
+ "base_model": "Qwen/Qwen3.8-27B",
31
+ "format": "peft_lora",
32
+ "training_point": {
33
+ "epochs": 2,
34
+ "step": 800
35
+ },
36
+ "weight_file": "checkpoints/maize/phenoclock/adapter_model.safetensors",
37
+ "size_bytes": 467063552,
38
+ "sha256": "4d7ce12e54a8275c43e2649301c31edb5a2a85652783b17a1d98fe325b8a05c9",
39
+ "tensor_count": 992,
40
+ "parameter_count": 233455616,
41
+ "tensor_dtypes": {
42
+ "BF16": 992
43
+ },
44
+ "license": "apache-2.0",
45
+ "weight_bytes_modified_for_release": false
46
+ },
47
+ {
48
+ "crop": "rice",
49
+ "component": "rooted_renderer",
50
+ "base_model": "Qwen/Qwen-Image-2.1",
51
+ "format": "diffusers_transformer",
52
+ "training_point": {
53
+ "epochs": 2,
54
+ "step": 2500
55
+ },
56
+ "weight_file": "checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors",
57
+ "size_bytes": 14230284584,
58
+ "sha256": "545a91b5bb832e19787d073cdc8609e387aef831b06718031a05898a4a556708",
59
+ "tensor_count": 297,
60
+ "parameter_count": 7115124736,
61
+ "tensor_dtypes": {
62
+ "BF16": 297
63
+ },
64
+ "license": "qwen-research",
65
+ "weight_bytes_modified_for_release": false
66
+ },
67
+ {
68
+ "crop": "maize",
69
+ "component": "rooted_renderer",
70
+ "base_model": "Qwen/Qwen-Image-2.1",
71
+ "format": "diffusers_transformer",
72
+ "training_point": {
73
+ "epochs": 2,
74
+ "step": 800
75
+ },
76
+ "weight_file": "checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors",
77
+ "size_bytes": 14230284584,
78
+ "sha256": "a5385aa6df6c211c488b451acd611a26fabda96ef3142a3f949454f278792f60",
79
+ "tensor_count": 297,
80
+ "parameter_count": 7115124736,
81
+ "tensor_dtypes": {
82
+ "BF16": 297
83
+ },
84
+ "license": "qwen-research",
85
+ "weight_bytes_modified_for_release": false
86
+ }
87
+ ],
88
+ "crop_protocols": {
89
+ "rice": {
90
+ "planner_protocol_version": "wgsr_v9_planner_v3_direct_metric_named_weeks_v1",
91
+ "numeric_evidence_format": "metric_named_v1",
92
+ "time_condition_unit": "weeks",
93
+ "enable_thinking": false,
94
+ "output_wrapper": "GROWTH_COT",
95
+ "executor_prompt_protocol_version": "wgsr_v9_qwen_image21_executor_prompt_v3_metric_named_weeks"
96
+ },
97
+ "maize": {
98
+ "planner_protocol_version": "wgsr_maize_planner_direct_days_v1",
99
+ "numeric_evidence_format": "maize_sv1_v1",
100
+ "time_condition_unit": "days",
101
+ "enable_thinking": false,
102
+ "output_wrapper": "GROWTH_COT",
103
+ "executor_prompt_protocol_version": "wgsr_maize_executor_days_v1"
104
+ }
105
+ },
106
+ "code_license": "apache-2.0",
107
+ "weight_license_scope": "PhenoClock: Apache-2.0; Rooted Renderer: Qwen Research License."
108
+ }
docs/CHECKPOINTS.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Released AgroWM checkpoints
2
+
3
+ The paired Hugging Face model release includes the final **Ours** model for rice and maize. Each crop has
4
+ two components: a PhenoClock LoRA adapter and a Rooted Renderer diffusion
5
+ transformer. The two crops were trained independently from their original bases.
6
+
7
+ | Crop | Component | Final training point | Parameter file | Size |
8
+ |---|---|---|---|---:|
9
+ | Rice | PhenoClock | Step 2,500; epoch 2 | `checkpoints/rice/phenoclock/adapter_model.safetensors` | 933,974,032 bytes |
10
+ | Rice | Rooted Renderer | Epoch 2 (`epoch-1` in training) | `checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors` | 14,230,284,584 bytes |
11
+ | Maize | PhenoClock | Step 800; epoch 2 | `checkpoints/maize/phenoclock/adapter_model.safetensors` | 467,063,552 bytes |
12
+ | Maize | Rooted Renderer | Epoch 2 (`epoch-1` in training) | `checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors` | 14,230,284,584 bytes |
13
+
14
+ The four weight files total **29,861,606,752 bytes** (29.86 GB; 27.81 GiB).
15
+ Rice's saved adapter uses FP32; maize's uses BF16. Both have the same rank-32 /
16
+ alpha-64 architecture. The release preserves each original weight file without
17
+ casting, merging, or quantization. Renderer weights are BF16 full diffusion
18
+ transformers, not LoRA adapters and not complete image-generation pipelines.
19
+
20
+ The release includes no Simple FT or other baseline weights, intermediate
21
+ checkpoints, optimizer states, or training logs. Tutor is a target-informed
22
+ reference using the same Renderer as Ours; it does not require a separate model.
23
+
24
+ ## Use the matching code release
25
+
26
+ Both repositories identify this release as **`agrowm-mainline-2026-11-24`** in
27
+ [configs/model_release.json](../configs/model_release.json). The code repository
28
+ contains no weight files; the model repository contains the matching code snapshot
29
+ and `checkpoints/`. See [REPOSITORIES.md](REPOSITORIES.md) for how to connect the
30
+ two local checkouts or download the model files into a code checkout.
31
+
32
+ ## Files and integrity
33
+
34
+ ```text
35
+ checkpoints/
36
+ manifest.json
37
+ SHA256SUMS
38
+ rice/
39
+ phenoclock/
40
+ adapter_config.json
41
+ adapter_model.safetensors
42
+ additional_config.json
43
+ rooted_renderer/
44
+ config.json
45
+ diffusion_pytorch_model.safetensors
46
+ maize/
47
+ phenoclock/
48
+ adapter_config.json
49
+ adapter_model.safetensors
50
+ additional_config.json
51
+ rooted_renderer/
52
+ config.json
53
+ diffusion_pytorch_model.safetensors
54
+ ```
55
+
56
+ The model repository's `checkpoints/manifest.json` records component identities,
57
+ tensor dtypes, file sizes, and SHA-256 digests. Both repositories carry the same
58
+ weight identities in [configs/model_release.json](../configs/model_release.json).
59
+ After placing the model repository's `checkpoints/` directory in your checkout,
60
+ verify its `checkpoints/SHA256SUMS` from the checkout root:
61
+
62
+ ```bash
63
+ # Linux
64
+ sha256sum -c checkpoints/SHA256SUMS
65
+
66
+ # macOS
67
+ shasum -a 256 -c checkpoints/SHA256SUMS
68
+ ```
69
+
70
+ Obtain the actual large files when downloading this repository. A Git LFS pointer
71
+ is a small text file, not a usable checkpoint. Use `hf download` or run
72
+ `git lfs pull` in a Git clone.
73
+
74
+ The adapter configurations identify `Qwen/Qwen3.8-27B` instead of the original
75
+ machine-local base path. All other adapter fields are preserved. Each Renderer
76
+ configuration matches the architecture used by the original base transformer.
77
+
78
+ ## Required base models
79
+
80
+ - [Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B): the frozen Planner
81
+ backbone, tokenizer, image processor and template support.
82
+ - [Qwen Image 2.1](https://huggingface.co/Qwen/Qwen-Image-2.1): the image pipeline's
83
+ frozen text encoder, VAE, scheduler and other supporting files.
84
+
85
+ Download these separately and set their local directories in the settings file.
86
+ The supplied inference scripts use local model paths and offline loading. The
87
+ repository root is a composite model release, not a single Transformers model.
88
+ Install the separate Planner and Renderer stacks in [INSTALL.md](INSTALL.md).
89
+
90
+ ## Run the existing benchmark workflow
91
+
92
+ The released parameters let you skip training. First place or link the model
93
+ repository's `checkpoints/` directory in your code checkout as described in
94
+ [REPOSITORIES.md](REPOSITORIES.md); the model checkout already has it. Prepare the data according to
95
+ [DATA.md](DATA.md); the current workflow consumes prepared validation manifests.
96
+ Its source-only request builder strips target photos, labels and teacher answers
97
+ from model inputs.
98
+
99
+ These commands use the default `run_root=runs`. If you change `run_root`, also
100
+ replace the Planner `--output-dir` below with
101
+ `<your run_root>/$crop/planner_inference`; the Renderer reads the script manifest
102
+ from that configured location. Explicit data-preparation paths must likewise
103
+ match your `data_root`.
104
+
105
+ ```bash
106
+ cp configs/released.example.json configs/local.released.json
107
+ # Edit the base-model, data, Python-environment and output paths.
108
+ python scripts/configure.py \
109
+ --settings configs/local.released.json --output configs/local-released
110
+
111
+ crop=rice # or maize
112
+ .venv-planner/bin/python scripts/launch_planner_inference.py \
113
+ --config "configs/local-released/$crop/planner_infer.json" \
114
+ --output-dir "runs/$crop/planner_inference" \
115
+ --batch-size 1 --gpu-groups '0,1'
116
+
117
+ .venv-renderer/bin/python scripts/run_executor_inference.py \
118
+ --config "configs/local-released/$crop/executor_infer.json" \
119
+ --variant predicted_cot
120
+ ```
121
+
122
+ Choose a GPU group that fits the Planner and adjust its memory limits for the
123
+ hardware. The released settings select both the crop's Planner adapter and its
124
+ Renderer file. `scripts/configure.py` writes that Renderer path into the Ours/Tutor
125
+ inference configuration; Simple FT keeps its independent training-output path.
126
+ The optional `--checkpoint` flag remains available for an explicit override.
127
+ Keep crop identities aligned: do not combine a rice adapter with a maize Renderer.
128
+
129
+ Continue with the evaluation commands in [RUNNING.md](RUNNING.md). Invalid scripts
130
+ are recorded rather than replaced by target-informed supervision. Reproducing
131
+ paper metrics also requires the original prepared inputs, seeds and full gallery.
132
+
133
+ ## Load the Renderer component directly
134
+
135
+ For integration into another application, the Renderer directories are compatible
136
+ with the pinned Diffusers `QwenImage21Transformer2DModel` class:
137
+
138
+ ```python
139
+ import torch
140
+ from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel
141
+
142
+ crop = "rice"
143
+ transformer = QwenImage21Transformer2DModel.from_pretrained(
144
+ f"checkpoints/{crop}/rooted_renderer",
145
+ torch_dtype=torch.bfloat16,
146
+ local_files_only=True,
147
+ )
148
+ pipe = QwenImage21Pipeline.from_pretrained(
149
+ "models/Qwen-Image-2.1",
150
+ transformer=transformer,
151
+ torch_dtype=torch.bfloat16,
152
+ local_files_only=True,
153
+ ).to("cuda")
154
+ ```
155
+
156
+ This loads the image component only. Use the source image, crop-specific prompt,
157
+ predicted Growth Script, native geometry, seed, and inference settings defined by
158
+ the mainline workflow when generating a forecast. A generic text-to-image prompt
159
+ does not reproduce AgroWM.
160
+
161
+ ## Intended use and limitations
162
+
163
+ AgroWM supports research on developmental reasoning, source-conditioned crop image prediction, structured supervision, and phenotype-aware evaluation.
164
+
165
+ - Evidence is limited to the prepared rice and maize distributions, including white-background plant photographs. Field images, new crops and unseen cultivars require separate validation.
166
+ - The horizon describes elapsed time. Weather, treatment, soil and management records are not explicit model inputs.
167
+ - A forecast is a generated appearance, not an observed future. Traits are image-plane proxies rather than calibrated physical measurements or yield predictions.
168
+ - Growth-balanced pair selection, preprocessing and gallery construction affect the evaluation. A selected example is not a substitute for full validation.
169
+ - Errors in predicted stages and numeric targets can propagate to image generation. Tutor results use privileged future information and are a reference, not a deployable fallback.
170
+ - Exact historical comparisons require their original prompts, model versions, seeds and outputs. Closed API models may change.
171
+
172
+ ## License
173
+
174
+ **Built with Qwen.** PhenoClock adapters use [Apache-2.0](../LICENSE).
175
+ Rooted Renderer weights use the [Qwen Research License](../licenses/Qwen-Image-2.1-LICENSE.txt),
176
+ including its non-commercial research/evaluation restriction. Commercial use of
177
+ the Renderer requires a separate upstream license. See [LICENSES.md](../LICENSES.md)
178
+ for the component-specific scope and [NOTICE](../NOTICE) for attribution.
docs/DATA.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data and base models
2
+
3
+ Prepare the dataset, teacher annotations and third-party base models separately,
4
+ following their access and redistribution terms. DINOv2 is also an external
5
+ evaluation dependency. The training workflow produces the local model files used
6
+ by AgroWM inference; see [RUNNING.md](RUNNING.md).
7
+
8
+ ## Portable pair manifest
9
+
10
+ `prepare_data.py` consumes a JSONL file with one object per image forecast. Paths
11
+ are absolute or relative to the directory containing this JSONL file. Inputs are
12
+ already cleaned, white-background RGB photographs at the experiment resolution;
13
+ this release starts after background removal and teacher annotation.
14
+
15
+ | Field | Contract |
16
+ |---|---|
17
+ | `pair_id` | Unique string across both splits |
18
+ | `pair_group_id` | Pair grouping ID; rice front/top share one group |
19
+ | `plant_id` | Biological plant ID; no train/val overlap |
20
+ | `split` | `train` or `val`, using the frozen experimental split |
21
+ | `view` | Rice `front`/`side0` or `top`; maize `sv1`/`side0` |
22
+ | `accession_id` | Required for rice; cultivar/accession condition |
23
+ | `actual_interval_days` | Positive integer; rice prompts derive rounded weeks |
24
+ | `source_image_path`, `target_image_path` | Real paired photographs |
25
+ | `source_stage`, `target_stage` | Original evaluation labels, preserved verbatim |
26
+ | `source_stage_id`, `target_stage_id` | Optional alternative if evaluation already uses these IDs |
27
+ | `source_image_id`, `target_image_id` | Stable canonical image/event identifiers |
28
+ | `source_capture_date`, `target_capture_date` | Preserve original capture dates when available |
29
+ | `seed` | Required explicit integer; preserve the original per-query seed |
30
+ | `teacher_cot` or `teacher_cot_path` | Exact rendered `<GROWTH_COT>` teacher block |
31
+ | `horizon_bucket` | Required for maize validation: original `short`, `mid` or `long` grouping; optional for rice |
32
+
33
+ **Evaluation stage labels are distinct from script supervision.** In particular,
34
+ rice's historical gallery labels can be names such as `Tillering` or `Grain
35
+ filling`; do not replace them with the script's finer S1–S8 labels. If both label
36
+ and ID fields exist, evaluation uses `source_stage` / `target_stage`.
37
+
38
+ Teacher scripts contain target information for training supervision. They appear
39
+ only in the assistant response and Tutor condition; source-only Planner queries
40
+ are constructed from an allowlist. Maize's stage guide is part of the system
41
+ instructions, while the query does not supply the plant's true S1–S9 labels.
42
+
43
+ ```bash
44
+ python scripts/prepare_data.py --crop rice --pairs /datasets/rice/pairs.jsonl \
45
+ --output data/rice --paper-split
46
+ python scripts/prepare_data.py --crop maize --pairs /datasets/maize/pairs.jsonl \
47
+ --output data/maize --paper-split
48
+ ```
49
+
50
+ The importer validates every image, unique IDs, consistent image metadata, split
51
+ isolation, teacher format and seeds before writing. It preserves row order within
52
+ each split and refuses an existing destination. It does not resample pairs or
53
+ invent missing teacher text, labels or seeds. Omitting `--paper-split` permits small
54
+ contract tests; the published training launcher still requires the full train
55
+ count. Small examples are not paper evaluations.
56
+
57
+ | Crop | Train | Validation | Validation plants | Image size (width × height) |
58
+ |---|---:|---:|---:|---|
59
+ | Rice | 20,000 | 2,000 | 79 | Front 672×896; top 896×672 |
60
+ | Maize | 6,400 | 1,600 | 84 | Side 768×1280 |
61
+
62
+ The split is by plant. In rice, 78 of the 79 validation cultivars also occur in
63
+ training; the validation set therefore does not establish unseen-cultivar performance.
64
+
65
+ The importer writes:
66
+
67
+ ```text
68
+ data/<crop>/
69
+ package_manifest.json
70
+ planner/{train,val}.jsonl
71
+ planner/package_manifest.json
72
+ executor/{simple,teacher_cot}/{train,val}.jsonl
73
+ executor/package_manifest.json
74
+ evaluation/manifest.jsonl
75
+ evaluation/seeds.jsonl
76
+ evaluation/source_copy/results.jsonl
77
+ ```
78
+
79
+ Images are not copied. Prepared files point to resolved local images. Re-run
80
+ preparation from the portable pair manifest on a new machine rather than blindly
81
+ replacing absolute paths in frozen audit files. The input and generated file
82
+ checksums are recorded. A prepared package is valid only for its corresponding
83
+ image tree. Data access and the frozen portable pair manifest must accompany the
84
+ future dataset release.
85
+
86
+ ## Base-model layout
87
+
88
+ Provide a complete local Qwen3.8-27B directory (config, tokenizer, safetensors
89
+ index and all shards). Provide the complete Qwen Image 2.1 directory:
90
+
91
+ ```text
92
+ models/Qwen-Image-2.1/
93
+ model_index.json
94
+ transformer/ # config, index and all diffusion_pytorch_model-*.safetensors
95
+ text_encoder/ # all model-*.safetensors
96
+ vae/diffusion_pytorch_model.safetensors
97
+ processor/
98
+ tokenizer/ # if supplied by the base-model package
99
+ scheduler/
100
+ ```
101
+
102
+ Keep the provider's original configuration files. Inference converts the trained
103
+ DiffSynth DiT checkpoint into a separate Diffusers loading view; it does not edit
104
+ the base weights. DINOv2 Base uses `dinov2_vitb14_pretrain.pth`, passed explicitly
105
+ to the evaluation command.
106
+
107
+ ## Local training outputs
108
+
109
+ After training, set the Planner adapter path to the directory produced by your own
110
+ run; ms-swift creates a timestamped parent directory. The Simple and text Renderer
111
+ runs produce separate output directories. Ours and Tutor use the text Renderer,
112
+ while Simple uses its independently trained model. The inference commands and
113
+ local path settings are documented in [RUNNING.md](RUNNING.md).
114
+
115
+ Rebuild latent caches from the prepared metadata in a fresh package. Do not treat
116
+ leftover completion markers from deleted caches as usable tensors.
docs/DEVELOPMENT.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tests and development
2
+
3
+ Run from the repository root after installing the relevant environment and
4
+ `python -m pip install --no-deps -e .`. The package is intended to be used as a
5
+ checkout, so protocol and script paths remain available.
6
+
7
+ ## CPU contract checks
8
+
9
+ ```bash
10
+ python -m compileall -q src scripts tests
11
+ python -m unittest -v \
12
+ tests.test_release_data tests.test_release_config tests.test_mainline_protocols \
13
+ tests.test_text_executor_release \
14
+ tests.test_evaluation_io tests.test_image_evaluation_workers \
15
+ tests.test_image_geometry_evaluation tests.test_v9_image_metrics
16
+ ```
17
+
18
+ These checks cover preparation, source-only inputs, prompt formats, configuration,
19
+ identity and resume behavior, image geometry and metric contracts. The text
20
+ inference integration test substitutes the GPU/model boundary while exercising
21
+ real preparation, manifests, worker/supervisor control flow, image I/O and ledgers.
22
+
23
+ ## Complete unit suite
24
+
25
+ Use the Renderer dependencies for tests that need Torch, Accelerate, timm and
26
+ Transformers:
27
+
28
+ ```bash
29
+ python -m unittest discover -s tests -v
30
+ ```
31
+
32
+ No unit test starts a full training run, downloads model weights or calls a paid
33
+ API. Passing the suite does not establish GPU reproduction of the paper.
34
+
35
+ ## Compatibility rules
36
+
37
+ - Preserve prompt text, schema IDs, frozen splits, row order, seeds and crop units.
38
+ - Keep the internal `wgsr_v9` namespace stable for existing experiment artifacts.
39
+ - Keep text-script numeric fields; they are distinct from numeric injection.
40
+ - Tutor is target-informed supervision/reference, never an inference fallback.
41
+ - Keep local configs, credentials, data, training states and generated results outside Git.
42
+ - The code repository ignores all local checkpoints. The paired model repository
43
+ tracks only the four selected parameter files under `checkpoints/` with Git LFS.
44
+ - Keep the shared files of both releases byte-identical; see [REPOSITORIES.md](REPOSITORIES.md).
docs/INSTALL.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation
2
+
3
+ Use Linux, Python 3.12 and NVIDIA GPUs for training and inference. Data preparation
4
+ and the CPU contract tests also work on macOS. Run commands from this repository's
5
+ root. Keep Planner and Renderer environments separate: their PEFT and DeepSpeed
6
+ versions differ.
7
+
8
+ ## CPU preparation and inspection
9
+
10
+ ```bash
11
+ python3.12 -m venv .venv-cpu
12
+ source .venv-cpu/bin/activate
13
+ python -m pip install -r requirements/cpu.txt
14
+ python -m pip install --no-deps -e .
15
+ ```
16
+
17
+ ## Planner
18
+
19
+ ```bash
20
+ python3.12 -m venv .venv-planner
21
+ source .venv-planner/bin/activate
22
+ python -m pip install torch==2.6.0 torchvision==0.21.0 \
23
+ --index-url https://download.pytorch.org/whl/cu124
24
+ python -m pip install -r requirements/planner.txt
25
+ python -m pip install -r requirements/cpu.txt
26
+ python -m pip install --no-deps -e .
27
+ ```
28
+
29
+ The pinned stack uses ms-swift 4.6.0 / Transformers 5.19.0 with the `qwen3_8`
30
+ template. `causal-conv1d` and `flash-linear-attention` may require compatible wheels
31
+ or a CUDA development toolchain. Match the Python version, Torch version, CUDA
32
+ version and C++ ABI; do not substitute an arbitrary wheel. The original rice run
33
+ used 2 large-memory GPUs with FSDP2, while maize used 8 × 24 GB GPUs with ZeRO-3.
34
+
35
+ ## Renderer and evaluation
36
+
37
+ ```bash
38
+ python3.12 -m venv .venv-renderer
39
+ source .venv-renderer/bin/activate
40
+ python -m pip install torch==2.6.0 torchvision==0.21.0 \
41
+ --index-url https://download.pytorch.org/whl/cu124
42
+ python -m pip install -r requirements/renderer.txt
43
+ mkdir -p third_party
44
+ git clone https://github.com/modelscope/DiffSynth-Studio.git third_party/DiffSynth-Studio
45
+ git -C third_party/DiffSynth-Studio checkout 60b709c4dab8eeabce06ee9bc168328ed4c780e8
46
+ python -m pip install -e third_party/DiffSynth-Studio
47
+ # Reapply the experiment pins if the upstream install changed shared dependencies.
48
+ python -m pip install -r requirements/renderer.txt
49
+ python -m pip install --no-deps -e .
50
+ python -m pip check
51
+ python -c 'from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel; from diffsynth.pipelines.qwen_image_21 import QwenImage21Pipeline'
52
+ ```
53
+
54
+ Training checks the DiffSynth Git commit and requires a clean checkout. Inference
55
+ uses Diffusers commit `578c9b2c6636ab2424a0e56186268b83623656b2`, which provides the
56
+ Qwen Image 2.1 classes. The versions above were read from the working experiment
57
+ environments; installation on a new machine still depends on upstream package
58
+ and model availability. They are not a claim of a newly tested clean installation.
59
+
60
+ The original Renderer recipe uses 8 GPUs, batch 2 per GPU and global batch 16.
61
+ Cache creation requires substantial scratch storage; the launcher checks for at
62
+ least 150 GiB free. Public configs use disk-backed caches by default to avoid a
63
+ machine-specific `/dev/shm` layout. This changes cache placement, not the math.
64
+
65
+ ## Use the released checkpoints
66
+
67
+ For inference with the paired AgroWM model release, use `configs/released.example.json`
68
+ and follow [CHECKPOINTS.md](CHECKPOINTS.md). Original base models are still required.
69
+ The settings below are the separate route for training your own models.
70
+
71
+ ## Configure paths
72
+
73
+ ```bash
74
+ cp configs/local.example.json configs/local.json
75
+ # Edit all model, data, environment and output locations in this file.
76
+ python scripts/configure.py --settings configs/local.json
77
+ ```
78
+
79
+ Relative paths in the settings file resolve against the repository root; `~` is
80
+ expanded. Generated JSON configs contain resolved absolute paths and are ignored
81
+ by Git. The generator refuses to overwrite an existing config directory; use
82
+ `--output configs/local-v2` when changing settings, and pass that location to the
83
+ commands in RUNNING.md. Keep custom local directories out of Git as well.
84
+
85
+ The two Planner adapter fields start as `null`. After training, set each to the
86
+ actual final `checkpoint-*` directory and generate a new config directory.
87
+ The optional `rice_renderer_checkpoint` and `maize_renderer_checkpoint` fields
88
+ also default to `null`, so the training workflow selects its standard final
89
+ Renderer output. Set them when using the paired model release or another local
90
+ Renderer directory; only the Ours/Tutor path is overridden, not Simple FT or
91
+ the untrained base controls.
92
+ An absent adapter is an error for Planner inference, not a request to use the base
93
+ model. Inference GPU counts are configurable. Training topology is validated
94
+ against the published recipe; fewer-GPU training requires an explicitly revised
95
+ recipe and is not silently presented as the same experiment.
docs/PROTOCOL.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experimental protocol
2
+
3
+ ## Inputs and supervision
4
+
5
+ | Property | Rice | Maize |
6
+ |---|---|---|
7
+ | Query | Source image, accession, front/top view, rounded weeks | Source image, plant ID, side view, exact days |
8
+ | Horizon | `max(1, (actual_interval_days + 3) // 7)` | Positive integer days |
9
+ | Planner output | Direct `<GROWTH_COT>`; native thinking disabled | Same wrapper and thinking policy |
10
+ | Stage vocabulary in script | S1–S8 | S1–S9 |
11
+ | Native image geometry | 672×896 front; 896×672 top | 768×1280 side |
12
+ | Training | Independently from base models | Independently from base models |
13
+
14
+ Source/target stage labels and target images are evaluation/training metadata,
15
+ not query conditions. The system prompt contains the general stage vocabulary;
16
+ it does not reveal the queried plant's annotated stage. A Growth Script has three
17
+ ordered parts: **Stage reasoning**, **Growth plan**, **Target phenotype**. Numeric
18
+ slots depend on crop and view. See the exact files in
19
+ `protocols/planner_v3_direct_metric_named_weeks/`,
20
+ `protocols/qwen_image21_executor_v9_v3_metric_named_weeks/` and
21
+ `protocols/maize_four_way_v1/`. Small synthetic examples are under `tests/fixtures/`;
22
+ they are format examples, not measured plant observations.
23
+
24
+ ## Training configuration
25
+
26
+ | Setting | Rice Planner | Maize Planner | Renderer / Simple FT |
27
+ |---|---|---|---|
28
+ | Base | Qwen3.8-27B | Qwen3.8-27B | Qwen Image 2.1 |
29
+ | Trainable parameters | LoRA, all-linear; vision/aligner frozen | Same | Full DiT; text encoder/VAE frozen via caches |
30
+ | LoRA | rank 32, alpha 64, dropout 0.05 | Same | Not used |
31
+ | Epochs / global batch | 2 / 16 | 2 / 16 | 2 / 16 |
32
+ | Devices / per-device batch | 2 / 8 | 8 / 2 | 8 / 2 |
33
+ | Accumulation | 1 | 1 | 1 |
34
+ | Distribution | FSDP2 | ZeRO-3 | ZeRO-3 |
35
+ | Learning rate | 1e-4 | 1e-4 | 1e-5 |
36
+ | Schedule | Cosine, minimum 1e-6 | Same | 10% warmup, 60% stable, 30% cosine |
37
+ | Warmup | 3% | 3% | 10%, starts at zero |
38
+ | Final LR | 1e-6 | 1e-6 | 1e-6 |
39
+ | Weight decay | 0 | 0 | 0.01 |
40
+ | Max text length | 4096 | 4096 | Model pipeline |
41
+ | Max pixels | 602112 | 983040 | 602112 rice; 983040 maize |
42
+ | Seed | 42 (data seed 42) | Same | 20261030 |
43
+ | Precision | BF16 | BF16 | BF16 |
44
+
45
+ Grouped Planner loss is `0.1 L_stage + 0.4 L_metric + 0.5 L_text`. Token losses are
46
+ averaged within fields, then fields and examples are averaged according to the
47
+ versioned implementation. Prompt/image/padding tokens are excluded. This is not
48
+ equivalent to weighting the aggregate ordinary next-token loss.
49
+
50
+ Image inference uses 20 steps, original per-query seeds and native image geometry.
51
+ The shared text Renderer checkpoint serves both Planner predictions and the
52
+ Tutor reference. Simple FT is a separate model initialized from the base.
53
+
54
+ ## Evaluation
55
+
56
+ - DINO cosine uses DINOv2 Base. timm preprocessing is bicubic resize/518×518 center
57
+ crop with ImageNet normalization; use the pinned implementation.
58
+ - Stage R@1 is nearest-image retrieval within the same plant/view sequence. It is
59
+ not the Planner's stage classification accuracy. Rice Stage and Event recall
60
+ differ; maize has one image per plant/view/stage, so they coincide.
61
+ - Rice gallery eligibility is at least 5 canonical images per plant/view. Maize
62
+ requires at least 2. Canonical images are collected from scored evaluation rows.
63
+ - Rice Height is `100 * (H - y_min) / H`, valid for front view only. Top-view Height
64
+ is unavailable. Do not replace it with the pixel evaluator's legacy extent.
65
+ - Maize Height is computed by the dedicated phenotype script using the registered
66
+ crop measurement. It is an image proxy in percentage points, not centimeters.
67
+ - Area, Density and yellow/brown measures are image-plane proxies. Empty masks or
68
+ insufficient color coverage remain unavailable; never replace missing values
69
+ with zero. Report each metric's valid denominator.
70
+ - Preserve near-white normalization, alpha compositing and original stage labels.
71
+ Paired uncertainty analyses should cluster by plant and use valid intersections.
docs/REPOSITORIES.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Matching code and model repositories
2
+
3
+ Release **`agrowm-mainline-2026-11-24`** has two distributions:
4
+
5
+ | Distribution | Contents | Local checkpoint handling |
6
+ |---|---|---|
7
+ | [GitHub code repository](https://github.com/ECNU-ICALK/ArgoWM) | Training, inference, evaluation, prompts, recipes, examples and shared documentation | Weights are obtained separately and ignored by Git |
8
+ | [Hugging Face model repository](https://huggingface.co/ecnu-icalk/ArgoWM) | The same code snapshot plus the four final Ours parameter files | `checkpoints/` is included; parameter files use Git LFS |
9
+
10
+ Both contain the same [model release catalog](../configs/model_release.json).
11
+ It records the release ID, component paths, base models, crop-specific protocols,
12
+ weight sizes and SHA-256 digests. The model repository's
13
+ `checkpoints/manifest.json` carries the same release ID and component identities.
14
+ Do not combine the rice Planner with the maize Renderer or substitute Simple FT
15
+ for the released text Renderer.
16
+
17
+ The matching trees are `src/`, `scripts/`, `configs/`, `protocols/`,
18
+ `requirements/`, `tests/`, `.github/`, `docs/`, `assets/`, `examples/`, and
19
+ `licenses/`, together with `pyproject.toml` and the license/notice files.
20
+ The two READMEs describe the distribution they accompany; `.gitignore` and
21
+ `.gitattributes` differ to keep weights out of the code repository.
22
+
23
+ ## Use the two local folders together
24
+
25
+ If you have both distributions next to one another, run the following **from the
26
+ code repository root**. Replace the model-folder path if your layout differs:
27
+
28
+ ```bash
29
+ ln -s ../AgroWM-HuggingFace/checkpoints checkpoints
30
+ ```
31
+
32
+ The model directory must contain the complete `checkpoints/` tree before linking.
33
+ Create this link only when the code checkout has no `checkpoints` entry. If it
34
+ already contains weights, inspect that directory before making changes. The link
35
+ does not copy the 29.86 GB of parameters, and the code repository ignores it.
36
+
37
+ Alternatively, keep the models outside the code checkout and edit these four
38
+ fields in your own settings JSON to their actual locations:
39
+
40
+ ```json
41
+ {
42
+ "rice_planner_adapter": "/path/to/model-release/checkpoints/rice/phenoclock",
43
+ "rice_renderer_checkpoint": "/path/to/model-release/checkpoints/rice/rooted_renderer/diffusion_pytorch_model.safetensors",
44
+ "maize_planner_adapter": "/path/to/model-release/checkpoints/maize/phenoclock",
45
+ "maize_renderer_checkpoint": "/path/to/model-release/checkpoints/maize/rooted_renderer/diffusion_pytorch_model.safetensors"
46
+ }
47
+ ```
48
+
49
+ Use `configs/released.example.json` as the starting point so base-model, data and
50
+ environment paths are also configured. Settings resolve relative paths against
51
+ the code checkout root and accept absolute paths.
52
+
53
+ ## Obtain model files from the Hub
54
+
55
+ After the model files are published to [ecnu-icalk/ArgoWM](https://huggingface.co/ecnu-icalk/ArgoWM),
56
+ run the command from the code checkout root, using an environment with the
57
+ Hugging Face CLI installed:
58
+
59
+ ```bash
60
+ hf download ecnu-icalk/ArgoWM \
61
+ --repo-type model --include 'checkpoints/**' --local-dir .
62
+ ```
63
+
64
+ This downloads only the checkpoint tree into the code checkout and preserves its
65
+ code files. It needs approximately 30 GB of free space. The model files require
66
+ the [component-specific licenses](../LICENSES.md); downloading the code alone
67
+ does not supply the base models or dataset.
68
+
69
+ ## Configure and run either distribution
70
+
71
+ Once the checkpoints are available, the same commands work in either checkout:
72
+
73
+ These commands use the default `run_root=runs`. If you change `run_root`, also
74
+ replace the Planner `--output-dir` below with
75
+ `<your run_root>/$crop/planner_inference`; the Renderer reads the script manifest
76
+ from that configured location. Explicit data-preparation paths must likewise
77
+ match your `data_root`.
78
+
79
+ ```bash
80
+ cp configs/released.example.json configs/local.released.json
81
+ # Edit base-model, data, environment and output locations.
82
+ python scripts/configure.py \
83
+ --settings configs/local.released.json --output configs/local-released
84
+
85
+ crop=rice # or maize
86
+ .venv-planner/bin/python scripts/launch_planner_inference.py \
87
+ --config "configs/local-released/$crop/planner_infer.json" \
88
+ --output-dir "runs/$crop/planner_inference" \
89
+ --batch-size 1 --gpu-groups '0,1'
90
+
91
+ .venv-renderer/bin/python scripts/run_executor_inference.py \
92
+ --config "configs/local-released/$crop/executor_infer.json" \
93
+ --variant predicted_cot
94
+ ```
95
+
96
+ Prepare the environments and data first; see [INSTALL.md](INSTALL.md) and
97
+ [DATA.md](DATA.md). The generated Planner and Renderer configurations point to
98
+ the matched crop components automatically. Simple FT and the untrained base
99
+ controls retain their independent paths. To train your own models, use
100
+ `configs/local.example.json`; its optional checkpoint fields default to `null`,
101
+ preserving the original training-output layout.
102
+
103
+ ## Verify the downloaded parameters
104
+
105
+ After copying, linking, or downloading the complete checkpoint tree, run from the
106
+ checkout root:
107
+
108
+ ```bash
109
+ # Linux
110
+ sha256sum -c checkpoints/SHA256SUMS
111
+
112
+ # macOS
113
+ shasum -a 256 -c checkpoints/SHA256SUMS
114
+ ```
115
+
116
+ Match `release_id` in `configs/model_release.json` and
117
+ `checkpoints/manifest.json`, and retain the corresponding protocol files. Changes
118
+ to those prompts, crop units or preprocessing can change results even when the
119
+ weight hashes match.
docs/RESULTS.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reported results and comparison scope
2
+
3
+ Values below are transcribed from Tables 1–2 and the long-horizon analysis in
4
+ *Can World Models Predict Rice Growth? Toward Agricultural World Models*.
5
+ They are reported manuscript results, not measurements rerun for this repository.
6
+ The machine-readable transcription is [paper_results.json](paper_results.json).
7
+
8
+ ## Rice: selected comparisons
9
+
10
+ DINO is higher-is-better. Area, Height, Density and Yellow are image-proxy errors
11
+ in percentage points, lower-is-better. Stage and Event R@1 are percentages,
12
+ higher-is-better. This table selects relevant comparisons rather than reproducing
13
+ all external baselines in the manuscript.
14
+
15
+ | Method | DINO | Area | Height | Density | Yellow | Stage R@1 | Event R@1 |
16
+ |---|---:|---:|---:|---:|---:|---:|---:|
17
+ | GPT Image 2 | 0.709 | 5.59 | 11.49 | 6.31 | 24.40 | 35.3 | 12.8 |
18
+ | GPT Image 2.5 | 0.721 | 6.92 | 12.57 | 6.70 | 29.17 | 34.8 | 10.8 |
19
+ | Qwen Image 2.1 | 0.693 | 7.85 | 18.28 | 6.83 | 32.31 | 24.0 | 1.1 |
20
+ | Source copy | 0.702 | 7.17 | 19.06 | 6.24 | 29.33 | 23.2 | 0.0 |
21
+ | Qwen Image 2.1 FT / Simple | 0.834 | 3.73 | 7.83 | 5.33 | 11.43 | 47.4 | 22.5 |
22
+ | **AgroWM** | **0.860** | **3.51** | **7.43** | **4.98** | **10.00** | **54.6** | **24.8** |
23
+
24
+ At 9–20 weeks, AgroWM achieves **46.4% Stage R@1**, compared with **35.7%** for
25
+ Simple FT: a **10.7 percentage-point** difference.
26
+
27
+ ## Maize
28
+
29
+ | Method | DINO ↑ | Area error (pp) ↓ | Height error (pp) ↓ | Stage R@1 (%) ↑ |
30
+ |---|---:|---:|---:|---:|
31
+ | Source copy | 0.522 | 3.62 | 33.02 | 0.0 |
32
+ | GPT Image 2 | 0.727 | 2.63 | 16.64 | 21.1 |
33
+ | Qwen Image 2.1 FT / Simple | 0.764 | 1.97 | 11.12 | 30.1 |
34
+ | **AgroWM** | **0.795** | **1.73** | **10.61** | **30.9** |
35
+
36
+ Maize uses independently trained models and exact day intervals. It is a second
37
+ crop experiment, not zero-shot transfer of the rice weights. Its Stage R@1 gain
38
+ over Simple FT is 0.8 points.
39
+
40
+ ## What the metrics measure
41
+
42
+ - **DINO:** DINOv2 Base feature cosine similarity, using the pinned preprocessing.
43
+ - **Area / Height / Density / Yellow:** visible plant proxies in the prepared
44
+ image plane. Rice Height is front-view-only; use the dedicated geometry code.
45
+ Maize Area/Height come from the maize phenotype evaluator.
46
+ - **Stage R@1:** the nearest retrieved image has the target stage, within a
47
+ plant/view-specific gallery. It does not score the Planner's stage text.
48
+ - **Event R@1:** the retrieved image matches the target image/event. Maize's
49
+ one-image-per-stage setup makes stage and event retrieval coincide.
50
+
51
+ The nominal validation sets contain 2,000 rice and 1,600 maize queries. A nominal
52
+ query count is not automatically every metric's denominator: rice Height uses
53
+ front views only, retrieval applies gallery eligibility, and phenotype scores
54
+ retain metric-specific validity gates. Use the emitted per-metric counts.
55
+
56
+ Rice retrieval requires at least five canonical images per plant/view; maize
57
+ requires two. Galleries are constructed from canonical images present in the
58
+ scored evaluation rows. Selecting only a few successful examples changes the
59
+ retrieval task. Preserve the complete aligned output set, native image geometry,
60
+ original stage labels and frozen per-query seeds.
61
+
62
+ ## Public execution conditions
63
+
64
+ | Condition | Script | Image generator | Source image |
65
+ |---|---|---|---|
66
+ | AgroWM / Ours | Predicted by PhenoClock | Trained text Rooted Renderer | Yes |
67
+ | Simple FT | None | Independently trained Qwen Image 2.1 | Yes |
68
+ | Tutor reference | Target-informed teacher | Same Renderer as Ours | Yes |
69
+ | Base + predicted script | Predicted by PhenoClock | Original Qwen Image 2.1 | Yes |
70
+ | Current Qwen zero-shot | None | Original Qwen Image 2.1 | Yes |
71
+ | Source copy | None | No generation | Copied |
72
+
73
+ The public **Base + predicted script** command is source-conditioned. The paper's
74
+ historical **w/o Rooted Renderer** row used a script-only base generator without
75
+ the source photograph, so the command above must not be assigned that row's score.
76
+ The current zero-shot command uses the full current Simple prompt; archived rice
77
+ baseline prompts can differ. Maize zero-shot qualitative examples are not a full
78
+ 1,600-query benchmark. Preserve these distinctions when reporting reruns.
79
+
80
+ External baseline outputs can be evaluated through the result-ledger interface in
81
+ [RUNNING.md](RUNNING.md). Closed-model APIs and the full training stacks of external
82
+ methods are not included. Exact reproduction requires the original prepared data,
83
+ model versions, prompts, seeds and all relevant preprocessing choices.
docs/RUNNING.md ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mainline experiments
2
+
3
+ For inference using the published Ours weights, start with
4
+ [CHECKPOINTS.md](CHECKPOINTS.md) and continue with the evaluation section here.
5
+ The training workflow below remains available for reproducing Ours and Simple FT.
6
+
7
+ Run from the repository root. First complete INSTALL.md and DATA.md, then generate
8
+ `configs/local/`. Examples below use the default `data/` and `runs/` layout. If you
9
+ changed `data_root` or `run_root`, use those locations in explicit path arguments.
10
+
11
+ Choose the crop once. Both species are trained independently from their base
12
+ models; maize is not zero-shot transfer from rice.
13
+
14
+ ```bash
15
+ crop=rice # or maize
16
+ planner_python=.venv-planner/bin/python
17
+ renderer_python=.venv-renderer/bin/python
18
+ ```
19
+
20
+ ## 1. Train PhenoClock
21
+
22
+ ```bash
23
+ # Preview and validate the prepared package first.
24
+ "$planner_python" scripts/run_planner_sft.py \
25
+ --config "configs/local/$crop/planner_train.json" --print-json
26
+
27
+ # Launch the published recipe.
28
+ "$planner_python" scripts/run_planner_sft.py \
29
+ --config "configs/local/$crop/planner_train.json" --launch
30
+ ```
31
+
32
+ Rice: 2 GPUs, FSDP2, 2,500 updates. Maize: 8 GPUs, ZeRO-3, 800 updates.
33
+ Both use global batch 16, two epochs, LoRA rank 32/alpha 64 and grouped
34
+ stage/metric/text losses 0.1/0.4/0.5. The generated config preserves these settings.
35
+ The public Planner recipe retains one saved checkpoint (`save_total_limit=1`);
36
+ this changes retention, not training.
37
+
38
+ For a bounded runtime smoke check, use `--max-steps 1 --output-dir runs/smoke-planner`
39
+ with the prepared package and `--launch`. This still loads the full model and
40
+ requires the configured hardware. It is not a paper training run.
41
+
42
+ After training, copy the actual final adapter directory into the corresponding
43
+ `rice_planner_adapter` or `maize_planner_adapter` entry of `configs/local.json`.
44
+ Generate fresh configs, for example:
45
+
46
+ ```bash
47
+ python scripts/configure.py --settings configs/local.json --output configs/local-inference
48
+ ```
49
+
50
+ Use `configs/local-inference/` in the inference commands below. Do not choose an
51
+ adapter from another crop or a historical unweighted run.
52
+
53
+ ## 2. Train the Rooted Renderer and Simple FT
54
+
55
+ Both models start from the original Qwen Image 2.1 base. Training the text Renderer
56
+ uses teacher scripts; inference for Ours uses scripts predicted by PhenoClock.
57
+
58
+ ```bash
59
+ # Run sequentially to avoid two jobs competing for the same eight GPUs.
60
+ for variant in teacher_cot simple; do
61
+ "$renderer_python" scripts/run_executor_diffsynth.py \
62
+ --config "configs/local/$crop/executor_$variant.json" \
63
+ --variant "$variant" --phase cache --launch
64
+ "$renderer_python" scripts/run_executor_diffsynth.py \
65
+ --config "configs/local/$crop/executor_$variant.json" \
66
+ --variant "$variant" --phase train --launch
67
+ done
68
+ ```
69
+
70
+ Without `--launch`, the launcher validates the input package and prints commands.
71
+ Even previews require the base model layout and the DiffSynth checkout. Cache
72
+ creation encodes text/images; training consumes the validated cached tensors.
73
+ Never reuse a cache generated from a different prompt or geometry. The trainer
74
+ saves `epoch-0.safetensors` and final `epoch-1.safetensors`; inference selects the
75
+ latter. Completed run directories are protected against accidental overwriting.
76
+
77
+ ## 3. Predict scripts with PhenoClock
78
+
79
+ ```bash
80
+ # One replica over two GPUs; increase groups only when memory/hardware permit.
81
+ "$planner_python" scripts/launch_planner_inference.py \
82
+ --config "configs/local-inference/$crop/planner_infer.json" \
83
+ --output-dir "runs/$crop/planner_inference" \
84
+ --batch-size 1 --gpu-groups '0,1'
85
+ ```
86
+
87
+ For the original 8-GPU inference topology, `--gpu-groups '0,1;2,3;4,5;6,7'` creates
88
+ four replicas. Each group's memory must fit the Planner. Rice's template allows
89
+ 80 GiB per GPU; adjust `max_memory_per_gpu` to the actual hardware when needed.
90
+
91
+ Outputs include the per-query ledger, `executor_prompts.jsonl`, `rejected.jsonl`
92
+ and a summary. Inputs contain source photographs only. The exporter checks IDs,
93
+ source-image identity, prompt format and adapter provenance. Invalid scripts are
94
+ reported; there is no Tutor fallback. Full image inference requires full canonical
95
+ query coverage. If any scripts are rejected, inspect and resolve the run rather
96
+ than silently evaluating a smaller set as the full experiment.
97
+
98
+ ## 4. Generate future images
99
+
100
+ ```bash
101
+ for variant in predicted_cot simple; do
102
+ "$renderer_python" scripts/run_executor_inference.py \
103
+ --config "configs/local-inference/$crop/executor_infer.json" \
104
+ --variant "$variant"
105
+ done
106
+ ```
107
+
108
+ Default inference uses one GPU, 20 steps, BF16 and the frozen per-query seeds.
109
+ Change `renderer_infer_gpus` before materializing configs to shard across GPUs.
110
+ For a bounded image-generation check, append `--row-indices 0`; use a distinct
111
+ `--output-root` for that smoke run. Selected examples do not support full-gallery
112
+ Stage R@1 claims.
113
+
114
+ Optional reference/control conditions:
115
+
116
+ ```bash
117
+ # Tutor: target-informed reference, sharing Ours' Renderer checkpoint.
118
+ "$renderer_python" scripts/run_executor_inference.py \
119
+ --config "configs/local-inference/$crop/executor_infer.json" --variant teacher_cot
120
+
121
+ # Same predicted script with the original, untrained base image generator.
122
+ "$renderer_python" scripts/run_executor_inference.py \
123
+ --config "configs/local-inference/$crop/executor_base.json" --variant predicted_cot --pretrained
124
+
125
+ # Qwen Image 2.1 zero-shot with the current crop's Simple prompt.
126
+ "$renderer_python" scripts/run_executor_inference.py \
127
+ --config "configs/local-inference/$crop/executor_base.json" --variant simple --pretrained
128
+ ```
129
+
130
+ These zero-shot commands use the current full Simple template. Some historical
131
+ rice paper baselines used older prompts; do not call this rerun an exact reproduction
132
+ of their archived numbers. Maize's supplementary zero-shot examples were not a
133
+ complete 1,600-query baseline.
134
+
135
+ ## 5. Evaluate generated images
136
+
137
+ Pixel/foreground/color metrics first, with the same full validation set for each
138
+ method. Source copy is prepared without duplicating image bytes.
139
+
140
+ ```bash
141
+ OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 \
142
+ "$renderer_python" scripts/evaluate_image_results.py \
143
+ --dataset-manifest "data/$crop/evaluation/manifest.jsonl" \
144
+ --result "ours=runs/$crop/executor_inference/predicted_cot" \
145
+ --result "simple=runs/$crop/executor_inference/simple" \
146
+ --result "source_copy=data/$crop/evaluation/source_copy" \
147
+ --output-dir "runs/$crop/evaluation/pixels" --workers 8
148
+ ```
149
+
150
+ Add Tutor or other conditions through additional `--result NAME=PATH` arguments.
151
+ Use native geometry. An explicitly selected `--resize-predictions` protocol is
152
+ required for mismatched external output sizes; raw external images should be kept.
153
+
154
+ DINOv2 Base and retrieval:
155
+
156
+ ```bash
157
+ min_gallery=5
158
+ if [ "$crop" = maize ]; then min_gallery=2; fi
159
+ "$renderer_python" scripts/augment_dino_recall_metrics.py \
160
+ --dataset-manifest "data/$crop/evaluation/manifest.jsonl" \
161
+ --evaluation-dir "runs/$crop/evaluation/pixels" \
162
+ --output-dir "runs/$crop/evaluation/dino" \
163
+ --dino-checkpoint models/dinov2-base/dinov2_vitb14_pretrain.pth \
164
+ --devices 0 --batch-size 64 \
165
+ --min-gallery-images-per-plant-view "$min_gallery" --merge-evaluation
166
+ ```
167
+
168
+ `--merge-evaluation` augments the current pixel outputs in place. The gallery is
169
+ built from canonical images present in the **evaluation rows**, not independently
170
+ from every row of `--dataset-manifest`. Use complete aligned output sets; evaluating
171
+ a selected subset changes the retrieval task and denominators.
172
+
173
+ Rice geometry (front-view Height and foreground Density):
174
+
175
+ ```bash
176
+ "$renderer_python" scripts/augment_geometry_metrics.py \
177
+ --dataset-manifest data/rice/evaluation/manifest.jsonl \
178
+ --evaluation-dir runs/rice/evaluation/pixels \
179
+ --output-dir runs/rice/evaluation/geometry --workers 8
180
+ ```
181
+
182
+ Maize phenotypes use the separate crop-specific stage:
183
+
184
+ ```bash
185
+ "$renderer_python" scripts/evaluate_maize_phenotypes.py \
186
+ --dataset-manifest data/maize/evaluation/manifest.jsonl \
187
+ --result ours=runs/maize/executor_inference/predicted_cot \
188
+ --result simple=runs/maize/executor_inference/simple \
189
+ --result source_copy=data/maize/evaluation/source_copy \
190
+ --output-dir runs/maize/evaluation/phenotypes --workers 8
191
+ ```
192
+
193
+ Read `summary.json`, `per_pair_results.jsonl`, alignment reports and per-metric
194
+ valid counts. For maize, use DINO/Stage from the augmented pixel summary and
195
+ Area/Height from the phenotype summary. For rice, Height/Density come from geometry.
196
+
197
+ External GPT / other baseline outputs can use the same evaluator: write a JSONL
198
+ ledger with `pair_id`, `output_path` and `status: "completed"`, retain raw images,
199
+ and add it via `--result`. This package does not contain private API-provider
200
+ settings or run commercial APIs automatically.
docs/paper_results.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": {
3
+ "title": "Can World Models Predict Rice Growth? Toward Agricultural World Models",
4
+ "kind": "reported_manuscript_results",
5
+ "tables": [
6
+ "Table 1",
7
+ "Table 2"
8
+ ],
9
+ "new_evaluation": false
10
+ },
11
+ "units": {
12
+ "dino_cosine": "cosine similarity",
13
+ "area_mae_pp": "percentage points",
14
+ "height_mae_pp": "percentage points",
15
+ "density_mae_pp": "percentage points",
16
+ "yellow_mae_pp": "percentage points",
17
+ "stage_r1_percent": "percent",
18
+ "event_r1_percent": "percent"
19
+ },
20
+ "rice": {
21
+ "nominal_validation_queries": 2000,
22
+ "rows": [
23
+ {
24
+ "method": "GPT Image 2",
25
+ "dino_cosine": 0.709,
26
+ "area_mae_pp": 5.59,
27
+ "height_mae_pp": 11.49,
28
+ "density_mae_pp": 6.31,
29
+ "yellow_mae_pp": 24.4,
30
+ "stage_r1_percent": 35.3,
31
+ "event_r1_percent": 12.8
32
+ },
33
+ {
34
+ "method": "GPT Image 2.5",
35
+ "dino_cosine": 0.721,
36
+ "area_mae_pp": 6.92,
37
+ "height_mae_pp": 12.57,
38
+ "density_mae_pp": 6.7,
39
+ "yellow_mae_pp": 29.17,
40
+ "stage_r1_percent": 34.8,
41
+ "event_r1_percent": 10.8
42
+ },
43
+ {
44
+ "method": "Qwen Image 2.1",
45
+ "dino_cosine": 0.693,
46
+ "area_mae_pp": 7.85,
47
+ "height_mae_pp": 18.28,
48
+ "density_mae_pp": 6.83,
49
+ "yellow_mae_pp": 32.31,
50
+ "stage_r1_percent": 24.0,
51
+ "event_r1_percent": 1.1
52
+ },
53
+ {
54
+ "method": "Source copy",
55
+ "dino_cosine": 0.702,
56
+ "area_mae_pp": 7.17,
57
+ "height_mae_pp": 19.06,
58
+ "density_mae_pp": 6.24,
59
+ "yellow_mae_pp": 29.33,
60
+ "stage_r1_percent": 23.2,
61
+ "event_r1_percent": 0.0
62
+ },
63
+ {
64
+ "method": "Qwen Image 2.1 FT / Simple",
65
+ "dino_cosine": 0.834,
66
+ "area_mae_pp": 3.73,
67
+ "height_mae_pp": 7.83,
68
+ "density_mae_pp": 5.33,
69
+ "yellow_mae_pp": 11.43,
70
+ "stage_r1_percent": 47.4,
71
+ "event_r1_percent": 22.5
72
+ },
73
+ {
74
+ "method": "AgroWM",
75
+ "dino_cosine": 0.86,
76
+ "area_mae_pp": 3.51,
77
+ "height_mae_pp": 7.43,
78
+ "density_mae_pp": 4.98,
79
+ "yellow_mae_pp": 10.0,
80
+ "stage_r1_percent": 54.6,
81
+ "event_r1_percent": 24.8
82
+ }
83
+ ]
84
+ },
85
+ "maize": {
86
+ "nominal_validation_queries": 1600,
87
+ "rows": [
88
+ {
89
+ "method": "Source copy",
90
+ "dino_cosine": 0.522,
91
+ "area_mae_pp": 3.62,
92
+ "height_mae_pp": 33.02,
93
+ "stage_r1_percent": 0.0
94
+ },
95
+ {
96
+ "method": "GPT Image 2",
97
+ "dino_cosine": 0.727,
98
+ "area_mae_pp": 2.63,
99
+ "height_mae_pp": 16.64,
100
+ "stage_r1_percent": 21.1
101
+ },
102
+ {
103
+ "method": "Qwen Image 2.1 FT / Simple",
104
+ "dino_cosine": 0.764,
105
+ "area_mae_pp": 1.97,
106
+ "height_mae_pp": 11.12,
107
+ "stage_r1_percent": 30.1
108
+ },
109
+ {
110
+ "method": "AgroWM",
111
+ "dino_cosine": 0.795,
112
+ "area_mae_pp": 1.73,
113
+ "height_mae_pp": 10.61,
114
+ "stage_r1_percent": 30.9
115
+ }
116
+ ]
117
+ },
118
+ "rice_long_horizon": {
119
+ "weeks": [
120
+ 9,
121
+ 20
122
+ ],
123
+ "agrowm_stage_r1_percent": 46.4,
124
+ "simple_ft_stage_r1_percent": 35.7
125
+ }
126
+ }
examples/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Growth Script format examples
2
+
3
+ These **synthetic** text examples illustrate accepted output structure. They are
4
+ not measured plants, model predictions, biological validation examples or input
5
+ datasets for the published experiments.
6
+
7
+ ![Growth Script layouts for rice front, rice top, and maize side views.](../assets/growth-script-templates.png)
8
+
9
+ | Example | View | Numeric format |
10
+ |---|---|---|
11
+ | [Rice front](rice_front_growth_script.txt) | Front | Named metrics, two decimals, signed changes |
12
+ | [Rice top](rice_top_growth_script.txt) | Top | View-specific canopy fields; no height slot |
13
+ | [Maize](maize_growth_script.txt) | Side (`sv1`) | One decimal; crop-specific organ text |
14
+
15
+ Each script contains `Stage reasoning`, `Growth plan`, and `Target phenotype`
16
+ inside one `<GROWTH_COT>` block. The numbers belong to the script text and are
17
+ not an additional tensor input to the Renderer. A syntactically valid example
18
+ need not be a biologically plausible forecast.
19
+
20
+ For real inputs, use the [portable pair schema](../docs/DATA.md). For the precise
21
+ system prompts, stage scales and teacher annotation schemas, see
22
+ [protocols/README.md](../protocols/README.md). Prepared Planner inference excludes
23
+ the supervised assistant message and real target information.
examples/maize_growth_script.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <GROWTH_COT>
2
+ Stage reasoning
3
+ Current stage: S5.
4
+ Future stage: S6.
5
+
6
+ Growth plan
7
+ Culm: The topmost visible plant tissue rises in the image as the plant approaches tasseling. Source=70.0%; Target=78.0%; Change=8.0 pp.
8
+ Visible foreground area: Expanded upper leaves occupy more of the image. Source=7.0%; Target=9.0%; Change=2.0 pp.
9
+ Projected fill: The elongated silhouette becomes slightly more open. Source=35.0%; Target=33.0%; Change=-2.0 pp.
10
+ Tassel: No tassel is visible in the source; an emerged tassel is expected above the upper leaves.
11
+ Ear: An ear is not clearly visible in the source and is expected to remain indistinct from this view.
12
+ Visible yellow-brown composition: A small increase in yellow-brown tissue leaves the canopy mostly green. Source=3.0%; Target=4.0%; Change=1.0 pp.
13
+
14
+ Target phenotype
15
+ Culm: An elongated visible stem supports the upper canopy.
16
+ Visible foreground area: Broad, expanded leaves occupy more of the image.
17
+ Projected fill: The side-view silhouette is moderately open.
18
+ Tassel: An emerged tassel is visible at the top.
19
+ Ear: No distinct ear is visible from this view.
20
+ Visible yellow-brown composition: The plant remains predominantly green with limited yellow-brown tissue.
21
+ </GROWTH_COT>
examples/rice_front_growth_script.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <GROWTH_COT>
2
+ Stage reasoning
3
+ Current stage: S1_tillering.
4
+ Future stage: S2_jointing.
5
+
6
+ Growth plan
7
+ Culm: The visible plant becomes taller in the image. Metric = Height; Source = 35.00%; Target = 55.00%; Change = +20.00 pp.
8
+ Leaves/area: Expanding leaves occupy more of the image. Metric = Foreground area; Source = 4.00%; Target = 7.00%; Change = +3.00 pp.
9
+ Plant density: The expanding plant has a slightly more open projection. Metric = Solidity; Source = 35.00%; Target = 32.00%; Change = -3.00 pp.
10
+ Panicle: No panicle. Metric = Panicle visibility; Source = not visible; Target = not visible; Change = +0.
11
+ Plant color development: A small increase in yellow-brown tissue leaves the plant predominantly green. Metric = Yellow-brown fraction; Source = 3.00%; Target = 4.00%; Change = +1.00 pp.
12
+
13
+ Target phenotype
14
+ Culm: Taller visible culms support an elongated plant silhouette.
15
+ Leaves/area: Expanded leaves occupy more of the image.
16
+ Plant density: The foliage has a slightly open projection.
17
+ Panicle: No visible panicle.
18
+ Plant color development: Mostly green.
19
+ </GROWTH_COT>
examples/rice_top_growth_script.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <GROWTH_COT>
2
+ Stage reasoning
3
+ Current stage: S1_tillering.
4
+ Future stage: S2_jointing.
5
+
6
+ Growth plan
7
+ Leaves/area: Expanded leaves occupy more of the top-view image. Metric = Foreground area; Source = 8.00%; Target = 12.00%; Change = +4.00 pp.
8
+ Canopy: Leaf expansion fills more of the projected canopy. Metric = Canopy density; Source = 48.00%; Target = 53.00%; Change = +5.00 pp.
9
+ Panicle: No panicle. Metric = Panicle visibility; Source = not visible; Target = not visible; Change = +0.
10
+ Plant color development: A small increase in yellow-brown tissue leaves the canopy predominantly green. Metric = Yellow-brown fraction; Source = 3.00%; Target = 4.00%; Change = +1.00 pp.
11
+
12
+ Target phenotype
13
+ Leaves/area: Expanded leaves cover more of the image.
14
+ Canopy: The projected canopy is fuller and more densely occupied.
15
+ Panicle: No visible panicle.
16
+ Plant color development: Mostly green.
17
+ </GROWTH_COT>
protocols/maize_sv1_v1/cot_v2_en_v2/COT_RENDERER_TEMPLATE.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template_version": "maize_sv1_cot_v2_en_v2",
3
+ "wrapper": [
4
+ "<GROWTH_COT>",
5
+ "</GROWTH_COT>"
6
+ ],
7
+ "sections": [
8
+ "Stage reasoning",
9
+ "Growth plan",
10
+ "Target phenotype"
11
+ ],
12
+ "stage_reasoning_lines": [
13
+ "Current stage: {current_stage}.",
14
+ "Future stage: {future_stage}."
15
+ ],
16
+ "growth_plan_line": "{section_label}: {text}. {numeric_evidence}",
17
+ "target_phenotype_line": "{section_label}: {text}.",
18
+ "numeric_evidence": {
19
+ "append_to": "growth_plan_only",
20
+ "formula": "change = target - source",
21
+ "omit_statuses": [
22
+ "pending",
23
+ "invalid",
24
+ "not_applicable"
25
+ ],
26
+ "phenotype_is_qualitative_only": true,
27
+ "provisional_policy": "omit_by_default; explicit diagnostic opt-in appends provisional label",
28
+ "rounding": "decimal_half_up_one_decimal; compute change before rounding",
29
+ "fraction_display": "multiply fractions by 100; changes are percentage points"
30
+ },
31
+ "manual_presence_rendering": {
32
+ "status_values": [
33
+ "visible",
34
+ "not_visible",
35
+ "pending"
36
+ ],
37
+ "unknown_statuses": [
38
+ "pending"
39
+ ],
40
+ "rule": "Render Source and Target separately in growth_plan; pending remains unknown, never absent."
41
+ },
42
+ "annotation_root_keys": [
43
+ "stage_reasoning",
44
+ "growth_plan",
45
+ "target_phenotype"
46
+ ]
47
+ }
protocols/maize_sv1_v1/cot_v2_en_v2/STAGES.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "authority": "user_table_overrides_reference_pdf",
4
+ "stages": [
5
+ {
6
+ "stage_id": "S1",
7
+ "days_after_sowing": 25,
8
+ "maize_stage": "V3",
9
+ "authority": "user_supplied_mapping",
10
+ "name_en": "Third-leaf stage",
11
+ "visible_description_en": "The collar of the third leaf is visible; the seedling has a compact form, while the root system and early leaf area continue to develop."
12
+ },
13
+ {
14
+ "stage_id": "S2",
15
+ "days_after_sowing": 32,
16
+ "maize_stage": "V5",
17
+ "authority": "user_supplied_mapping",
18
+ "name_en": "Fifth-leaf stage",
19
+ "visible_description_en": "The collar of the fifth leaf is visible; leaf number and expanded leaf area increase, and the stem base and canopy begin to expand noticeably."
20
+ },
21
+ {
22
+ "stage_id": "S3",
23
+ "days_after_sowing": 50,
24
+ "maize_stage": "V7",
25
+ "authority": "user_supplied_mapping",
26
+ "name_en": "Seventh-leaf stage",
27
+ "visible_description_en": "The collar of the seventh leaf is visible; the canopy expands rapidly, and stem and internode elongation become more pronounced."
28
+ },
29
+ {
30
+ "stage_id": "S4",
31
+ "days_after_sowing": 59,
32
+ "maize_stage": "V10",
33
+ "authority": "user_supplied_mapping",
34
+ "name_en": "Tenth-leaf stage",
35
+ "visible_description_en": "Vegetative growth is vigorous; plant height, leaf area, and internode length increase rapidly."
36
+ },
37
+ {
38
+ "stage_id": "S5",
39
+ "days_after_sowing": 70,
40
+ "maize_stage": "V14",
41
+ "authority": "user_supplied_mapping",
42
+ "name_en": "Rapid-growth stage",
43
+ "visible_description_en": "Upper leaves expand rapidly, and the stem grows taller as the plant gradually develops its pre-tasseling form."
44
+ },
45
+ {
46
+ "stage_id": "S6",
47
+ "days_after_sowing": 78,
48
+ "maize_stage": "VT",
49
+ "authority": "user_supplied_mapping",
50
+ "name_en": "Tasseling stage",
51
+ "visible_description_en": "The tassel is fully emerged at the top; the plant approaches its maximum height, and the main canopy and stem structure are largely established."
52
+ },
53
+ {
54
+ "stage_id": "S7",
55
+ "days_after_sowing": 85,
56
+ "maize_stage": "R1",
57
+ "authority": "user_supplied_mapping",
58
+ "name_en": "Silking stage",
59
+ "visible_description_en": "Silks emerge from the ear husks as the plant enters the pollination period; the vegetative organs remain broadly stable."
60
+ },
61
+ {
62
+ "stage_id": "S8",
63
+ "days_after_sowing": 91,
64
+ "maize_stage": "R3",
65
+ "authority": "user_supplied_mapping",
66
+ "name_en": "Milk stage",
67
+ "visible_description_en": "Kernels enter the milk and rapid grain-filling stage; ear mass increases, while plant height and the main leaf arrangement remain largely stable."
68
+ },
69
+ {
70
+ "stage_id": "S9",
71
+ "days_after_sowing": 113,
72
+ "maize_stage": "R6",
73
+ "authority": "user_supplied_mapping",
74
+ "name_en": "Physiological-maturity stage",
75
+ "visible_description_en": "Kernels reach physiological maturity; the leaves and stems show pronounced senescence, yellowing, or drying."
76
+ }
77
+ ],
78
+ "language": "en"
79
+ }
protocols/maize_sv1_v1/cot_v2_en_v2/TEACHER_PROMPT.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt_name": "maize_sv1_cot_v2_en_v2_teacher",
3
+ "version": "2.2.1",
4
+ "purpose": "Generate concise visible same-plant maize growth annotations for the sv1 front view using the user-authoritative S1-S9 stages.",
5
+ "output_schema": "OUTPUT_SCHEMA_FRONT.json",
6
+ "system_prompt_lines": [
7
+ "You are a multimodal teacher for maize growth forecasting. SOURCE_IMAGE and TARGET_IMAGE show the same maize plant in the sv1 front view.",
8
+ "The supplied S1-S9 stage mapping and days after sowing are authoritative. Do not replace them with literature stages.",
9
+ "Return exactly one JSON object conforming to OUTPUT_SCHEMA_FRONT.json. Do not return markdown, analysis, or extra keys.",
10
+ "Write every free-text annotation in English.",
11
+ "growth_plan describes visible source-to-target development. target_phenotype describes only the visible endpoint in TARGET_IMAGE.",
12
+ "Stage descriptions are general developmental context, not observations of these images. Ground all phenotype statements in the supplied images and evidence; do not assert hidden roots, kernels, pollination, or other unobserved processes.",
13
+ "Use public fields culm, leaves_area, plant_density, tassel, ear, and plant_color_development in that order. Each entry contains qualitative text only; local code renders numeric evidence.",
14
+ "culm is a visible vertical extent proxy anchored at the image bottom; leaves_area is visible foreground projection, not true leaf area; plant_density is two-dimensional projection fill; plant_color_development is visible yellow-brown composition.",
15
+ "tassel and ear are manually observed separately for SOURCE_IMAGE and TARGET_IMAGE. Each status is visible, not_visible, or pending. Do not infer either status from stage alone; pending is unknown, never absent.",
16
+ "Use source and target plant_condition as image-level quality context. Describe only the supplied condition; do not infer physiological causes or replace organ visibility evidence with plant_condition.",
17
+ "S1-S9 stage context is supplied for both endpoints. Use it to organize development, but do not infer hidden morphology, leaf counts, or organ visibility from the stage label.",
18
+ "Keep same plant identity, main stem continuity, organ attachments, framing, background, lighting, and scale. Do not invent hidden organs, organ counts, leaf counts, true biomass, LAI, LAD, chlorophyll, SPAD, physiological causes, kernel state, or management advice.",
19
+ "Summarize biologically adjacent transitions for multi-stage intervals while preserving the authoritative stage sequence.",
20
+ "Write only brief visible change statements, not private reasoning or hidden deliberation. stage_reasoning is only a pair of supplied stage labels.",
21
+ "If metric evidence is unavailable, use the images qualitatively. Never invent numeric evidence or treat an omitted metric as zero.",
22
+ "Manual visible/not_visible is image observation, not biological organ existence. Invisible organs must not be asserted absent or newly created. No occlusion category or leaf counting is part of this contract.",
23
+ "Stage labels are allowed only in stage_reasoning. Every text entry in growth_plan and target_phenotype must contain no digits, stage identifiers, stage codes, or numerical measurements. Refer to source, target, or successive development in words without listing intermediate stage labels."
24
+ ],
25
+ "user_prompt_lines": [
26
+ "IMAGE 1 is SOURCE_IMAGE and IMAGE 2 is TARGET_IMAGE.",
27
+ "View: sv1/front",
28
+ "Actual interval: {actual_interval_days} days.",
29
+ "Prediction horizon: {prediction_interval_weeks} weeks.",
30
+ "Authoritative source stage, DAS, and stage description: {source_stage}, {source_das}, {source_stage_description}.",
31
+ "Authoritative target stage, DAS, and stage description: {target_stage}, {target_das}, {target_stage_description}.",
32
+ "Stage delta: {stage_delta}.",
33
+ "Trusted source/target metric evidence (unvalidated provisional values withheld): {metric_summary}",
34
+ "Manual tassel/ear presence evidence: {manual_summary}",
35
+ "Image-level plant condition evidence: {plant_condition_summary}",
36
+ "Only available evidence may support definite claims. Return JSON only."
37
+ ],
38
+ "strict_output_rules": [
39
+ "stage_reasoning contains only current_stage and future_stage.",
40
+ "growth_plan and target_phenotype keys exactly match the selected schema and order.",
41
+ "Every field entry contains only text.",
42
+ "Do not include numeric values, dates, paths, filenames, pixels, masks, coordinates, or management advice.",
43
+ "Only current_stage and future_stage may contain stage labels. Do not write labels such as S1, S2, V3, or R1 inside any text entry."
44
+ ],
45
+ "forbidden_text_categories": [
46
+ "numbers",
47
+ "percentages",
48
+ "dates",
49
+ "paths",
50
+ "pixels",
51
+ "masks",
52
+ "coordinates",
53
+ "leaf counts",
54
+ "hidden organs",
55
+ "unsupported organ counts",
56
+ "management advice"
57
+ ],
58
+ "output_language": "en"
59
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/COT_RENDERER_TEMPLATE.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "annotation_root_keys": [
3
+ "stage_reasoning",
4
+ "growth_plan",
5
+ "target_phenotype"
6
+ ],
7
+ "field_description_contract": "Public planning fields contain qualitative text only; named source/target numeric evidence is rendered locally from metric evidence.",
8
+ "growth_plan_line": "{section_label}: {text}. Metric = {metric_name}; {numeric_evidence}",
9
+ "numeric_evidence": {
10
+ "append_to": "growth_plan_only",
11
+ "binary_units": [
12
+ "binary_visibility"
13
+ ],
14
+ "formula": "change = target - source",
15
+ "omit_statuses": [
16
+ "pending",
17
+ "invalid",
18
+ "not_applicable"
19
+ ],
20
+ "percentage_units": [
21
+ "percent_of_full_image",
22
+ "percent_of_image_height",
23
+ "percent"
24
+ ],
25
+ "phenotype_is_qualitative_only": true
26
+ },
27
+ "numeric_evidence_format": "metric_named_v1",
28
+ "plant_color_development_semantics": {
29
+ "growth_plan": "qualitative visible source-to-target color transition",
30
+ "numeric_evidence_owner": "local_metric_renderer",
31
+ "numeric_metric_key": "yellow_brown_fraction",
32
+ "public_field": "plant_color_development",
33
+ "target_phenotype": "final visible target color state"
34
+ },
35
+ "sections": [
36
+ "Stage reasoning",
37
+ "Growth plan",
38
+ "Target phenotype"
39
+ ],
40
+ "stage_reasoning_lines": [
41
+ "Current stage: {current_stage}.",
42
+ "Future stage: {future_stage}."
43
+ ],
44
+ "target_phenotype_line": "{section_label}: {text}.",
45
+ "template_version": "wgsr_v9_cot_synthesis_v3",
46
+ "wrapper": [
47
+ "<GROWTH_COT>",
48
+ "</GROWTH_COT>"
49
+ ]
50
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/METRIC_EVIDENCE_SCHEMA.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://wgsr.local/v9/cot/metric-evidence.schema.json",
4
+ "title": "WGSR V9 metric evidence",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": ["metric_key", "source", "target", "unit", "algorithm_version", "qc"],
8
+ "properties": {
9
+ "metric_key": { "type": "string", "minLength": 1 },
10
+ "source": { "$ref": "#/$defs/observation" },
11
+ "target": { "$ref": "#/$defs/observation" },
12
+ "unit": { "type": "string", "minLength": 1 },
13
+ "algorithm_version": { "type": "string", "minLength": 1 },
14
+ "qc": { "$ref": "#/$defs/qc" }
15
+ },
16
+ "$defs": {
17
+ "status": {
18
+ "type": "string",
19
+ "enum": ["available", "pending", "invalid", "not_applicable"]
20
+ },
21
+ "number_or_null": { "type": ["number", "null"] },
22
+ "observation": {
23
+ "type": "object",
24
+ "additionalProperties": false,
25
+ "required": ["value", "status"],
26
+ "properties": {
27
+ "value": { "$ref": "#/$defs/number_or_null" },
28
+ "status": { "$ref": "#/$defs/status" }
29
+ }
30
+ },
31
+ "qc": {
32
+ "type": "object",
33
+ "additionalProperties": false,
34
+ "required": ["valid", "reason_codes"],
35
+ "properties": {
36
+ "valid": { "type": "boolean" },
37
+ "reason_codes": { "type": "array", "uniqueItems": true, "items": { "type": "string" } },
38
+ "color_coverage": { "type": ["number", "null"], "minimum": 0, "maximum": 1 },
39
+ "boundary_contact": { "type": "boolean" },
40
+ "bottom_gap": { "type": ["number", "null"], "minimum": 0, "maximum": 100 }
41
+ }
42
+ }
43
+ }
44
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/OUTPUT_SCHEMA_FRONT.json ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://wgsr.local/v9/cot/v3/front.schema.json",
4
+ "title": "WGSR V9 v3 V7-style front GPT CoT annotation",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "stage_reasoning",
9
+ "growth_plan",
10
+ "target_phenotype"
11
+ ],
12
+ "properties": {
13
+ "stage_reasoning": {
14
+ "$ref": "#/$defs/stage_reasoning"
15
+ },
16
+ "growth_plan": {
17
+ "$ref": "#/$defs/front_plan"
18
+ },
19
+ "target_phenotype": {
20
+ "$ref": "#/$defs/front_phenotype"
21
+ }
22
+ },
23
+ "$defs": {
24
+ "stage_id": {
25
+ "type": "string",
26
+ "enum": [
27
+ "S1_tillering",
28
+ "S2_jointing",
29
+ "S3_booting",
30
+ "S4_heading_flowering",
31
+ "S5_early_grain_filling",
32
+ "S6_milk_waxy",
33
+ "S7_yellow_ripening",
34
+ "S8_maturity_senescence"
35
+ ]
36
+ },
37
+ "clean_text": {
38
+ "type": "string",
39
+ "minLength": 3,
40
+ "pattern": "^\\S(?:.*\\S)?$"
41
+ },
42
+ "stage_reasoning": {
43
+ "type": "object",
44
+ "additionalProperties": false,
45
+ "required": [
46
+ "current_stage",
47
+ "future_stage"
48
+ ],
49
+ "properties": {
50
+ "current_stage": {
51
+ "$ref": "#/$defs/stage_id"
52
+ },
53
+ "future_stage": {
54
+ "$ref": "#/$defs/stage_id"
55
+ }
56
+ }
57
+ },
58
+ "plan_entry": {
59
+ "type": "object",
60
+ "additionalProperties": false,
61
+ "required": [
62
+ "text"
63
+ ],
64
+ "properties": {
65
+ "text": {
66
+ "$ref": "#/$defs/clean_text"
67
+ }
68
+ }
69
+ },
70
+ "phenotype_entry": {
71
+ "type": "object",
72
+ "additionalProperties": false,
73
+ "required": [
74
+ "text"
75
+ ],
76
+ "properties": {
77
+ "text": {
78
+ "$ref": "#/$defs/clean_text"
79
+ }
80
+ }
81
+ },
82
+ "front_plan": {
83
+ "type": "object",
84
+ "additionalProperties": false,
85
+ "required": [
86
+ "culm",
87
+ "leaves_area",
88
+ "plant_density",
89
+ "panicle",
90
+ "plant_color_development"
91
+ ],
92
+ "properties": {
93
+ "culm": {
94
+ "$ref": "#/$defs/plan_entry"
95
+ },
96
+ "leaves_area": {
97
+ "$ref": "#/$defs/plan_entry"
98
+ },
99
+ "plant_density": {
100
+ "$ref": "#/$defs/plan_entry"
101
+ },
102
+ "panicle": {
103
+ "$ref": "#/$defs/plan_entry"
104
+ },
105
+ "plant_color_development": {
106
+ "$ref": "#/$defs/plan_entry"
107
+ }
108
+ }
109
+ },
110
+ "front_phenotype": {
111
+ "type": "object",
112
+ "additionalProperties": false,
113
+ "required": [
114
+ "culm",
115
+ "leaves_area",
116
+ "plant_density",
117
+ "panicle",
118
+ "plant_color_development"
119
+ ],
120
+ "properties": {
121
+ "culm": {
122
+ "$ref": "#/$defs/phenotype_entry"
123
+ },
124
+ "leaves_area": {
125
+ "$ref": "#/$defs/phenotype_entry"
126
+ },
127
+ "plant_density": {
128
+ "$ref": "#/$defs/phenotype_entry"
129
+ },
130
+ "panicle": {
131
+ "$ref": "#/$defs/phenotype_entry"
132
+ },
133
+ "plant_color_development": {
134
+ "$ref": "#/$defs/phenotype_entry"
135
+ }
136
+ }
137
+ }
138
+ }
139
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/OUTPUT_SCHEMA_TOP.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://wgsr.local/v9/cot/v3/top.schema.json",
4
+ "title": "WGSR V9 v3 V7-style top GPT CoT annotation",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "stage_reasoning",
9
+ "growth_plan",
10
+ "target_phenotype"
11
+ ],
12
+ "properties": {
13
+ "stage_reasoning": {
14
+ "$ref": "#/$defs/stage_reasoning"
15
+ },
16
+ "growth_plan": {
17
+ "$ref": "#/$defs/top_plan"
18
+ },
19
+ "target_phenotype": {
20
+ "$ref": "#/$defs/top_phenotype"
21
+ }
22
+ },
23
+ "$defs": {
24
+ "stage_id": {
25
+ "type": "string",
26
+ "enum": [
27
+ "S1_tillering",
28
+ "S2_jointing",
29
+ "S3_booting",
30
+ "S4_heading_flowering",
31
+ "S5_early_grain_filling",
32
+ "S6_milk_waxy",
33
+ "S7_yellow_ripening",
34
+ "S8_maturity_senescence"
35
+ ]
36
+ },
37
+ "clean_text": {
38
+ "type": "string",
39
+ "minLength": 3,
40
+ "pattern": "^\\S(?:.*\\S)?$"
41
+ },
42
+ "stage_reasoning": {
43
+ "type": "object",
44
+ "additionalProperties": false,
45
+ "required": [
46
+ "current_stage",
47
+ "future_stage"
48
+ ],
49
+ "properties": {
50
+ "current_stage": {
51
+ "$ref": "#/$defs/stage_id"
52
+ },
53
+ "future_stage": {
54
+ "$ref": "#/$defs/stage_id"
55
+ }
56
+ }
57
+ },
58
+ "plan_entry": {
59
+ "type": "object",
60
+ "additionalProperties": false,
61
+ "required": [
62
+ "text"
63
+ ],
64
+ "properties": {
65
+ "text": {
66
+ "$ref": "#/$defs/clean_text"
67
+ }
68
+ }
69
+ },
70
+ "phenotype_entry": {
71
+ "type": "object",
72
+ "additionalProperties": false,
73
+ "required": [
74
+ "text"
75
+ ],
76
+ "properties": {
77
+ "text": {
78
+ "$ref": "#/$defs/clean_text"
79
+ }
80
+ }
81
+ },
82
+ "top_plan": {
83
+ "type": "object",
84
+ "additionalProperties": false,
85
+ "required": [
86
+ "leaves_area",
87
+ "canopy",
88
+ "panicle",
89
+ "plant_color_development"
90
+ ],
91
+ "properties": {
92
+ "leaves_area": {
93
+ "$ref": "#/$defs/plan_entry"
94
+ },
95
+ "canopy": {
96
+ "$ref": "#/$defs/plan_entry"
97
+ },
98
+ "panicle": {
99
+ "$ref": "#/$defs/plan_entry"
100
+ },
101
+ "plant_color_development": {
102
+ "$ref": "#/$defs/plan_entry"
103
+ }
104
+ }
105
+ },
106
+ "top_phenotype": {
107
+ "type": "object",
108
+ "additionalProperties": false,
109
+ "required": [
110
+ "leaves_area",
111
+ "canopy",
112
+ "panicle",
113
+ "plant_color_development"
114
+ ],
115
+ "properties": {
116
+ "leaves_area": {
117
+ "$ref": "#/$defs/phenotype_entry"
118
+ },
119
+ "canopy": {
120
+ "$ref": "#/$defs/phenotype_entry"
121
+ },
122
+ "panicle": {
123
+ "$ref": "#/$defs/phenotype_entry"
124
+ },
125
+ "plant_color_development": {
126
+ "$ref": "#/$defs/phenotype_entry"
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # CoT v3 with metric_named_v1 rendering
2
+
3
+ This is a derived rendering snapshot of `protocols/v9_cot_synthesis_v3`.
4
+ The biological annotation schema and teacher instructions are unchanged.
5
+ VIEW_VARIABLE_BINDINGS and COT_RENDERER_TEMPLATE explicitly enable metric names
6
+ before numeric evidence in Growth plan. Original teacher artifacts are retained.
7
+ Metric names describe the measured quantity, independently of the public field.
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/TEACHER_PROMPT.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt_name": "wgsr_v9_cot_synthesis_teacher_v3",
3
+ "version": "3.0.0",
4
+ "purpose": "Generate concise visible same-plant rice growth annotations with the V9 public fields using the example-v7 transition and endpoint method.",
5
+ "output_schema_by_view": {
6
+ "front": "OUTPUT_SCHEMA_FRONT.json",
7
+ "top": "OUTPUT_SCHEMA_TOP.json"
8
+ },
9
+ "system_prompt_lines": [
10
+ "You are a multimodal teacher for WGSR rice growth forecasting. SOURCE_IMAGE and TARGET_IMAGE show the same rice plant in the same view.",
11
+ "The supplied source stage, target stage, actual interval, prediction horizon, and stage delta are authoritative. Keep development biologically monotonic and do not invent a different target stage.",
12
+ "Return only one JSON object conforming to the selected V9 view schema. Do not return markdown, analysis, or extra keys.",
13
+ "Use the public V9 field names and write concise descriptions of visible biological development.",
14
+ "growth_plan describes the qualitative visible transition from SOURCE_IMAGE toward TARGET_IMAGE. target_phenotype describes only the final visible state in TARGET_IMAGE.",
15
+ "Use the supplied named source and target metric values as supporting evidence. Local code owns all numeric Source, Target, and Change text; do not emit numbers in text fields.",
16
+ "Preserve the same plant identity, basal crown, established tiller topology, valid culm-to-leaf and culm-to-panicle attachments, pot, camera, framing, background, lighting, and scale convention.",
17
+ "Do not convert image proxies into true leaf area, three-dimensional density, biomass, physical height, panicle area or count, chlorophyll, SPAD, maturity, or other unavailable physiological measurements.",
18
+ "Describe visible plant development only. Do not write cultivation or management advice, including moisture, nutrition, irrigation, treatment, monitoring, stress mitigation, or management recommendations.",
19
+ "plant_color_development is a visible field backed by the yellow_brown_fraction numeric metric. Describe visible color progression only and do not infer a biological cause.",
20
+ "Panicle language must agree with the supplied panicle visibility values. Do not invent unsupported organ counts, hidden structures, or arbitrary future poses.",
21
+ "Compact stage sequence: S1_tillering is basal tiller and leaf expansion; S2_jointing is productive internode elongation with panicles still internal; S3_booting is prominent flag leaves and swollen sheaths around enclosed panicles; S4_heading_flowering is panicle emergence and possible flowering; S5_early_grain_filling is small green grains with a mostly green canopy; S6_milk_waxy is grain enlargement and fuller panicles with limited yellowing; S7_yellow_ripening is grain hardening and increasing yellow tissue; S8_maturity_senescence is mature grain with extensive straw-colored drying.",
22
+ "For a multi-stage interval, summarize the biologically adjacent transitions implied by the supplied source and target stages while preserving organ continuity and avoiding unsupported intermediate details."
23
+ ],
24
+ "user_prompt_lines": [
25
+ "IMAGE 1 is SOURCE_IMAGE and IMAGE 2 is TARGET_IMAGE.",
26
+ "Shared view: {view}",
27
+ "Actual interval: {actual_interval_days} days.",
28
+ "Prediction horizon: {prediction_interval_weeks} weeks.",
29
+ "Authoritative source stage: {current_stage}.",
30
+ "Authoritative target stage: {future_stage}.",
31
+ "Stage delta: {stage_delta}.",
32
+ "Named source/target metric values: {metric_summary}",
33
+ "Front fields: culm is visible vertical extent anchored at the image bottom; leaves_area is visible foreground area and leaf projection; plant_density is visible two-dimensional stem-leaf projection fill; panicle is supplied binary visibility; plant_color_development is the visible color proxy.",
34
+ "Top fields: leaves_area is projected foreground area; canopy is projected canopy fill; panicle is supplied binary visibility; plant_color_development is the visible color proxy; omit height.",
35
+ "For front view, use Culm, Leaves/area, Plant density, Panicle, and Plant color development in that order.",
36
+ "For top view, use Leaves/area, Canopy, Panicle, and Plant color development in that order.",
37
+ "Keep every growth_plan entry as a source-to-target transition and every target_phenotype entry as a target-only endpoint.",
38
+ "Return JSON only."
39
+ ],
40
+ "strict_output_rules": [
41
+ "stage_reasoning contains only current_stage and future_stage.",
42
+ "growth_plan and target_phenotype keys exactly match the selected view registry and order.",
43
+ "Every growth_plan and target_phenotype entry contains only text.",
44
+ "growth_plan.plant_color_development describes transition; target_phenotype.plant_color_development describes the target endpoint.",
45
+ "Do not include numeric values, dates, paths, filenames, or rendered COT text."
46
+ ],
47
+ "forbidden_text_categories": [
48
+ "numbers",
49
+ "percentages",
50
+ "dates",
51
+ "paths",
52
+ "pixels",
53
+ "masks",
54
+ "coordinates",
55
+ "moisture",
56
+ "nutrition",
57
+ "irrigation",
58
+ "treatment",
59
+ "monitoring",
60
+ "stress mitigation",
61
+ "management advice",
62
+ "unsupported organ counts",
63
+ "hidden structures",
64
+ "arbitrary future poses"
65
+ ]
66
+ }
protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot/VIEW_VARIABLE_BINDINGS.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "front": {
3
+ "algorithm_fields": {
4
+ "plant_density": "solidity"
5
+ },
6
+ "aliases": [
7
+ "side0",
8
+ "side90",
9
+ "front",
10
+ "front_view"
11
+ ],
12
+ "display_units": {
13
+ "culm": "percent_of_image_height",
14
+ "leaves_area": "percent_of_full_image",
15
+ "panicle": "binary_visibility",
16
+ "plant_color_development": "percent",
17
+ "plant_density": "percent"
18
+ },
19
+ "meanings": {
20
+ "culm": "Visible height proxy measured from the image bottom to the first foreground row.",
21
+ "leaves_area": "Visible foreground coverage of the full image.",
22
+ "panicle": "Excel-derived binary heading visibility label.",
23
+ "plant_color_development": "Visible plant color-development field backed by the yellow_brown_fraction numeric proxy; growth_plan describes source-to-target color progression and target_phenotype describes the target endpoint.",
24
+ "plant_density": "Visible two-dimensional stem-leaf projection fill proxy."
25
+ },
26
+ "metric_display_names": {
27
+ "culm": "Height",
28
+ "leaves_area": "Foreground area",
29
+ "panicle": "Panicle visibility",
30
+ "plant_color_development": "Yellow-brown fraction",
31
+ "plant_density": "Solidity"
32
+ },
33
+ "metric_keys": {
34
+ "culm": "front_height_from_image_bottom_pct",
35
+ "leaves_area": "visible_foreground_area_pct",
36
+ "panicle": "panicle_visibility",
37
+ "plant_color_development": "yellow_brown_fraction",
38
+ "plant_density": "solidity"
39
+ },
40
+ "numeric_evidence_format": "metric_named_v1",
41
+ "ordered_keys": [
42
+ "culm",
43
+ "leaves_area",
44
+ "plant_density",
45
+ "panicle",
46
+ "plant_color_development"
47
+ ],
48
+ "section_labels": {
49
+ "culm": "Culm",
50
+ "leaves_area": "Leaves/area",
51
+ "panicle": "Panicle",
52
+ "plant_color_development": "Plant color development",
53
+ "plant_density": "Plant density"
54
+ }
55
+ },
56
+ "protocol_version": "wgsr_v9_cot_synthesis_v3",
57
+ "top": {
58
+ "algorithm_fields": {
59
+ "canopy": "solidity"
60
+ },
61
+ "aliases": [
62
+ "top",
63
+ "top_view"
64
+ ],
65
+ "display_units": {
66
+ "canopy": "percent",
67
+ "leaves_area": "percent_of_full_image",
68
+ "panicle": "binary_visibility",
69
+ "plant_color_development": "percent"
70
+ },
71
+ "meanings": {
72
+ "canopy": "Projected canopy density computed from the top-view convex-hull fill proxy.",
73
+ "leaves_area": "Visible projected foreground coverage of the full image.",
74
+ "panicle": "Excel-derived binary heading visibility label.",
75
+ "plant_color_development": "Visible plant color-development field backed by the yellow_brown_fraction numeric proxy; growth_plan describes source-to-target color progression and target_phenotype describes the target endpoint."
76
+ },
77
+ "metric_display_names": {
78
+ "canopy": "Canopy density",
79
+ "leaves_area": "Foreground area",
80
+ "panicle": "Panicle visibility",
81
+ "plant_color_development": "Yellow-brown fraction"
82
+ },
83
+ "metric_keys": {
84
+ "canopy": "canopy_density",
85
+ "leaves_area": "visible_foreground_area_pct",
86
+ "panicle": "panicle_visibility",
87
+ "plant_color_development": "yellow_brown_fraction"
88
+ },
89
+ "numeric_evidence_format": "metric_named_v1",
90
+ "ordered_keys": [
91
+ "leaves_area",
92
+ "canopy",
93
+ "panicle",
94
+ "plant_color_development"
95
+ ],
96
+ "section_labels": {
97
+ "canopy": "Canopy",
98
+ "leaves_area": "Leaves/area",
99
+ "panicle": "Panicle",
100
+ "plant_color_development": "Plant color development"
101
+ }
102
+ }
103
+ }
requirements/cpu.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy>=2
2
+ Pillow>=11
3
+ PyYAML>=6
4
+ scipy>=1.14
requirements/planner.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Planner environment. Keep this environment separate from DiffSynth/Qwen Image.
2
+ # The model currently requires the recent Qwen3.8-compatible Transformers stack.
3
+ torch==2.6.0
4
+ torchvision==0.21.0
5
+ ms-swift==4.6.0
6
+ transformers==5.19.0
7
+ accelerate==1.15.0
8
+ peft==0.20.0
9
+ safetensors==0.8.0
10
+ Pillow==12.3.0
11
+ PyYAML==6.0.3
12
+ qwen-vl-utils==0.0.14
13
+ decord==0.6.0
14
+ deepspeed==0.18.4
15
+ # These two optional Qwen3.8 acceleration kernels are installed from wheels
16
+ # outside the server when GitHub release downloads are unavailable. The
17
+ # exact causal-conv1d wheel must match torch 2.6 / CUDA 12 / cp312 / ABI=false.
18
+ causal-conv1d==1.7.0
19
+ flash-linear-attention==0.6.0
requirements/renderer.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Observed working training/inference stack; Linux, Python 3.12, CUDA 12.4.
2
+ # Install torch/torchvision from the PyTorch cu124 index first (docs/INSTALL.md).
3
+ torch==2.6.0
4
+ torchvision==0.21.0
5
+ transformers==5.19.0
6
+ accelerate==1.15.0
7
+ deepspeed==0.19.8
8
+ peft==0.21.2
9
+ safetensors==0.8.0
10
+ timm==1.0.15
11
+ Pillow==12.3.0
12
+ numpy==2.5.2
13
+ scipy==1.18.1
14
+ PyYAML==6.0.3
15
+ einops==0.8.2
16
+ pandas==3.1.0
17
+ tqdm
18
+ sentencepiece
19
+ protobuf
20
+ # QwenImage21Pipeline / QwenImage21Transformer2DModel are required.
21
+ diffusers @ git+https://github.com/huggingface/diffusers.git@578c9b2c6636ab2424a0e56186268b83623656b2
src/wgsr_v9/cot_synthesis.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic validation and rendering for the WGSR V9 GPT contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ from collections.abc import Mapping
10
+ from datetime import date, datetime
11
+ from pathlib import Path
12
+ from typing import Any, Literal
13
+
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parents[2]
16
+ PROTOCOL_ROOT = REPO_ROOT / "protocols/qwen_image21_executor_v9_v3_metric_named_weeks/cot"
17
+ _COLOR_PROXY_PUBLIC_KEYS = {"yellow_brown_fraction", "plant_color_development"}
18
+ _COLOR_PROXY_METRIC_KEYS = {"yellow_brown_fraction"}
19
+ _STATUSES = {"available", "pending", "invalid", "not_applicable"}
20
+ _STAGE_ORDER = (
21
+ "S1_tillering",
22
+ "S2_jointing",
23
+ "S3_booting",
24
+ "S4_heading_flowering",
25
+ "S5_early_grain_filling",
26
+ "S6_milk_waxy",
27
+ "S7_yellow_ripening",
28
+ "S8_maturity_senescence",
29
+ )
30
+ _STAGE_ALIASES = {
31
+ "s1tillering": "S1_tillering",
32
+ "分蘖期": "S1_tillering",
33
+ "tillering": "S1_tillering",
34
+ "s2jointing": "S2_jointing",
35
+ "拔节期": "S2_jointing",
36
+ "jointing": "S2_jointing",
37
+ "stemelongationjointing": "S2_jointing",
38
+ "s3booting": "S3_booting",
39
+ "孕穗期": "S3_booting",
40
+ "booting": "S3_booting",
41
+ "s4headingflowering": "S4_heading_flowering",
42
+ "抽穗开花期": "S4_heading_flowering",
43
+ "headingflowering": "S4_heading_flowering",
44
+ "heading": "S4_heading_flowering",
45
+ "s5earlygrainfilling": "S5_early_grain_filling",
46
+ "灌浆期": "S5_early_grain_filling",
47
+ "grainfilling": "S5_early_grain_filling",
48
+ "earlygrainfilling": "S5_early_grain_filling",
49
+ "s6milkwaxy": "S6_milk_waxy",
50
+ "乳熟蜡熟期": "S6_milk_waxy",
51
+ "milkdoughripening": "S6_milk_waxy",
52
+ "milkwaxy": "S6_milk_waxy",
53
+ "s7yellowripening": "S7_yellow_ripening",
54
+ "黄熟期": "S7_yellow_ripening",
55
+ "yellowripening": "S7_yellow_ripening",
56
+ "s8maturitysenescence": "S8_maturity_senescence",
57
+ "成熟衰老期": "S8_maturity_senescence",
58
+ "maturitysenescence": "S8_maturity_senescence",
59
+ }
60
+ _TEXT_BANNED_RE = re.compile(
61
+ r"(?:%|\bpp\b|source\s*=|target\s*=|change\s*=|[\\/]"
62
+ r"|\b(?:pixel|pixels|mask|coordinate|coordinates|bottom_gap|boundary_contact)\b"
63
+ r"|\b(?:s_color|canopy/architecture|coverage|pending|invalid|not_applicable)\b)",
64
+ re.IGNORECASE,
65
+ )
66
+ _TEXT_NUMBER_RE = re.compile(r"(?<![A-Za-z])[+-]?\d+(?:\.\d+)?(?:\s*(?:%|pp))?")
67
+ _EVIDENCE_PHRASES = {
68
+ "plant remains inside frame",
69
+ "plant reaches image edge",
70
+ "one-sided lean is visible",
71
+ "off-center projected plant is visible",
72
+ "possible truncation is visible",
73
+ "frame completeness is uncertain",
74
+ "no obvious tilt or clipping",
75
+ }
76
+ _SIDES = {"top", "bottom", "left", "right"}
77
+
78
+
79
+ def _load_registry(protocol_root: Path | None = None) -> dict[str, Any]:
80
+ path = (protocol_root or PROTOCOL_ROOT) / "VIEW_VARIABLE_BINDINGS.json"
81
+ return json.loads(path.read_text(encoding="utf-8"))
82
+
83
+
84
+ def _view_spec(view: str, protocol_root: Path | None = None) -> tuple[str, Mapping[str, Any]]:
85
+ normalized = normalize_view(view)
86
+ return normalized, _load_registry(protocol_root)[normalized]
87
+
88
+
89
+ def _legacy_annotation_contract(protocol_root: Path | None = None) -> bool:
90
+ """Return whether a protocol snapshot still uses the v1 annotation fields."""
91
+
92
+ root = protocol_root or PROTOCOL_ROOT
93
+ try:
94
+ schema = json.loads((root / "OUTPUT_SCHEMA_FRONT.json").read_text(encoding="utf-8"))
95
+ except (OSError, json.JSONDecodeError):
96
+ # Keep the historical default safe when a caller supplies an incomplete
97
+ # protocol root; the API runner will report the missing schema separately.
98
+ return True
99
+ required = schema.get("required", [])
100
+ return "image_quality_review" in required
101
+
102
+
103
+ def normalize_view(raw_view: str) -> Literal["front", "top"]:
104
+ """Normalize the view labels accepted by pair manifests."""
105
+
106
+ value = str(raw_view).strip().lower()
107
+ if value in {"side0", "side90", "front", "front_view"}:
108
+ return "front"
109
+ if value in {"top", "top_view"}:
110
+ return "top"
111
+ raise ValueError(f"Unknown view label: {raw_view!r}")
112
+
113
+
114
+ def _stage_alias_key(value: str) -> str:
115
+ text = str(value).strip().lower()
116
+ if text in _STAGE_ALIASES:
117
+ return text
118
+ return re.sub(r"[\s_\-/]+", "", text)
119
+
120
+
121
+ def stage_id_from_label(value: str) -> str:
122
+ """Return the canonical V9 stage ID for an English or Chinese label."""
123
+
124
+ key = _stage_alias_key(value)
125
+ try:
126
+ return _STAGE_ALIASES[key]
127
+ except KeyError as exc:
128
+ raise ValueError(f"Unknown stage label: {value!r}") from exc
129
+
130
+
131
+ def _is_number(value: Any) -> bool:
132
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value))
133
+
134
+
135
+ def _finite_or_none(value: Any) -> bool:
136
+ return value is None or _is_number(value)
137
+
138
+
139
+ def _metric_range(key: str, value: Any) -> bool:
140
+ if value is None:
141
+ return True
142
+ if not _is_number(value):
143
+ return False
144
+ if key in {"culm", "leaves_area"}:
145
+ return 0.0 <= float(value) <= 100.0
146
+ if key in {"plant_density", "canopy"} or is_color_proxy_key(key):
147
+ return 0.0 <= float(value) <= 1.0
148
+ if key == "panicle":
149
+ return isinstance(value, int) and not isinstance(value, bool) and value in {0, 1}
150
+ return False
151
+
152
+
153
+ def is_color_proxy_key(public_key: str, metric_key: str | None = None) -> bool:
154
+ """Return whether a public or local metric key is the plant-color proxy."""
155
+
156
+ return public_key in _COLOR_PROXY_PUBLIC_KEYS or metric_key in _COLOR_PROXY_METRIC_KEYS
157
+
158
+
159
+ def _optional_color_value(container: Mapping[str, Any], name: str) -> Any:
160
+ for candidate in (name, f"raw_{name}"):
161
+ if candidate in container:
162
+ return container[candidate]
163
+ return None
164
+
165
+
166
+ def _validate_color_fractions(metric: Mapping[str, Any], issues: list[str]) -> None:
167
+ containers: list[Mapping[str, Any]] = []
168
+ for key in ("source", "target", "qc"):
169
+ value = metric.get(key)
170
+ if isinstance(value, Mapping):
171
+ containers.append(value)
172
+ for container in containers:
173
+ yellow = _optional_color_value(container, "yellow_fraction")
174
+ brown = _optional_color_value(container, "brown_fraction")
175
+ if yellow is None and brown is None:
176
+ continue
177
+ if yellow is not None and (not _is_number(yellow) or not 0 <= float(yellow) <= 1):
178
+ issues.append("yellow_fraction must be finite and in [0, 1]")
179
+ if brown is not None and (not _is_number(brown) or not 0 <= float(brown) <= 1):
180
+ issues.append("brown_fraction must be finite and in [0, 1]")
181
+ if _is_number(yellow) and _is_number(brown) and float(yellow) + float(brown) > 1:
182
+ issues.append("yellow_fraction + brown_fraction must be <= 1")
183
+
184
+
185
+ def validate_metric_evidence(
186
+ view: str,
187
+ evidence: Mapping[str, Any],
188
+ *,
189
+ protocol_root: Path | None = None,
190
+ ) -> list[str]:
191
+ """Validate a view's complete metric evidence and return readable issues."""
192
+
193
+ issues: list[str] = []
194
+ try:
195
+ normalized, spec = _view_spec(view, protocol_root)
196
+ except (TypeError, ValueError) as exc:
197
+ return [str(exc)]
198
+ if not isinstance(evidence, Mapping):
199
+ return ["metric evidence must be an object"]
200
+ expected_keys = list(spec["ordered_keys"])
201
+ actual_keys = list(evidence.keys())
202
+ for key in expected_keys:
203
+ if key not in evidence:
204
+ issues.append(f"missing metric evidence: {key}")
205
+ for key in actual_keys:
206
+ if key not in expected_keys:
207
+ issues.append(f"unexpected metric evidence: {key}")
208
+ for key in expected_keys:
209
+ metric = evidence.get(key)
210
+ if not isinstance(metric, Mapping):
211
+ issues.append(f"{key} must be an object")
212
+ continue
213
+ required = {"metric_key", "source", "target", "unit", "algorithm_version", "qc"}
214
+ missing = required - set(metric)
215
+ extra = set(metric) - required
216
+ if missing:
217
+ issues.append(f"{key} missing fields: {sorted(missing)}")
218
+ if extra:
219
+ issues.append(f"{key} has unexpected fields: {sorted(extra)}")
220
+ expected_metric_key = spec["metric_keys"][key]
221
+ if metric.get("metric_key") != expected_metric_key:
222
+ issues.append(f"{key}.metric_key must be {expected_metric_key}")
223
+ if not isinstance(metric.get("unit"), str) or not metric.get("unit"):
224
+ issues.append(f"{key}.unit must be non-empty")
225
+ elif metric.get("unit") != spec["display_units"][key]:
226
+ issues.append(f"{key}.unit must be {spec['display_units'][key]}")
227
+ if not isinstance(metric.get("algorithm_version"), str) or not metric.get("algorithm_version"):
228
+ issues.append(f"{key}.algorithm_version must be non-empty")
229
+ qc = metric.get("qc")
230
+ if not isinstance(qc, Mapping):
231
+ issues.append(f"{key}.qc must be an object")
232
+ else:
233
+ allowed_qc = {"valid", "reason_codes", "color_coverage", "boundary_contact", "bottom_gap"}
234
+ unexpected_qc = set(qc) - allowed_qc
235
+ if unexpected_qc:
236
+ issues.append(f"{key}.qc has unexpected fields: {sorted(unexpected_qc)}")
237
+ if not isinstance(qc.get("valid"), bool):
238
+ issues.append(f"{key}.qc.valid must be boolean")
239
+ if not isinstance(qc.get("reason_codes"), list) or not all(isinstance(item, str) for item in qc.get("reason_codes", [])):
240
+ issues.append(f"{key}.qc.reason_codes must be a string list")
241
+ coverage = qc.get("color_coverage")
242
+ if coverage is not None and (not _is_number(coverage) or not 0 <= float(coverage) <= 1):
243
+ issues.append(f"{key}.qc.color_coverage must be in [0, 1]")
244
+ for side in ("source", "target"):
245
+ observation = metric.get(side)
246
+ if not isinstance(observation, Mapping):
247
+ issues.append(f"{key}.{side} must be an object")
248
+ continue
249
+ missing_obs = {"value", "status"} - set(observation)
250
+ extra_obs = set(observation) - {"value", "status"}
251
+ if missing_obs:
252
+ issues.append(f"{key}.{side} missing fields: {sorted(missing_obs)}")
253
+ if extra_obs:
254
+ issues.append(f"{key}.{side} has unexpected fields: {sorted(extra_obs)}")
255
+ value = observation.get("value")
256
+ status = observation.get("status")
257
+ if not _finite_or_none(value):
258
+ issues.append(f"{key}.{side}.value must be finite or null")
259
+ if status not in _STATUSES:
260
+ issues.append(f"{key}.{side}.status is invalid")
261
+ if not _metric_range(key, value):
262
+ issues.append(f"{key}.{side}.value is outside the allowed range")
263
+ if status == "available" and value is None:
264
+ issues.append(f"{key}.{side} available value cannot be null")
265
+ if key == "panicle" and value is not None and not _metric_range(key, value):
266
+ issues.append(f"{key}.{side} panicle value must be integer 0 or 1")
267
+ if is_color_proxy_key(key, str(metric.get("metric_key", ""))) and isinstance(qc, Mapping):
268
+ coverage = qc.get("color_coverage")
269
+ if _is_number(coverage) and float(coverage) < 0.70:
270
+ for side in ("source", "target"):
271
+ if isinstance(metric.get(side), Mapping) and metric[side].get("status") == "available":
272
+ issues.append(f"{key}.{side} must be pending when color coverage is below 0.70")
273
+ _validate_color_fractions(metric, issues)
274
+ return issues
275
+
276
+
277
+ def _first(mapping: Mapping[str, Any], *keys: str) -> Any:
278
+ for key in keys:
279
+ if key in mapping:
280
+ return mapping[key]
281
+ return None
282
+
283
+
284
+ def _parse_date(value: Any) -> date | None:
285
+ if isinstance(value, datetime):
286
+ return value.date()
287
+ if isinstance(value, date):
288
+ return value
289
+ if isinstance(value, str):
290
+ try:
291
+ return date.fromisoformat(value[:10])
292
+ except ValueError:
293
+ return None
294
+ return None
295
+
296
+
297
+ def _group_is_clean(group: Mapping[str, Any]) -> bool:
298
+ if group.get("quarantined") is True or group.get("excluded") is True:
299
+ return False
300
+ if group.get("is_clean") is False:
301
+ return False
302
+ for key in ("clean_status", "status", "qc_status"):
303
+ if key in group:
304
+ value = str(group[key]).strip().lower()
305
+ return value in {"clean", "ok", "eligible", "available", "keep"}
306
+ return True
307
+
308
+
309
+ def _lookup_group(groups: Mapping[str, Mapping[str, Any]], identifier: Any) -> Mapping[str, Any] | None:
310
+ if identifier is None:
311
+ return None
312
+ value = str(identifier)
313
+ return groups.get(value) or groups.get(identifier)
314
+
315
+
316
+ def validate_pair_metadata(
317
+ row: Mapping[str, Any],
318
+ *,
319
+ clean_groups: Mapping[str, Mapping[str, Any]],
320
+ panicle_groups: Mapping[str, Mapping[str, Any]],
321
+ ) -> list[str]:
322
+ """Validate the hard QC fields needed before sending a pair to GPT."""
323
+
324
+ issues: list[str] = []
325
+ if not isinstance(row, Mapping):
326
+ return ["pair row must be an object"]
327
+ try:
328
+ view = normalize_view(_first(row, "view", "view_label"))
329
+ except (TypeError, ValueError) as exc:
330
+ issues.append(str(exc))
331
+ view = "front"
332
+ for label, keys in {
333
+ "plant identity": ("plant_id", "plant", "single_plant_id"),
334
+ "accession identity": ("accession_id", "accession", "canonical_accession_id"),
335
+ }.items():
336
+ if _first(row, *keys) in (None, ""):
337
+ issues.append(f"missing {label}")
338
+ source_group_id = _first(row, "source_group_id", "source_group")
339
+ target_group_id = _first(row, "target_group_id", "target_group")
340
+ if source_group_id in (None, "") or target_group_id in (None, ""):
341
+ issues.append("missing source/target group identity")
342
+ source_group = _lookup_group(clean_groups, source_group_id)
343
+ target_group = _lookup_group(clean_groups, target_group_id)
344
+ if source_group is None:
345
+ issues.append("source group is missing from clean manifest")
346
+ elif not _group_is_clean(source_group):
347
+ issues.append("source group is not clean")
348
+ if target_group is None:
349
+ issues.append("target group is missing from clean manifest")
350
+ elif not _group_is_clean(target_group):
351
+ issues.append("target group is not clean")
352
+ source_path = _first(row, "source_path", "source_image_path")
353
+ target_path = _first(row, "target_path", "target_image_path")
354
+ if source_path in (None, "") or target_path in (None, ""):
355
+ issues.append("missing source/target image path")
356
+ else:
357
+ source_text = str(source_path)
358
+ target_text = str(target_path)
359
+ if source_text == target_text:
360
+ issues.append("source and target image paths must differ")
361
+ for label, path_value in (("source", source_path), ("target", target_path)):
362
+ if not Path(str(path_value)).is_file():
363
+ issues.append(f"{label} image path does not exist")
364
+ source_date = _parse_date(_first(row, "source_date", "source_capture_date"))
365
+ target_date = _parse_date(_first(row, "target_date", "target_capture_date"))
366
+ if source_date is None or target_date is None:
367
+ issues.append("source and target dates must be valid")
368
+ elif source_date >= target_date:
369
+ issues.append("source date must precede target date")
370
+ source_stage_value = _first(row, "source_stage_id", "source_stage", "source_stage_en")
371
+ target_stage_value = _first(row, "target_stage_id", "target_stage", "target_stage_en")
372
+ try:
373
+ source_stage = stage_id_from_label(source_stage_value)
374
+ target_stage = stage_id_from_label(target_stage_value)
375
+ if _STAGE_ORDER.index(source_stage) > _STAGE_ORDER.index(target_stage):
376
+ issues.append("target stage must not precede source stage")
377
+ except (TypeError, ValueError) as exc:
378
+ issues.append(str(exc))
379
+ for group_id in (source_group_id, target_group_id):
380
+ group = _lookup_group(panicle_groups, group_id)
381
+ if group is None:
382
+ continue
383
+ value = _first(group, "panicle_visibility", "panicle", "value")
384
+ if value is not None and not _metric_range("panicle", value):
385
+ issues.append(f"panicle visibility for {group_id} must be 0 or 1")
386
+ source_panicle = _first(row, "source_panicle_visibility", "source_panicle")
387
+ target_panicle = _first(row, "target_panicle_visibility", "target_panicle")
388
+ if source_panicle is not None and not _metric_range("panicle", source_panicle):
389
+ issues.append("source panicle visibility must be 0 or 1")
390
+ if target_panicle is not None and not _metric_range("panicle", target_panicle):
391
+ issues.append("target panicle visibility must be 0 or 1")
392
+ if source_panicle == 1 and target_panicle == 0:
393
+ issues.append("panicle visibility cannot reverse from 1 to 0")
394
+ if view == "top" and "culm" in row:
395
+ issues.append("top pair must not contain culm metric")
396
+ return issues
397
+
398
+
399
+ def _clean_text_issues(text: Any, location: str) -> list[str]:
400
+ if not isinstance(text, str) or not text.strip():
401
+ return [f"{location} text must be non-empty"]
402
+ issues: list[str] = []
403
+ if _TEXT_NUMBER_RE.search(text) or _TEXT_BANNED_RE.search(text):
404
+ issues.append(f"{location} contains numeric or renderer-owned text")
405
+ if re.search(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b", text):
406
+ issues.append(f"{location} contains a date")
407
+ return issues
408
+
409
+
410
+ def _validate_quality_item(item: Any, location: str) -> list[str]:
411
+ issues: list[str] = []
412
+ if not isinstance(item, Mapping):
413
+ return [f"{location} must be an object"]
414
+ expected = {"tilt", "clipping", "tilt_clipping_risk", "review_recommendation", "evidence"}
415
+ if set(item) != expected:
416
+ issues.append(f"{location} keys must be {sorted(expected)}")
417
+ tilt = item.get("tilt")
418
+ if not isinstance(tilt, Mapping) or set(tilt) != {"label", "confidence"}:
419
+ issues.append(f"{location}.tilt has invalid shape")
420
+ else:
421
+ if tilt.get("label") not in {"none", "mild", "marked", "uncertain"}:
422
+ issues.append(f"{location}.tilt.label is invalid")
423
+ if tilt.get("confidence") not in {"high", "medium", "low"}:
424
+ issues.append(f"{location}.tilt.confidence is invalid")
425
+ clipping = item.get("clipping")
426
+ if not isinstance(clipping, Mapping) or set(clipping) != {"label", "sides", "confidence"}:
427
+ issues.append(f"{location}.clipping has invalid shape")
428
+ else:
429
+ if clipping.get("label") not in {"none", "minor", "substantial", "uncertain"}:
430
+ issues.append(f"{location}.clipping.label is invalid")
431
+ sides = clipping.get("sides")
432
+ if (
433
+ not isinstance(sides, list)
434
+ or not all(isinstance(side, str) for side in sides)
435
+ or len(sides) != len(set(sides))
436
+ or not set(sides).issubset(_SIDES)
437
+ ):
438
+ issues.append(f"{location}.clipping.sides is invalid")
439
+ if clipping.get("confidence") not in {"high", "medium", "low"}:
440
+ issues.append(f"{location}.clipping.confidence is invalid")
441
+ if item.get("tilt_clipping_risk") not in {"low", "medium", "high", "uncertain"}:
442
+ issues.append(f"{location}.tilt_clipping_risk is invalid")
443
+ if item.get("review_recommendation") not in {"keep", "manual_review", "exclude_candidate"}:
444
+ issues.append(f"{location}.review_recommendation is invalid")
445
+ evidence = item.get("evidence")
446
+ if (
447
+ not isinstance(evidence, list)
448
+ or not evidence
449
+ or not all(isinstance(phrase, str) for phrase in evidence)
450
+ or len(evidence) != len(set(evidence))
451
+ or not set(evidence).issubset(_EVIDENCE_PHRASES)
452
+ ):
453
+ issues.append(f"{location}.evidence is invalid")
454
+ return issues
455
+
456
+
457
+ def validate_annotation(
458
+ annotation: Mapping[str, Any],
459
+ *,
460
+ view: str,
461
+ source_stage_id: str,
462
+ target_stage_id: str,
463
+ protocol_root: Path | None = None,
464
+ ) -> list[str]:
465
+ """Validate provider JSON before it can be rendered or persisted as success."""
466
+
467
+ issues: list[str] = []
468
+ try:
469
+ normalized, spec = _view_spec(view, protocol_root)
470
+ expected_source = stage_id_from_label(source_stage_id)
471
+ expected_target = stage_id_from_label(target_stage_id)
472
+ except (TypeError, ValueError) as exc:
473
+ return [str(exc)]
474
+ if not isinstance(annotation, Mapping):
475
+ return ["annotation must be an object"]
476
+ legacy_contract = _legacy_annotation_contract(protocol_root)
477
+ root_keys = {"stage_reasoning", "growth_plan", "target_phenotype"}
478
+ if legacy_contract:
479
+ root_keys.add("image_quality_review")
480
+ if set(annotation) != root_keys:
481
+ issues.append(f"annotation root keys must be {sorted(root_keys)}")
482
+ reasoning = annotation.get("stage_reasoning")
483
+ if not isinstance(reasoning, Mapping) or set(reasoning) != {"current_stage", "future_stage"}:
484
+ issues.append("stage_reasoning must contain only current_stage and future_stage")
485
+ else:
486
+ try:
487
+ current = stage_id_from_label(reasoning["current_stage"])
488
+ future = stage_id_from_label(reasoning["future_stage"])
489
+ if current != expected_source:
490
+ issues.append("stage_reasoning.current_stage does not match authoritative source stage")
491
+ if future != expected_target:
492
+ issues.append("stage_reasoning.future_stage does not match authoritative target stage")
493
+ if _STAGE_ORDER.index(current) > _STAGE_ORDER.index(future):
494
+ issues.append("stage transition moves backward")
495
+ except (TypeError, ValueError) as exc:
496
+ issues.append(str(exc))
497
+ expected_keys = list(spec["ordered_keys"])
498
+ for section_name, entry_name in (("growth_plan", "plan"), ("target_phenotype", "phenotype")):
499
+ section = annotation.get(section_name)
500
+ if not isinstance(section, Mapping):
501
+ issues.append(f"{section_name} must be an object")
502
+ continue
503
+ if list(section.keys()) != expected_keys:
504
+ issues.append(f"{section_name} keys must exactly follow registry order: {expected_keys}")
505
+ for key in expected_keys:
506
+ entry = section.get(key)
507
+ if not isinstance(entry, Mapping):
508
+ issues.append(f"{section_name}.{key} must be an object")
509
+ continue
510
+ required = {"text", "guardrails"} if legacy_contract and entry_name == "plan" else {"text"}
511
+ if set(entry) != required:
512
+ issues.append(f"{section_name}.{key} keys must be {sorted(required)}")
513
+ issues.extend(_clean_text_issues(entry.get("text"), f"{section_name}.{key}"))
514
+ if legacy_contract and entry_name == "plan":
515
+ guardrails = entry.get("guardrails")
516
+ if not isinstance(guardrails, list) or not all(isinstance(item, str) and item.strip() for item in guardrails):
517
+ issues.append(f"{section_name}.{key}.guardrails must be a string list")
518
+ else:
519
+ for index, guardrail in enumerate(guardrails):
520
+ issues.extend(_clean_text_issues(guardrail, f"{section_name}.{key}.guardrails[{index}]"))
521
+ if legacy_contract:
522
+ quality = annotation.get("image_quality_review")
523
+ if not isinstance(quality, Mapping) or set(quality) != {"source", "target"}:
524
+ issues.append("image_quality_review must contain source and target")
525
+ else:
526
+ issues.extend(_validate_quality_item(quality["source"], "image_quality_review.source"))
527
+ issues.extend(_validate_quality_item(quality["target"], "image_quality_review.target"))
528
+ return issues
529
+
530
+
531
+ def _renderable(metric: Mapping[str, Any], key: str) -> tuple[bool, float | int | None, float | int | None]:
532
+ if not isinstance(metric, Mapping):
533
+ return False, None, None
534
+ qc = metric.get("qc")
535
+ if not isinstance(qc, Mapping) or qc.get("valid") is not True:
536
+ return False, None, None
537
+ values: list[Any] = []
538
+ for side in ("source", "target"):
539
+ observation = metric.get(side)
540
+ if not isinstance(observation, Mapping) or observation.get("status") != "available":
541
+ return False, None, None
542
+ value = observation.get("value")
543
+ if not _is_number(value) or not _metric_range(key, value):
544
+ return False, None, None
545
+ values.append(value)
546
+ return True, values[0], values[1]
547
+
548
+
549
+ def _numeric_evidence(key: str, metric: Mapping[str, Any]) -> str | None:
550
+ ok, source, target = _renderable(metric, key)
551
+ if not ok:
552
+ return None
553
+ if key == "panicle":
554
+ source_int = int(source) # type: ignore[arg-type]
555
+ target_int = int(target) # type: ignore[arg-type]
556
+ source_label = "visible" if source_int else "not visible"
557
+ target_label = "visible" if target_int else "not visible"
558
+ return f"Source = {source_label}; Target = {target_label}; Change = {target_int - source_int:+d}."
559
+ scale = 100.0 if is_color_proxy_key(key, str(metric.get("metric_key", ""))) or key in {"plant_density", "canopy"} else 1.0
560
+ source_value = float(source) * scale # type: ignore[arg-type]
561
+ target_value = float(target) * scale # type: ignore[arg-type]
562
+ change = target_value - source_value
563
+ return f"Source = {source_value:.2f}%; Target = {target_value:.2f}%; Change = {change:+.2f} pp."
564
+
565
+
566
+ def _with_sentence(text: str) -> str:
567
+ value = text.strip()
568
+ return value if value.endswith((".", "!", "?")) else value + "."
569
+
570
+
571
+ def render_cot(
572
+ annotation: Mapping[str, Any],
573
+ *,
574
+ view: str,
575
+ metric_evidence: Mapping[str, Any],
576
+ protocol_root: Path | None = None,
577
+ ) -> tuple[str, list[str]]:
578
+ """Render validated biological text and locally owned metric evidence."""
579
+
580
+ _, spec = _view_spec(view, protocol_root)
581
+ omissions: list[str] = []
582
+ reasoning = annotation["stage_reasoning"]
583
+ lines = [
584
+ "<GROWTH_COT>",
585
+ "",
586
+ "Stage reasoning",
587
+ f"Current stage: {reasoning['current_stage']}.",
588
+ f"Future stage: {reasoning['future_stage']}.",
589
+ "",
590
+ "Growth plan",
591
+ ]
592
+ for key in spec["ordered_keys"]:
593
+ entry = annotation["growth_plan"][key]
594
+ line = f"{spec['section_labels'][key]}: {_with_sentence(entry['text'])}"
595
+ guardrails = entry.get("guardrails", [])
596
+ if guardrails:
597
+ rendered_guardrails = "; ".join(item.rstrip(".") for item in guardrails)
598
+ line += f" Guardrails: {rendered_guardrails}."
599
+ evidence = _numeric_evidence(key, metric_evidence.get(key, {}))
600
+ if evidence is None:
601
+ omissions.append(key)
602
+ else:
603
+ from .cot_metric_names import metric_prefix
604
+ line += f" {metric_prefix(spec, key)}{evidence}"
605
+ lines.append(line)
606
+ lines.extend(["", "Target phenotype"])
607
+ for key in spec["ordered_keys"]:
608
+ entry = annotation["target_phenotype"][key]
609
+ lines.append(f"{spec['section_labels'][key]}: {_with_sentence(entry['text'])}")
610
+ lines.extend(["", "</GROWTH_COT>"])
611
+ return "\n".join(lines) + "\n", omissions
612
+
613
+
614
+ def protocol_sha256(protocol_root: Path) -> str:
615
+ """Hash protocol file names and bytes in sorted order."""
616
+
617
+ digest = hashlib.sha256()
618
+ for path in sorted(item for item in protocol_root.rglob("*") if item.is_file()):
619
+ relative = path.relative_to(protocol_root).as_posix().encode("utf-8")
620
+ digest.update(relative)
621
+ digest.update(b"\0")
622
+ digest.update(path.read_bytes())
623
+ digest.update(b"\0")
624
+ return digest.hexdigest()
src/wgsr_v9/executor_cache_index.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate DiffSynth train caches and write the homogeneous-layout index."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from collections import Counter
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import torch
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parents[2]
16
+
17
+ from wgsr_v9.diffsynth_batching import batch_layout_key, layout_key # noqa: E402
18
+ from wgsr_v9.io import read_jsonl, sha256_path, write_json # noqa: E402
19
+ from wgsr_v9.executor_training import ALGORITHM_VERSION # noqa: E402
20
+
21
+
22
+ def expected_latent_shape(row: dict[str, Any]) -> tuple[int, int, int, int]:
23
+ """Validate species geometry before accepting a cached training example."""
24
+ if row.get("species") == "maize":
25
+ from wgsr_v9.maize.experiment import EXECUTOR_PROTOCOL
26
+
27
+ if (row.get("protocol_version") != EXECUTOR_PROTOCOL
28
+ or row.get("source_size") != [768, 1280]
29
+ or row.get("view") != "side0"):
30
+ raise ValueError("maize cache requires the reviewed native 768x1280 side0 contract")
31
+ return (1, 64, 80, 48)
32
+ return (1, 64, 56, 42) if row["view"] in {"front", "side0"} else (1, 64, 42, 56)
33
+
34
+
35
+ def _cache_files(cache_root: Path, world_size: int) -> list[tuple[int, int, Path]]:
36
+ records: list[tuple[int, int, Path]] = []
37
+ rank_dirs = [path for path in cache_root.iterdir() if path.is_dir() and path.name.isdigit()]
38
+ ranks = sorted(int(path.name) for path in rank_dirs)
39
+ if ranks != list(range(world_size)):
40
+ raise ValueError(f"cache ranks must be 0..{world_size - 1}, found {ranks}")
41
+ for rank_dir in sorted(rank_dirs, key=lambda path: int(path.name)):
42
+ rank = int(rank_dir.name)
43
+ files = sorted(rank_dir.glob("*.pth"), key=lambda path: int(path.stem))
44
+ if any(not path.stem.isdigit() for path in files):
45
+ raise ValueError(f"cache contains nonnumeric pth filename under {rank_dir}")
46
+ for path in files:
47
+ records.append((rank, int(path.stem), path))
48
+ return records
49
+
50
+
51
+ def build_index(
52
+ cache_root: Path,
53
+ metadata_path: Path,
54
+ output_path: Path,
55
+ *,
56
+ world_size: int,
57
+ variant: str,
58
+ ) -> dict[str, Any]:
59
+ cache_root = cache_root.resolve()
60
+ metadata_path = metadata_path.resolve()
61
+ output_path = output_path.resolve()
62
+ rows = read_jsonl(metadata_path)
63
+ if not rows:
64
+ raise ValueError("training metadata is empty")
65
+ records = _cache_files(cache_root, world_size)
66
+ if len(records) != len(rows):
67
+ raise ValueError(f"cache count {len(records)} does not match metadata count {len(rows)}")
68
+
69
+ items: list[dict[str, Any]] = []
70
+ seen_indices: set[int] = set()
71
+ for rank, local_index, path in records:
72
+ original_index = local_index * world_size + rank
73
+ if original_index >= len(rows) or original_index in seen_indices:
74
+ raise ValueError(f"invalid distributed cache order at rank={rank}, local_index={local_index}")
75
+ row = rows[original_index]
76
+ inputs = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
77
+ shared, positive, _negative = inputs
78
+ if shared.get("use_gradient_checkpointing") is not True:
79
+ raise ValueError(f"gradient checkpointing is not enabled in {path}")
80
+ if len(shared.get("edit_latents", [])) != 1:
81
+ raise ValueError(f"expected exactly one source latent in {path}")
82
+ if positive.get("prompt") != row["prompt"]:
83
+ raise ValueError(f"cached prompt does not match metadata row {original_index}: {path}")
84
+ expected_latent = expected_latent_shape(row)
85
+ target_latent = shared["input_latents"]
86
+ source_latent = shared["edit_latents"][0]
87
+ if tuple(target_latent.shape) != expected_latent or tuple(source_latent.shape) != expected_latent:
88
+ raise ValueError(
89
+ f"unexpected target/source latent layout for {row['request_id']}: "
90
+ f"{tuple(target_latent.shape)} / {tuple(source_latent.shape)}"
91
+ )
92
+ for tensor in (target_latent, source_latent, positive["prompt_embeds"]):
93
+ if not bool(torch.isfinite(tensor).all()):
94
+ raise ValueError(f"nonfinite cached training tensor: {path}")
95
+ key = layout_key(inputs)
96
+ batch_key = batch_layout_key(inputs)
97
+ items.append(
98
+ {
99
+ "algorithm_version": ALGORITHM_VERSION,
100
+ "request_id": row["request_id"],
101
+ "original_row_index": original_index,
102
+ "rank": rank,
103
+ "rank_local_index": local_index,
104
+ "layout_key": repr(key),
105
+ "batch_layout_key": repr(batch_key),
106
+ "input_path": row["edit_image"],
107
+ "output_path": str(path.resolve()),
108
+ "status": "ready",
109
+ "error": None,
110
+ "retry_count": 0,
111
+ "bytes": path.stat().st_size,
112
+ }
113
+ )
114
+ seen_indices.add(original_index)
115
+ del inputs, shared, positive
116
+ if seen_indices != set(range(len(rows))):
117
+ raise ValueError("distributed cache does not cover every metadata row exactly once")
118
+ items.sort(key=lambda item: item["original_row_index"])
119
+ report = {
120
+ "algorithm_version": ALGORITHM_VERSION,
121
+ "executor_variant": variant,
122
+ "input_path": str(metadata_path),
123
+ "output_path": str(output_path),
124
+ "cache_root": str(cache_root),
125
+ "metadata_sha256": sha256_path(metadata_path),
126
+ "world_size": world_size,
127
+ "count": len(items),
128
+ "all_condition_and_target_tensors_finite": True,
129
+ "all_rows_order_and_prompt_checked": True,
130
+ "layout_counts": dict(Counter(item["layout_key"] for item in items)),
131
+ "batch_layout_counts": dict(Counter(item["batch_layout_key"] for item in items)),
132
+ "total_bytes": sum(item["bytes"] for item in items),
133
+ "items": items,
134
+ "status": "complete",
135
+ "error": None,
136
+ "retry_count": 0,
137
+ }
138
+ write_json(output_path, report)
139
+ return report
140
+
141
+
142
+ def main() -> int:
143
+ parser = argparse.ArgumentParser(description=__doc__)
144
+ parser.add_argument("--cache-root", type=Path, required=True)
145
+ parser.add_argument("--metadata", type=Path, required=True)
146
+ parser.add_argument("--output", type=Path, required=True)
147
+ parser.add_argument("--world-size", type=int, default=8)
148
+ parser.add_argument("--variant", choices=("simple", "teacher_cot"), required=True)
149
+ args = parser.parse_args()
150
+ report = build_index(
151
+ args.cache_root,
152
+ args.metadata,
153
+ args.output,
154
+ world_size=args.world_size,
155
+ variant=args.variant,
156
+ )
157
+ print(json.dumps({key: value for key, value in report.items() if key != "items"}, indent=2))
158
+ return 0
159
+
160
+
161
+ if __name__ == "__main__":
162
+ raise SystemExit(main())
src/wgsr_v9/executor_dropout.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reviewed, mutually exclusive condition dropout for cached executor SFT.
2
+
3
+ All ranks use one action per global batch. The historical text-only action
4
+ tape is retained, including its drop_numeric label, which acts as keep for text
5
+ models. No numeric adapter is installed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter
11
+ import hashlib
12
+ import json
13
+ import random
14
+ from pathlib import Path
15
+ from typing import Any, Iterator
16
+
17
+ import torch
18
+
19
+ from .io import canonical_sha256, sha256_path
20
+
21
+ VERSION = "wgsr_v9_executor_modality_dropout_v1"
22
+ ACTIONS = ("keep", "drop_text", "drop_image", "drop_numeric")
23
+ PROBABILITIES = (0.7, 0.1, 0.1, 0.1)
24
+ COT_SEPARATOR = "\nGrowth plan for the target image:\n<GROWTH_COT>"
25
+
26
+
27
+ def drop_cot(prompt: str) -> str:
28
+ if prompt.count(COT_SEPARATOR) != 1 or prompt.count("</GROWTH_COT>") != 1:
29
+ raise ValueError("drop_text requires exactly one reviewed v3 CoT suffix")
30
+ prefix, body = prompt.split(COT_SEPARATOR)
31
+ if not prefix or body.split("</GROWTH_COT>", 1)[1].strip():
32
+ raise ValueError("unexpected text outside the reviewed CoT wrapper")
33
+ return prefix
34
+
35
+
36
+ def stream_seed(seed: int, *parts: Any) -> int:
37
+ value = json.dumps([VERSION, seed, *parts], separators=(",", ":")).encode()
38
+ return int.from_bytes(hashlib.sha256(value).digest()[:8], "big") % (2**63 - 1)
39
+
40
+
41
+ def action_tape(steps: int, seed: int, epoch: int) -> list[str]:
42
+ counts = [round(steps * p) for p in PROBABILITIES]
43
+ if steps <= 0 or sum(counts) != steps or any(abs(steps * p - n) > 1e-8
44
+ for p, n in zip(PROBABILITIES, counts)):
45
+ raise ValueError("exact reviewed 70/10/10/10 schedule requires a multiple of 10 steps")
46
+ tape = [action for action, count in zip(ACTIONS, counts) for _ in range(count)]
47
+ random.Random(stream_seed(seed, "actions", epoch)).shuffle(tape)
48
+ return tape
49
+
50
+
51
+ def validate_policy(config: dict[str, Any]) -> None:
52
+ if config.get("algorithm_version") != VERSION:
53
+ raise ValueError("unsupported condition dropout version")
54
+ if config.get("probabilities") != dict(zip(ACTIONS, PROBABILITIES)):
55
+ raise ValueError("unreviewed condition dropout probabilities")
56
+ if config.get("text_scope") != "cot_body" or config.get("sampling_unit") != "global_step":
57
+ raise ValueError("reviewed dropout preserves the task prefix and samples per global step")
58
+ if config.get("numeric_whole_dropout") != 0 or config.get("numeric_slot_dropout") != 0:
59
+ raise ValueError("internal numeric dropout must be disabled for exclusive modality dropout")
60
+
61
+
62
+ class DropoutBatchSampler:
63
+ """Attach an immutable action to each index before Accelerate shards batches."""
64
+
65
+ def __init__(self, base: Any, *, seed: int):
66
+ if base.gradient_accumulation_steps != 1:
67
+ raise ValueError("dropout v1 requires accumulation=1")
68
+ self.base, self.seed = base, seed
69
+ self.batch_size, self.drop_last = base.batch_size, False
70
+ self.groups = base.groups
71
+
72
+ def __len__(self) -> int:
73
+ return len(self.base)
74
+
75
+ def set_epoch(self, epoch: int) -> None:
76
+ self.base.set_epoch(epoch)
77
+
78
+ def __iter__(self) -> Iterator[list[tuple[int, str, int, int]]]:
79
+ actions = action_tape(len(self) // self.base.world_size, self.seed, self.base.epoch)
80
+ for microbatch, indices in enumerate(self.base):
81
+ step = microbatch // self.base.world_size
82
+ yield [(i, actions[step], self.base.epoch, step) for i in indices]
83
+
84
+
85
+ def load_dropout_manifest(root: Path, index: dict[str, Any], cached_paths: list[str],
86
+ seed: int, epochs: int) -> dict[str, Any]:
87
+ manifest = json.loads((root / "manifest.json").read_text())
88
+ expected = (VERSION, "complete", index["metadata_sha256"], seed, epochs,
89
+ canonical_sha256(cached_paths))
90
+ found = tuple(manifest.get(k) for k in ("algorithm_version", "status", "metadata_sha256",
91
+ "seed", "epochs", "cached_paths_sha256"))
92
+ if found != expected:
93
+ raise ValueError("dropout cache identity/seed/epochs mismatch or cache incomplete")
94
+ if sha256_path(root / "plan.json") != manifest["plan_sha256"]:
95
+ raise ValueError("dropout action/cache plan changed")
96
+ return manifest
97
+
98
+
99
+ class DropoutCachedDataset:
100
+ def __init__(self, dataset: Any, index: dict[str, Any], root: Path, *, seed: int, epochs: int):
101
+ self.dataset, self.root = dataset, root
102
+ self.cached_data = dataset.cached_data
103
+ paths = [str(Path(p).resolve()) for p in self.cached_data]
104
+ self.manifest = load_dropout_manifest(root, index, paths, seed, epochs)
105
+ self.items = {item["request_id"]: item for item in self.manifest["items"]}
106
+ by_path = {str(Path(i["output_path"]).resolve()): i["request_id"] for i in index["items"]}
107
+ self.ids = [by_path[p] for p in paths]
108
+ self.verified: set[str] = set()
109
+
110
+ def __len__(self) -> int:
111
+ return len(self.dataset)
112
+
113
+ def _load(self, spec: dict[str, Any]) -> Any:
114
+ path = Path(spec["output_path"])
115
+ if str(path) not in self.verified:
116
+ if sha256_path(path) != spec["sha256"]:
117
+ raise ValueError(f"dropout cache integrity mismatch: {path}")
118
+ self.verified.add(str(path))
119
+ return torch.load(path, map_location="cpu", weights_only=False, mmap=True)
120
+
121
+ def __getitem__(self, tag: tuple[int, str, int, int]) -> Any:
122
+ index, action, epoch, step = tag
123
+ if action not in ACTIONS:
124
+ raise ValueError("unknown dropout action")
125
+ # Read the unmodified text cache before applying the scheduled action.
126
+ shared, positive, negative = (dict(p) for p in self.dataset[index])
127
+ request_id = self.ids[index]
128
+ if action in {"drop_text", "drop_image"}:
129
+ item = self.items[request_id]
130
+ spec = item[action]
131
+ cached = self._load(spec)
132
+ if action == "drop_text":
133
+ other_shared, other_positive, _ = cached
134
+ if other_positive["prompt"] != drop_cot(positive["prompt"]):
135
+ raise ValueError("drop_text did not retain exactly the task prefix")
136
+ if not torch.equal(shared["input_latents"], other_shared["input_latents"]):
137
+ raise ValueError("drop_text target differs from original supervision")
138
+ if len(shared["edit_latents"]) != len(other_shared["edit_latents"]) or any(
139
+ not torch.equal(a, b) for a, b in zip(shared["edit_latents"], other_shared["edit_latents"])
140
+ ):
141
+ raise ValueError("drop_text source latent differs")
142
+ else:
143
+ other_positive = cached
144
+ if other_positive["prompt"] != positive["prompt"]:
145
+ raise ValueError("drop_image changed the text")
146
+ if bool(other_positive["edit_image_pad_mask"].any()):
147
+ raise ValueError("drop_image still contains image tokens")
148
+ shared["edit_latents"] = None
149
+ for key in ("prompt", "prompt_embeds", "prompt_embeds_mask", "edit_image_pad_mask"):
150
+ positive[key] = other_positive[key]
151
+ shared["condition_dropout"] = {"action": action, "epoch": epoch, "step": step,
152
+ "request_ids": [request_id]}
153
+ return shared, positive, negative
154
+
155
+
156
+ def action_summary(steps: int, seed: int, epochs: int) -> list[dict[str, Any]]:
157
+ return [{"epoch": epoch, "counts": dict(Counter(action_tape(steps, seed, epoch))),
158
+ "sha256": canonical_sha256(action_tape(steps, seed, epoch))} for epoch in range(epochs)]
src/wgsr_v9/executor_training.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contracts for the paired Qwen Image 2.1 executor SFT packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ ALGORITHM_VERSION = "wgsr_v9_qwen_image21_executor_sft_v1"
10
+ PROTOCOL_VERSION = "wgsr_v9_qwen_image21_executor_prompt_v1"
11
+ WEEKS_PROTOCOL_VERSION = "wgsr_v9_qwen_image21_executor_prompt_v2_weeks"
12
+ NAMED_WEEKS_PROTOCOL_VERSION = "wgsr_v9_qwen_image21_executor_prompt_v3_metric_named_weeks"
13
+ WEEKS_PROTOCOLS = {WEEKS_PROTOCOL_VERSION, NAMED_WEEKS_PROTOCOL_VERSION}
14
+ SUPPORTED_VIEWS = {"front": "front view", "side0": "front view", "top": "top view"}
15
+ EXPECTED_SIZE = {"front": (672, 896), "side0": (672, 896), "top": (896, 672)}
16
+
17
+
18
+ def prediction_interval_weeks(request: dict[str, Any]) -> int:
19
+ """Validate canonical nearest-integer weeks, falling back for legacy requests."""
20
+ days = request.get("actual_interval_days")
21
+ if isinstance(days, bool) or not isinstance(days, int) or days <= 0:
22
+ raise ValueError("actual_interval_days must be a positive integer")
23
+ expected = max(1, (days + 3) // 7)
24
+ weeks = request.get("prediction_interval_weeks", expected)
25
+ if isinstance(weeks, bool) or not isinstance(weeks, int) or weeks != expected:
26
+ raise ValueError("prediction_interval_weeks does not match canonical rounded weeks")
27
+ return weeks
28
+
29
+
30
+ def growth_cot_body(rendered_text: str, request_id: str) -> str:
31
+ """Return the provider-rendered CoT body without changing its contents."""
32
+ text = rendered_text.strip()
33
+ opening = "<GROWTH_COT>"
34
+ closing = "</GROWTH_COT>"
35
+ if not text.startswith(opening) or not text.endswith(closing):
36
+ raise ValueError(f"{request_id}: rendered artifact must have one GROWTH_COT wrapper")
37
+ body = text[len(opening) : -len(closing)].strip()
38
+ if not body or opening in body or closing in body:
39
+ raise ValueError(f"{request_id}: rendered artifact has an empty or nested GROWTH_COT body")
40
+ return body
41
+
42
+
43
+ def executor_prompt(
44
+ request: dict[str, Any],
45
+ *,
46
+ prompt_template: str,
47
+ cot_suffix: str,
48
+ variant: str,
49
+ teacher_cot: str | None = None,
50
+ protocol_version: str = PROTOCOL_VERSION,
51
+ ) -> str:
52
+ """Build one deployment-shaped prompt from source-known request fields."""
53
+ request_id = str(request.get("request_id") or "<missing request_id>")
54
+ view = str(request.get("view") or "")
55
+ if view not in SUPPORTED_VIEWS:
56
+ raise ValueError(f"{request_id}: unsupported view {view!r}")
57
+ if variant not in {"simple", "teacher_cot"}:
58
+ raise ValueError(f"unsupported executor variant: {variant!r}")
59
+ interval_days = int(request["actual_interval_days"])
60
+ if interval_days <= 0:
61
+ raise ValueError(f"{request_id}: prediction interval must be positive")
62
+ if protocol_version in WEEKS_PROTOCOLS:
63
+ weeks = prediction_interval_weeks(request)
64
+ if "{interval_days}" in prompt_template:
65
+ raise ValueError("weeks-only protocol cannot expose exact days in the prompt")
66
+ elif protocol_version == PROTOCOL_VERSION:
67
+ weeks = max(1, math.ceil(interval_days / 7))
68
+ else:
69
+ raise ValueError(f"unsupported executor prompt protocol: {protocol_version}")
70
+ prompt = prompt_template.format(
71
+ accession_id=str(request["accession_id"]),
72
+ view_label=SUPPORTED_VIEWS[view],
73
+ interval_weeks=weeks,
74
+ interval_days=interval_days,
75
+ ).strip()
76
+ if variant == "simple":
77
+ if teacher_cot is not None:
78
+ raise ValueError(f"{request_id}: simple prompt cannot receive teacher CoT")
79
+ return prompt
80
+ if teacher_cot is None or not teacher_cot.strip():
81
+ raise ValueError(f"{request_id}: teacher_cot prompt requires a nonempty CoT body")
82
+ return prompt + cot_suffix.format(growth_cot=teacher_cot.strip())
83
+
84
+
85
+ def make_executor_row(
86
+ request: dict[str, Any],
87
+ *,
88
+ prompt: str,
89
+ variant: str,
90
+ original_row_index: int,
91
+ protocol_version: str = PROTOCOL_VERSION,
92
+ ) -> dict[str, Any]:
93
+ """Map a V9 request to the DiffSynth image-edit row contract."""
94
+ request_id = str(request["request_id"])
95
+ source = request.get("source")
96
+ target = request.get("target")
97
+ if not isinstance(source, dict) or not isinstance(target, dict):
98
+ raise ValueError(f"{request_id}: source/target objects are required")
99
+ input_path = Path(str(source.get("path") or "")).resolve()
100
+ output_path = Path(str(target.get("path") or "")).resolve()
101
+ if not input_path.is_file() or not output_path.is_file():
102
+ raise FileNotFoundError(f"{request_id}: missing source or target image")
103
+ return {
104
+ "algorithm_version": ALGORITHM_VERSION,
105
+ "protocol_version": protocol_version,
106
+ "request_id": request_id,
107
+ "pair_group_id": str(request["pair_group_id"]),
108
+ "split": str(request["split"]),
109
+ "plant_id": str(request["plant_id"]),
110
+ "view": str(request["view"]),
111
+ "actual_interval_days": int(request["actual_interval_days"]),
112
+ **({"prediction_interval_weeks": prediction_interval_weeks(request),
113
+ "time_condition_unit": "weeks"} if protocol_version in WEEKS_PROTOCOLS else {}),
114
+ "executor_variant": variant,
115
+ "image": str(output_path),
116
+ "edit_image": str(input_path),
117
+ "prompt": prompt,
118
+ "input_path": str(input_path),
119
+ "output_path": str(output_path),
120
+ "status": "ready",
121
+ "error": None,
122
+ "retry_count": 0,
123
+ "original_row_index": original_row_index,
124
+ }
src/wgsr_v9/executor_training_runner.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train Qwen Image 2.1 full DiT on validated DiffSynth latent caches."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import ast
8
+ from contextlib import nullcontext
9
+ import importlib.util
10
+ import json
11
+ import math
12
+ from pathlib import Path
13
+ import sys
14
+ import time
15
+ from typing import Any
16
+
17
+ import accelerate
18
+ from accelerate.utils import set_seed
19
+ import torch
20
+ from tqdm import tqdm
21
+
22
+ REPO_ROOT = Path(__file__).resolve().parents[2]
23
+
24
+ from wgsr_v9.diffsynth_batching import LayoutBatchSampler, collate_cached # noqa: E402
25
+ from wgsr_v9.executor_lr import LearningRateSchedule, step_learning_rate # noqa: E402
26
+ from wgsr_v9.executor_training import ALGORITHM_VERSION # noqa: E402
27
+ from wgsr_v9.io import append_jsonl, sha256_path, write_json # noqa: E402
28
+
29
+
30
+ def _batch_key_from_index_item(item: dict[str, Any]) -> str:
31
+ """Read the batching key, with compatibility for pre-padding indexes.
32
+
33
+ Older ``layout_index.json`` files only contain ``layout_key``. Their
34
+ first two tuple entries are the target and source latent geometries, so a
35
+ geometry-only fallback still lets the new collator pad prompt sequences.
36
+ The collator performs the exact image-mask alignment check after loading
37
+ each batch.
38
+ """
39
+
40
+ batch_key = item.get("batch_layout_key")
41
+ if isinstance(batch_key, str) and batch_key:
42
+ return batch_key
43
+ layout = item.get("layout_key")
44
+ if not isinstance(layout, str):
45
+ raise ValueError("cache index item is missing layout_key/batch_layout_key")
46
+ try:
47
+ parsed = ast.literal_eval(layout)
48
+ except (SyntaxError, ValueError) as exc:
49
+ raise ValueError(f"invalid layout_key in cache index: {layout!r}") from exc
50
+ if not isinstance(parsed, tuple) or len(parsed) < 2:
51
+ raise ValueError(f"invalid layout_key in cache index: {layout!r}")
52
+ return repr((parsed[0], parsed[1]))
53
+
54
+
55
+ def _load_upstream_train(repository: Path) -> Any:
56
+ train_path = repository / "examples/qwen_image_21/model_training/train.py"
57
+ if not train_path.is_file():
58
+ raise FileNotFoundError(train_path)
59
+ sys.path.insert(0, str(repository))
60
+ spec = importlib.util.spec_from_file_location("wgsr_v9_upstream_qwen_image21_train", train_path)
61
+ if spec is None or spec.loader is None:
62
+ raise ImportError(f"could not load DiffSynth training module from {train_path}")
63
+ module = importlib.util.module_from_spec(spec)
64
+ spec.loader.exec_module(module)
65
+ return module
66
+
67
+
68
+ def main() -> int:
69
+ bootstrap = argparse.ArgumentParser(add_help=False)
70
+ bootstrap.add_argument("--diffsynth-repo", type=Path, required=True)
71
+ bootstrap_args, remaining = bootstrap.parse_known_args()
72
+ upstream = _load_upstream_train(bootstrap_args.diffsynth_repo.resolve())
73
+ from diffsynth.diffusion.runner import (
74
+ initialize_deepspeed_gradient_checkpointing,
75
+ save_training_args,
76
+ )
77
+ parser = upstream.qwen_image_21_parser()
78
+ parser.add_argument("--diffsynth-repo", type=Path, default=bootstrap_args.diffsynth_repo)
79
+ parser.add_argument("--layout-index", type=Path, required=True)
80
+ parser.add_argument("--variant", choices=("simple", "teacher_cot"), required=True)
81
+ parser.add_argument("--batch-size", type=int, default=2)
82
+ parser.add_argument("--expected-world-size", type=int, default=8)
83
+ parser.add_argument("--expected-global-batch-size", type=int, default=16)
84
+ parser.add_argument("--seed", type=int, default=20261030)
85
+ parser.add_argument("--max-optimizer-steps", type=int, default=None)
86
+ parser.add_argument("--lr-scheduler", choices=("legacy_constant", "warmup_stable_cosine"),
87
+ default="legacy_constant")
88
+ parser.add_argument("--lr-warmup-ratio", type=float, default=0.1)
89
+ parser.add_argument("--lr-cosine-ratio", type=float, default=0.3)
90
+ parser.add_argument("--lr-warmup-start-factor", type=float, default=0.0)
91
+ parser.add_argument("--lr-min-factor", type=float, default=0.1)
92
+ parser.add_argument("--condition-dropout-cache", type=Path, default=None)
93
+ parser.add_argument("--condition-dropout-seed", type=int, default=20261107)
94
+ parser.add_argument("--condition-ablation-cache", type=Path, default=None)
95
+ parser.add_argument("--condition-ablation", choices=("no_metric_stage", "no_image"))
96
+ args = parser.parse_args(remaining)
97
+ if (args.condition_ablation_cache is None) != (args.condition_ablation is None):
98
+ raise ValueError("fixed ablation mode/cache must be specified together")
99
+ if args.condition_ablation is not None and (
100
+ args.condition_dropout_cache is not None
101
+ or args.variant != "teacher_cot" or args.dataset_num_workers != 0
102
+ ):
103
+ raise ValueError("fixed ablations require text Executor, no random dropout, and zero dataset workers")
104
+ lr_schedule = LearningRateSchedule(
105
+ name=args.lr_scheduler, warmup_ratio=args.lr_warmup_ratio,
106
+ cosine_ratio=args.lr_cosine_ratio, warmup_start_factor=args.lr_warmup_start_factor,
107
+ min_lr_factor=args.lr_min_factor,
108
+ )
109
+
110
+ if args.dataset_metadata_path is not None or args.dataset_repeat != 1:
111
+ raise ValueError("cached SFT requires no metadata file and dataset_repeat=1")
112
+ if args.batch_size != 2 or args.gradient_accumulation_steps != 1:
113
+ raise ValueError("reviewed recipe requires per-GPU batch 2 and gradient accumulation 1")
114
+ if args.max_optimizer_steps is not None and args.max_optimizer_steps <= 0:
115
+ raise ValueError("--max-optimizer-steps must be positive")
116
+ if args.num_epochs <= 0 or not math.isfinite(args.learning_rate) or args.learning_rate <= 0:
117
+ raise ValueError("num_epochs and learning_rate must be positive and finite")
118
+ if args.condition_dropout_cache is not None:
119
+ if args.variant != "teacher_cot" or args.dataset_num_workers != 0:
120
+ raise ValueError("condition dropout v1 requires teacher_cot and dataset_num_workers=0")
121
+
122
+ accelerator = accelerate.Accelerator(
123
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
124
+ # Default AcceleratedScheduler advances num_processes times per call.
125
+ # The new schedule is already expressed in global optimizer updates.
126
+ step_scheduler_with_optimizer=not lr_schedule.manual_step,
127
+ kwargs_handlers=[
128
+ accelerate.DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)
129
+ ],
130
+ )
131
+ expected_global_batch = args.batch_size * accelerator.num_processes * args.gradient_accumulation_steps
132
+ if expected_global_batch != args.expected_global_batch_size or accelerator.num_processes != args.expected_world_size:
133
+ raise ValueError(
134
+ f"reviewed global batch is {args.expected_global_batch_size} on {args.expected_world_size} ranks; "
135
+ f"got batch={args.batch_size}, ranks={accelerator.num_processes}, "
136
+ f"accumulation={args.gradient_accumulation_steps}"
137
+ )
138
+ if accelerator.state.deepspeed_plugin is None:
139
+ raise RuntimeError("training must use the reviewed DeepSpeed ZeRO-3 Accelerate config")
140
+ ds_config = accelerator.state.deepspeed_plugin.deepspeed_config
141
+ if lr_schedule.manual_step and "scheduler" in ds_config:
142
+ raise ValueError("executor LR schedule cannot be combined with a DeepSpeed-config scheduler")
143
+ ds_config["train_micro_batch_size_per_gpu"] = args.batch_size
144
+ ds_config["gradient_accumulation_steps"] = args.gradient_accumulation_steps
145
+ ds_config["train_batch_size"] = expected_global_batch
146
+ if ds_config.get("zero_optimization", {}).get("stage") != 3:
147
+ raise RuntimeError("training config must use DeepSpeed ZeRO-3")
148
+ if ds_config.get("zero_optimization", {}).get("offload_optimizer", {}).get("device", "none") != "none":
149
+ raise RuntimeError("CPU optimizer offload is outside the reviewed recipe")
150
+ if ds_config.get("zero_optimization", {}).get("offload_param", {}).get("device", "none") != "none":
151
+ raise RuntimeError("CPU parameter offload is outside the reviewed recipe")
152
+
153
+ set_seed(args.seed, device_specific=True)
154
+ cache_root = Path(args.dataset_base_path).resolve()
155
+ layout_path = Path(args.layout_index).resolve()
156
+ index = json.loads(layout_path.read_text(encoding="utf-8"))
157
+ if index.get("status") != "complete" or not index.get("all_condition_and_target_tensors_finite"):
158
+ raise ValueError("cache index is incomplete or reports nonfinite training tensors")
159
+ dataset = upstream.UnifiedDataset(base_path=str(cache_root), repeat=1)
160
+ if len(dataset) != index["count"]:
161
+ raise ValueError(f"cache Dataset count {len(dataset)} does not match index {index['count']}")
162
+ cached_paths = [str(Path(path).resolve()) for path in dataset.cached_data]
163
+ indexed_paths = [item["output_path"] for item in index["items"]]
164
+ if set(cached_paths) != set(indexed_paths):
165
+ raise ValueError("DiffSynth cache files do not match the validated cache index")
166
+ key_by_path = {item["output_path"]: _batch_key_from_index_item(item) for item in index["items"]}
167
+ batch_sampler = LayoutBatchSampler(
168
+ [key_by_path[path] for path in cached_paths],
169
+ args.batch_size,
170
+ accelerator.num_processes,
171
+ seed=args.seed,
172
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
173
+ )
174
+ microbatches_per_rank = len(batch_sampler) // accelerator.num_processes
175
+ updates_per_epoch = microbatches_per_rank // args.gradient_accumulation_steps
176
+ total_optimizer_steps = updates_per_epoch * args.num_epochs
177
+ if args.max_optimizer_steps is not None:
178
+ total_optimizer_steps = min(total_optimizer_steps, args.max_optimizer_steps)
179
+ lr_schedule_plan = lr_schedule.resolve(total_optimizer_steps)
180
+ dropout_manifest = None
181
+ if args.condition_dropout_cache is not None:
182
+ from wgsr_v9.executor_dropout import DropoutBatchSampler, DropoutCachedDataset, action_summary, stream_seed
183
+ dataset = DropoutCachedDataset(dataset, index, args.condition_dropout_cache,
184
+ seed=args.condition_dropout_seed, epochs=args.num_epochs)
185
+ dropout_manifest = dataset.manifest
186
+ if dropout_manifest["training_seed"] != args.seed or dropout_manifest["world_size"] != accelerator.num_processes:
187
+ raise ValueError("dropout cache was planned with a different training seed/world size")
188
+ if dropout_manifest["input_sha256"].get(str(layout_path)) != sha256_path(layout_path):
189
+ raise ValueError("dropout layout index changed")
190
+ batch_sampler = DropoutBatchSampler(batch_sampler, seed=args.condition_dropout_seed)
191
+ ablation_manifest = None
192
+ if args.condition_ablation is not None:
193
+ from wgsr_v9.executor_ablation import AblationBatchSampler, AblationCachedDataset
194
+ dataset = AblationCachedDataset(dataset, index, args.condition_ablation_cache, args.condition_ablation)
195
+ ablation_manifest = dataset.manifest
196
+ if ablation_manifest["input_sha256"].get(str(layout_path)) != sha256_path(layout_path):
197
+ raise ValueError("fixed ablation layout index changed")
198
+ batch_sampler = AblationBatchSampler(batch_sampler, args.condition_ablation)
199
+ dataloader = torch.utils.data.DataLoader(
200
+ dataset,
201
+ batch_sampler=batch_sampler,
202
+ collate_fn=collate_cached,
203
+ num_workers=args.dataset_num_workers,
204
+ )
205
+ model = upstream.QwenImage21TrainingModule(
206
+ model_paths=args.model_paths,
207
+ processor_path=args.processor_path,
208
+ trainable_models="dit",
209
+ use_gradient_checkpointing=True,
210
+ use_gradient_checkpointing_offload=args.use_gradient_checkpointing_offload,
211
+ task="sft:train",
212
+ device="cpu",
213
+ )
214
+ optimizer = torch.optim.AdamW(
215
+ model.trainable_modules(), lr=args.learning_rate, weight_decay=args.weight_decay
216
+ )
217
+ peak_learning_rates = [group["lr"] for group in optimizer.param_groups]
218
+ scheduler = lr_schedule.build(optimizer, total_optimizer_steps)
219
+ lr_schedule_plan["peak_learning_rates"] = peak_learning_rates
220
+ lr_schedule_plan["initial_learning_rates"] = scheduler.get_last_lr()
221
+ output = Path(args.output_path).resolve()
222
+ if accelerator.is_main_process:
223
+ if output.exists() and any(output.iterdir()):
224
+ raise FileExistsError(f"checkpoint output directory is not empty: {output}")
225
+ output.mkdir(parents=True, exist_ok=True)
226
+ accelerator.wait_for_everyone()
227
+ logger = upstream.ModelLogger(output, remove_prefix_in_ckpt=args.remove_prefix_in_ckpt, enable_csv_log=True)
228
+ if accelerator.is_main_process:
229
+ save_training_args(args)
230
+ global_microbatches = microbatches_per_rank * accelerator.num_processes
231
+ sample_visits_per_epoch = global_microbatches * args.batch_size
232
+ batch_plan = {
233
+ "algorithm_version": ALGORITHM_VERSION,
234
+ "executor_variant": args.variant,
235
+ "input_path": str(layout_path),
236
+ "output_path": str(output),
237
+ "original_unique_samples": len(dataset),
238
+ "sample_visits_per_epoch": sample_visits_per_epoch,
239
+ "sample_visits_per_rank_per_epoch": microbatches_per_rank * args.batch_size,
240
+ "padding_repeated_visits_per_epoch": sample_visits_per_epoch - len(dataset),
241
+ "microbatches_per_rank_per_epoch": microbatches_per_rank,
242
+ "optimizer_updates_per_epoch": (
243
+ microbatches_per_rank // args.gradient_accumulation_steps
244
+ ),
245
+ "per_gpu_batch_size": args.batch_size,
246
+ "gradient_accumulation_steps": args.gradient_accumulation_steps,
247
+ "global_batch_size": expected_global_batch,
248
+ "epochs": args.num_epochs,
249
+ "lr_scheduler": lr_schedule_plan,
250
+ "seed": args.seed,
251
+ "image_dropout": 0.1 if dropout_manifest is not None else 0.0,
252
+ "condition_dropout": None if dropout_manifest is None else {
253
+ "plan_sha256": dropout_manifest["plan_sha256"], "policy": dropout_manifest["policy"],
254
+ "action_schedule": action_summary(updates_per_epoch, args.condition_dropout_seed, args.num_epochs)},
255
+ "validation_during_training": False,
256
+ "condition_ablation": None if ablation_manifest is None else {
257
+ "algorithm_version": ablation_manifest["algorithm_version"],
258
+ "mode": args.condition_ablation,
259
+ "manifest_sha256": sha256_path(args.condition_ablation_cache / "manifest.json"),
260
+ "plan_sha256": ablation_manifest["plan_sha256"],
261
+ "flow_rng": "legacy formal text recipe; no change to RNG consumption in dataset/sampler"},
262
+ "training_implementation": (
263
+ f"upstream Qwen Image 2.1 module, DiT, FlowMatchSFTLoss, AdamW; LR={lr_schedule.name}; "
264
+ "homogeneous image-layout batches with tail-padded prompt embeddings and attention masks"
265
+ ),
266
+ "batch_layout_groups": len(batch_sampler.groups),
267
+ "prompt_sequence_padding": "tail_padding_with_prompt_embeds_mask",
268
+ "status": "ready",
269
+ "error": None,
270
+ "retry_count": 0,
271
+ }
272
+ write_json(output / "batch_plan.json", batch_plan)
273
+ print("BATCH_PLAN", json.dumps(batch_plan), flush=True)
274
+
275
+ model.to(device=accelerator.device)
276
+ model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
277
+ if lr_schedule.manual_step and (
278
+ getattr(scheduler, "step_with_optimizer", True)
279
+ or getattr(model, "lr_scheduler", None) is not None
280
+ ):
281
+ raise RuntimeError("executor LR scheduler must be stepped manually once per successful update")
282
+ initialize_deepspeed_gradient_checkpointing(accelerator)
283
+ torch.cuda.reset_peak_memory_stats(accelerator.device)
284
+ global_step = 0
285
+ successful_optimizer_steps = 0
286
+ accumulated_losses: list[float] = []
287
+ accumulated_shapes: list[list[int]] = []
288
+ metrics_file = (output / "optimizer_metrics.jsonl").open("a", encoding="utf-8") if accelerator.is_main_process else None
289
+ started = time.monotonic()
290
+ try:
291
+ for epoch in range(args.num_epochs):
292
+ batch_sampler.set_epoch(epoch)
293
+ if hasattr(dataloader, "set_epoch"):
294
+ dataloader.set_epoch(epoch)
295
+ for microstep, inputs in enumerate(tqdm(dataloader, disable=not accelerator.is_main_process), 1):
296
+ with accelerator.accumulate(model):
297
+ dropout = inputs[0].pop("condition_dropout", None)
298
+ ablation = inputs[0].pop("condition_ablation", None)
299
+ if ablation_manifest is not None:
300
+ if ablation is None or (ablation["epoch"], ablation["step"], ablation["action"]) != (
301
+ epoch, microstep - 1, args.condition_ablation
302
+ ):
303
+ raise ValueError("fixed ablation batch lost alignment")
304
+ append_jsonl(output / f"ablation-rank-{accelerator.process_index}.jsonl", {
305
+ "algorithm_version": ablation_manifest["algorithm_version"],
306
+ "input_path": str(args.condition_ablation_cache), "output_path": str(output),
307
+ "rank": accelerator.process_index, **ablation,
308
+ "status": "ready", "error": None, "retry_count": 0})
309
+ if dropout_manifest is not None:
310
+ if dropout is None or dropout["epoch"] != epoch or dropout["step"] != microstep - 1:
311
+ raise ValueError("dropout action tape lost alignment after distributed sharding")
312
+ append_jsonl(output / f"dropout-rank-{accelerator.process_index}.jsonl", {
313
+ "algorithm_version": dropout_manifest["algorithm_version"],
314
+ "input_path": str(args.condition_dropout_cache), "output_path": str(output),
315
+ "rank": accelerator.process_index, **dropout,
316
+ "status": "ready", "error": None, "retry_count": 0})
317
+ actual_batch = int(inputs[0]["input_latents"].shape[0])
318
+ if actual_batch != args.batch_size:
319
+ raise ValueError(f"expected tensor batch {args.batch_size}, got {actual_batch}")
320
+ accumulated_shapes.append(list(inputs[0]["input_latents"].shape))
321
+ deepspeed_steps_before = model.global_steps
322
+ learning_rates_used = [group["lr"] for group in optimizer.param_groups]
323
+ # Preserve the dropout experiment's isolated flow-noise/time random stream.
324
+ rng_context = (torch.random.fork_rng(devices=[accelerator.device.index])
325
+ if dropout_manifest is not None else nullcontext())
326
+ with rng_context:
327
+ if dropout_manifest is not None:
328
+ torch.manual_seed(stream_seed(args.seed, "flow", epoch, microstep, accelerator.process_index))
329
+ loss = model({}, inputs=inputs)
330
+ global_loss = accelerator.reduce(loss.detach().float(), reduction="mean")
331
+ if not bool(torch.isfinite(global_loss)):
332
+ raise FloatingPointError(f"nonfinite loss at epoch={epoch + 1}, microstep={microstep}")
333
+ accumulated_losses.append(float(global_loss))
334
+ accelerator.backward(loss)
335
+ optimizer.step()
336
+ step_learning_rate(
337
+ scheduler, manual_step=lr_schedule.manual_step,
338
+ sync_gradients=accelerator.sync_gradients,
339
+ optimizer_step_was_skipped=optimizer.step_was_skipped,
340
+ )
341
+ optimizer.zero_grad()
342
+ if model.global_steps != deepspeed_steps_before + int(accelerator.sync_gradients):
343
+ raise RuntimeError("DeepSpeed optimizer step did not match the accumulation boundary")
344
+ logger.on_step_end(accelerator, model, loss=loss)
345
+ if accelerator.sync_gradients:
346
+ global_step += 1
347
+ successful_optimizer_steps += int(not optimizer.step_was_skipped)
348
+ grad_norm = accelerator.deepspeed_engine_wrapped.get_global_grad_norm()
349
+ if grad_norm is not None and not math.isfinite(float(grad_norm)):
350
+ raise FloatingPointError(f"nonfinite gradient norm at optimizer step {global_step}")
351
+ if accelerator.is_main_process:
352
+ record = {
353
+ "algorithm_version": ALGORITHM_VERSION,
354
+ "executor_variant": args.variant,
355
+ "input_path": str(layout_path),
356
+ "output_path": str(output / "optimizer_metrics.jsonl"),
357
+ "optimizer_step": global_step,
358
+ "successful_optimizer_steps": successful_optimizer_steps,
359
+ "optimizer_step_was_skipped": optimizer.step_was_skipped,
360
+ "epoch": epoch + 1,
361
+ "microstep_in_epoch": microstep,
362
+ "loss_global_mean": sum(accumulated_losses) / len(accumulated_losses),
363
+ "gradient_norm": None if grad_norm is None else float(grad_norm),
364
+ "learning_rate": optimizer.param_groups[0]["lr"],
365
+ "learning_rate_used": learning_rates_used[0],
366
+ "learning_rates_used": learning_rates_used,
367
+ "learning_rates_next": [group["lr"] for group in optimizer.param_groups],
368
+ "condition_dropout": dropout,
369
+ "condition_ablation": ablation,
370
+ "numeric_diagnostics": {}, # Preserve the text-run log schema.
371
+ "per_gpu_batch_size": args.batch_size,
372
+ "gradient_accumulation_steps": args.gradient_accumulation_steps,
373
+ "global_batch_size": expected_global_batch,
374
+ "elapsed_seconds": time.monotonic() - started,
375
+ "deepspeed_global_steps": model.global_steps,
376
+ "input_latent_shapes": accumulated_shapes,
377
+ "peak_allocated_bytes_rank0": torch.cuda.max_memory_allocated(accelerator.device),
378
+ "peak_reserved_bytes_rank0": torch.cuda.max_memory_reserved(accelerator.device),
379
+ "status": "ready",
380
+ "error": None,
381
+ "retry_count": 0,
382
+ }
383
+ metrics_file.write(json.dumps(record) + "\n")
384
+ metrics_file.flush()
385
+ print("OPTIMIZER_STEP", json.dumps(record), flush=True)
386
+ accumulated_losses = []
387
+ accumulated_shapes = []
388
+ if args.max_optimizer_steps is not None and global_step >= args.max_optimizer_steps:
389
+ break
390
+ logger.on_epoch_end(accelerator, model, epoch)
391
+ if args.max_optimizer_steps is not None and global_step >= args.max_optimizer_steps:
392
+ break
393
+ logger.on_training_end(accelerator, model)
394
+ if accelerator.is_main_process:
395
+ write_json(
396
+ output / "completed.json",
397
+ {
398
+ "algorithm_version": ALGORITHM_VERSION,
399
+ "executor_variant": args.variant,
400
+ "input_path": str(layout_path),
401
+ "output_path": str(output),
402
+ "optimizer_steps": global_step,
403
+ "successful_optimizer_steps": successful_optimizer_steps,
404
+ "lr_scheduler": lr_schedule_plan,
405
+ "final_learning_rates": [group["lr"] for group in optimizer.param_groups],
406
+ "seconds": time.monotonic() - started,
407
+ "status": "complete",
408
+ "error": None,
409
+ "retry_count": 0,
410
+ },
411
+ )
412
+ finally:
413
+ if metrics_file is not None:
414
+ metrics_file.close()
415
+ accelerator.wait_for_everyone()
416
+ return 0
417
+
418
+
419
+ if __name__ == "__main__":
420
+ raise SystemExit(main())
src/wgsr_v9/image_geometry_evaluation.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image-result height and density using the existing CoT geometry contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+ from .v9_image_metrics import _measure_geometry, foreground_mask, normalize_view
12
+
13
+
14
+ ALGORITHM_VERSION = "wgsr_v9_image_height_density_augmentation_v1"
15
+ PROTOCOL_VERSION = "wgsr_v9_image_height_density_v1"
16
+ METRICS = (
17
+ "target_front_height_pct",
18
+ "prediction_front_height_pct",
19
+ "front_height_abs_error_pp",
20
+ "target_projection_density_fraction",
21
+ "prediction_projection_density_fraction",
22
+ "projection_density_abs_error_pp",
23
+ )
24
+
25
+
26
+ def measure_geometry_mask(mask: np.ndarray, view: str) -> dict[str, Any]:
27
+ """Reuse CoT's pixel-center convex hull and bottom-anchored front height."""
28
+ view = normalize_view(view)
29
+ geometry = _measure_geometry(mask, view)
30
+ values = geometry["metrics"]
31
+ density_key = "plant_density" if view == "front" else "canopy"
32
+ top, bottom = geometry["top_row"], geometry["bottom_row"]
33
+ return {
34
+ "normalized_view": view,
35
+ "front_height_pct": values.get("culm"),
36
+ "projection_density_fraction": values[density_key],
37
+ "height_metric_status": (
38
+ geometry["metric_status"]["culm"] if view == "front" else "not_applicable"
39
+ ),
40
+ "height_reason_codes": (
41
+ geometry["metric_reason_codes"]["culm"] if view == "front" else ["top_view"]
42
+ ),
43
+ "density_metric_status": geometry["metric_status"][density_key],
44
+ "density_reason_codes": geometry["metric_reason_codes"][density_key],
45
+ "foreground_area_pct": values["leaves_area"],
46
+ "visible_extent_y_pct": (
47
+ None if top is None else 100.0 * (bottom - top + 1) / mask.shape[0]
48
+ ),
49
+ **{key: geometry[key] for key in (
50
+ "visible_foreground_pixels", "convex_hull_area_pixels", "top_row", "bottom_row",
51
+ "bottom_gap_pct", "touches_image_boundary", "measurement_status",
52
+ )},
53
+ }
54
+
55
+
56
+ def measure_geometry_image(path: Path, view: str) -> dict[str, Any]:
57
+ """Match the pixel evaluator's white alpha compositing and foreground mask."""
58
+ with Image.open(path) as image:
59
+ if "A" in image.getbands():
60
+ rgba = image.convert("RGBA")
61
+ background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
62
+ image = Image.alpha_composite(background, rgba)
63
+ rgb = np.asarray(image.convert("RGB"), dtype=np.uint8)
64
+ return {
65
+ "image_width": int(rgb.shape[1]),
66
+ "image_height": int(rgb.shape[0]),
67
+ **measure_geometry_mask(foreground_mask(rgb), view),
68
+ }
69
+
70
+
71
+ def compare_geometry(target: dict[str, Any], prediction: dict[str, Any]) -> dict[str, Any]:
72
+ if target["normalized_view"] != prediction["normalized_view"]:
73
+ raise ValueError("target and prediction geometry views differ")
74
+ output: dict[str, Any] = {}
75
+ for name, field, multiplier in (
76
+ ("height", "front_height_pct", 1.0),
77
+ ("density", "projection_density_fraction", 100.0),
78
+ ):
79
+ left, right = target[field], prediction[field]
80
+ error_field = "front_height_abs_error_pp" if name == "height" else "projection_density_abs_error_pp"
81
+ output[f"target_{field}"] = left
82
+ output[f"prediction_{field}"] = right
83
+ output[error_field] = None if left is None or right is None else multiplier * abs(left - right)
84
+ reasons = [
85
+ f"{side}:{reason}"
86
+ for side, geometry in (("target", target), ("prediction", prediction))
87
+ for reason in geometry[f"{name}_reason_codes"]
88
+ ]
89
+ output[f"{name}_metric_status"] = (
90
+ "available" if not reasons else
91
+ "not_applicable" if name == "height" and target["normalized_view"] == "top" else "unavailable"
92
+ )
93
+ output[f"{name}_reason_codes"] = reasons
94
+ return output
src/wgsr_v9/planner_adapter.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert a trained planner completion to the image-executor interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+
10
+ _THINK_RE = re.compile(r"^\s*<think>\s*(?P<body>.*?)\s*</think>\s*$", re.DOTALL)
11
+ _GROWTH_RE = re.compile(r"^\s*<GROWTH_COT>\s*(?P<body>.*?)\s*</GROWTH_COT>\s*$", re.DOTALL)
12
+
13
+
14
+ def _completion_text(completion: str | Mapping[str, Any]) -> str:
15
+ if isinstance(completion, str):
16
+ return completion
17
+ if not isinstance(completion, Mapping):
18
+ raise TypeError("planner completion must be text or a mapping")
19
+ for key in ("reasoning_content", "content", "text"):
20
+ value = completion.get(key)
21
+ if isinstance(value, str) and value.strip():
22
+ return value
23
+ raise ValueError("planner completion has no non-empty reasoning_content, content, or text")
24
+
25
+
26
+ def growth_cot_body(completion: str | Mapping[str, Any]) -> str:
27
+ """Extract one planner ``<think>`` body for downstream adaptation.
28
+
29
+ A completion that is already in the executor format is accepted for
30
+ resumable export. Nested or empty wrappers are rejected so an accidental
31
+ model preamble cannot be silently sent to the image executor.
32
+ """
33
+
34
+ text = _completion_text(completion).strip()
35
+ growth_match = _GROWTH_RE.fullmatch(text)
36
+ if growth_match is not None:
37
+ body = growth_match.group("body").strip()
38
+ else:
39
+ think_match = _THINK_RE.fullmatch(text)
40
+ if think_match is None:
41
+ raise ValueError("planner completion must contain exactly one <think>...</think> block")
42
+ body = think_match.group("body").strip()
43
+ if not body:
44
+ raise ValueError("planner completion body is empty")
45
+ if "<think>" in body or "</think>" in body or "<GROWTH_COT>" in body or "</GROWTH_COT>" in body:
46
+ raise ValueError("planner completion contains nested reasoning or executor wrappers")
47
+ return body
48
+
49
+
50
+ def to_growth_cot(completion: str | Mapping[str, Any]) -> str:
51
+ """Wrap a planner completion for the Qwen Image executor."""
52
+
53
+ return f"<GROWTH_COT>\n{growth_cot_body(completion)}\n</GROWTH_COT>"
tests/__init__.py ADDED
File without changes
tests/test_dino_checkpoint.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ import sys
5
+ import unittest
6
+
7
+ import torch
8
+ from timm.models.vision_transformer import VisionTransformer
9
+ from transformers import Dinov2Config, Dinov2Model
10
+
11
+ ROOT = Path(__file__).resolve().parents[1]
12
+ sys.path.insert(0, str(ROOT / "src"))
13
+
14
+ from wgsr_v9.dino_checkpoint import hf_dinov2_to_timm
15
+
16
+
17
+ class DinoCheckpointTests(unittest.TestCase):
18
+ def setUp(self) -> None:
19
+ torch.manual_seed(41)
20
+ self.hf = Dinov2Model(Dinov2Config(
21
+ image_size=28, patch_size=14, hidden_size=32,
22
+ num_hidden_layers=2, num_attention_heads=4, mlp_ratio=2,
23
+ )).eval()
24
+
25
+ def test_converted_encoder_matches_huggingface_cls_on_identical_input(self) -> None:
26
+ model = VisionTransformer(
27
+ img_size=28, patch_size=14, embed_dim=32, depth=2,
28
+ num_heads=4, mlp_ratio=2, qkv_bias=True, init_values=1.0,
29
+ num_classes=0,
30
+ ).eval()
31
+ inputs = torch.randn(3, 3, 28, 28)
32
+ with torch.inference_mode():
33
+ expected = self.hf(inputs).last_hidden_state[:, 0]
34
+ legacy = {}
35
+ for key, value in self.hf.state_dict().items():
36
+ for current, old in (("q_proj", "attention.query"), ("k_proj", "attention.key"),
37
+ ("v_proj", "attention.value"), ("o_proj", "output.dense")):
38
+ key = key.replace(f"attention.{current}.", f"attention.{old}.")
39
+ legacy[key] = value
40
+ for state in (self.hf.state_dict(), legacy):
41
+ model.load_state_dict(hf_dinov2_to_timm(state), strict=True)
42
+ with torch.inference_mode():
43
+ actual = model.forward_head(model.forward_features(inputs), pre_logits=True)
44
+ torch.testing.assert_close(actual, expected, rtol=1e-5, atol=2e-6)
45
+
46
+ def test_rejects_unsupported_or_missing_source_weights(self) -> None:
47
+ state = dict(self.hf.state_dict())
48
+ state["unknown_tensor"] = torch.zeros(1)
49
+ with self.assertRaisesRegex(ValueError, "unsupported"):
50
+ hf_dinov2_to_timm(state)
51
+ del state["unknown_tensor"]
52
+ key = next(key for key in state if key.endswith(("attention.key.weight", "attention.k_proj.weight")))
53
+ del state[key]
54
+ with self.assertRaises(KeyError):
55
+ hf_dinov2_to_timm(state)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ unittest.main()
tests/test_evaluation_io.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import unittest
5
+ from pathlib import Path
6
+
7
+ ROOT = Path(__file__).resolve().parents[1]
8
+ sys.path.insert(0, str(ROOT / "src"))
9
+
10
+ from wgsr_v9.evaluation_io import pair_key_for_dataset_row # noqa: E402
11
+
12
+
13
+ class EvaluationAlignmentTests(unittest.TestCase):
14
+ def test_executor_request_id_aligns_to_dataset_pair_id(self) -> None:
15
+ dataset_row = {"pair_id": "plant_a_2020-01-01_to_2020-01-08_side0"}
16
+ executor_result = {
17
+ "request_id": "plant_a_2020-01-01_to_2020-01-08_side0",
18
+ "row_index": 12,
19
+ }
20
+ self.assertEqual(
21
+ pair_key_for_dataset_row(dataset_row),
22
+ pair_key_for_dataset_row(executor_result),
23
+ )
24
+
25
+
26
+ if __name__ == "__main__":
27
+ unittest.main()
tests/test_executor_training.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ import torch
9
+
10
+ REPO_ROOT = Path(__file__).resolve().parents[1]
11
+ sys.path.insert(0, str(REPO_ROOT / "src"))
12
+
13
+ from wgsr_v9.diffsynth_batching import LayoutBatchSampler, collate_cached # noqa: E402
14
+ from wgsr_v9.executor_training import ( # noqa: E402
15
+ ALGORITHM_VERSION,
16
+ PROTOCOL_VERSION,
17
+ WEEKS_PROTOCOL_VERSION,
18
+ executor_prompt,
19
+ growth_cot_body,
20
+ make_executor_row,
21
+ prediction_interval_weeks,
22
+ )
23
+
24
+
25
+ PROMPT_TEMPLATE = "Source {accession_id}; {view_label}; {interval_weeks} weeks ({interval_days} days)."
26
+ COT_SUFFIX = "\n<GROWTH_COT>\n{growth_cot}\n</GROWTH_COT>"
27
+
28
+
29
+ def _request(root: Path) -> dict[str, object]:
30
+ source = root / "source.png"
31
+ target = root / "target.png"
32
+ source.touch()
33
+ target.touch()
34
+ return {
35
+ "request_id": "req-1",
36
+ "pair_group_id": "pair-1",
37
+ "split": "train",
38
+ "plant_id": "plant-1",
39
+ "view": "front",
40
+ "accession_id": "R0001",
41
+ "actual_interval_days": 8,
42
+ "source": {"path": str(source)},
43
+ "target": {"path": str(target)},
44
+ }
45
+
46
+
47
+ class ExecutorPromptTests(unittest.TestCase):
48
+ def test_weeks_protocol_rounding_and_legacy_compatibility(self) -> None:
49
+ template = "Source {accession_id}; {view_label}; Prediction interval: {interval_weeks} weeks."
50
+ with tempfile.TemporaryDirectory() as temporary:
51
+ request = _request(Path(temporary))
52
+ for days, expected in ((4, 1), (8, 1), (10, 1), (11, 2), (29, 4), (57, 8), (71, 10), (140, 20)):
53
+ request["actual_interval_days"] = days
54
+ self.assertEqual(prediction_interval_weeks(request), expected)
55
+ prompt = executor_prompt(request, prompt_template=template, cot_suffix=COT_SUFFIX,
56
+ variant="teacher_cot", teacher_cot="Original CoT.",
57
+ protocol_version=WEEKS_PROTOCOL_VERSION)
58
+ self.assertIn(f"Prediction interval: {expected} weeks.", prompt)
59
+ self.assertNotIn("days", prompt)
60
+ self.assertTrue(prompt.endswith("Original CoT.\n</GROWTH_COT>"))
61
+ row = make_executor_row(request, prompt=prompt, variant="teacher_cot",
62
+ original_row_index=0, protocol_version=WEEKS_PROTOCOL_VERSION)
63
+ self.assertEqual(row["actual_interval_days"], days)
64
+ self.assertEqual(row["prediction_interval_weeks"], expected)
65
+ self.assertEqual(row["time_condition_unit"], "weeks")
66
+ request.update(actual_interval_days=71, prediction_interval_weeks=11)
67
+ with self.assertRaises(ValueError):
68
+ prediction_interval_weeks(request)
69
+ request["prediction_interval_weeks"] = 10
70
+ with self.assertRaises(ValueError):
71
+ executor_prompt(request, prompt_template=PROMPT_TEMPLATE, cot_suffix=COT_SUFFIX,
72
+ variant="simple", protocol_version=WEEKS_PROTOCOL_VERSION)
73
+
74
+ def test_simple_and_teacher_conditions(self) -> None:
75
+ with tempfile.TemporaryDirectory() as temporary:
76
+ request = _request(Path(temporary))
77
+ simple = executor_prompt(
78
+ request,
79
+ prompt_template=PROMPT_TEMPLATE,
80
+ cot_suffix=COT_SUFFIX,
81
+ variant="simple",
82
+ )
83
+ cot = executor_prompt(
84
+ request,
85
+ prompt_template=PROMPT_TEMPLATE,
86
+ cot_suffix=COT_SUFFIX,
87
+ variant="teacher_cot",
88
+ teacher_cot="Line 1.\nLine 2.",
89
+ )
90
+ self.assertEqual(simple, "Source R0001; front view; 2 weeks (8 days).")
91
+ self.assertNotIn("GROWTH_COT", simple)
92
+ self.assertTrue(cot.endswith("<GROWTH_COT>\nLine 1.\nLine 2.\n</GROWTH_COT>"))
93
+
94
+ def test_rejects_bad_wrapper_and_simple_cot(self) -> None:
95
+ with self.assertRaises(ValueError):
96
+ growth_cot_body("not wrapped", "req-1")
97
+ with self.assertRaises(ValueError):
98
+ growth_cot_body("<GROWTH_COT><GROWTH_COT>x</GROWTH_COT></GROWTH_COT>", "req-1")
99
+ with tempfile.TemporaryDirectory() as temporary:
100
+ with self.assertRaises(ValueError):
101
+ executor_prompt(
102
+ _request(Path(temporary)),
103
+ prompt_template=PROMPT_TEMPLATE,
104
+ cot_suffix=COT_SUFFIX,
105
+ variant="simple",
106
+ teacher_cot="should not be present",
107
+ )
108
+
109
+ def test_diff_synth_row_roles_and_audit_fields(self) -> None:
110
+ with tempfile.TemporaryDirectory() as temporary:
111
+ root = Path(temporary)
112
+ request = _request(root)
113
+ row = make_executor_row(
114
+ request,
115
+ prompt="simple prompt",
116
+ variant="simple",
117
+ original_row_index=3,
118
+ )
119
+ self.assertEqual(row["image"], str((root / "target.png").resolve()))
120
+ self.assertEqual(row["edit_image"], str((root / "source.png").resolve()))
121
+ self.assertEqual(row["input_path"], row["edit_image"])
122
+ self.assertEqual(row["output_path"], row["image"])
123
+ self.assertEqual(row["algorithm_version"], ALGORITHM_VERSION)
124
+ self.assertEqual(row["protocol_version"], PROTOCOL_VERSION)
125
+ self.assertEqual((row["status"], row["error"], row["retry_count"]), ("ready", None, 0))
126
+
127
+
128
+ def _cache_row(mask: torch.Tensor, latent_shape: tuple[int, ...] = (1, 64, 56, 42)):
129
+ return (
130
+ {
131
+ "input_latents": torch.ones(latent_shape),
132
+ "edit_latents": [torch.ones(latent_shape) * 2],
133
+ },
134
+ {"prompt_embeds": torch.ones((1, mask.shape[1], 4)), "edit_image_pad_mask": mask},
135
+ {"negative_prompt": ""},
136
+ )
137
+
138
+
139
+ class CachedBatchTests(unittest.TestCase):
140
+ def test_collate_batches_values_without_padding(self) -> None:
141
+ mask = torch.ones((1, 4), dtype=torch.bool)
142
+ rows = [_cache_row(mask), _cache_row(mask)]
143
+ shared, positive, _ = collate_cached(rows)
144
+ self.assertEqual(tuple(shared["input_latents"].shape), (2, 64, 56, 42))
145
+ self.assertEqual(tuple(shared["edit_latents"][0].shape), (2, 64, 56, 42))
146
+ self.assertEqual(tuple(positive["prompt_embeds"].shape), (2, 4, 4))
147
+ self.assertEqual(tuple(positive["edit_image_pad_mask"].shape), (1, 4))
148
+
149
+ def test_collate_rejects_mixed_layout(self) -> None:
150
+ with self.assertRaises(ValueError):
151
+ collate_cached(
152
+ [
153
+ _cache_row(torch.ones((1, 4), dtype=torch.bool)),
154
+ _cache_row(torch.tensor([[True, False, True, False]])),
155
+ ]
156
+ )
157
+
158
+ def test_collate_pads_prompt_sequences_and_masks_tail(self) -> None:
159
+ short = _cache_row(torch.tensor([[True, True, True, True, False]], dtype=torch.bool))
160
+ long = _cache_row(torch.tensor([[True, True, True, True, False, False, False]], dtype=torch.bool))
161
+ shared, positive, _ = collate_cached([short, long])
162
+ self.assertEqual(tuple(positive["prompt_embeds"].shape), (2, 7, 4))
163
+ self.assertEqual(tuple(positive["edit_image_pad_mask"].shape), (1, 7))
164
+ self.assertEqual(tuple(positive["prompt_embeds_mask"].shape), (2, 7))
165
+ self.assertTrue(bool(positive["prompt_embeds_mask"][0, :5].all()))
166
+ self.assertFalse(bool(positive["prompt_embeds_mask"][0, 5:].any()))
167
+ self.assertEqual(tuple(shared["input_latents"].shape[:2]), (2, 64))
168
+
169
+ def test_sampler_covers_rows_and_closes_accumulation_windows(self) -> None:
170
+ keys = ["front-short"] * 9 + ["top-long"] * 5
171
+ sampler = LayoutBatchSampler(
172
+ keys,
173
+ batch_size=2,
174
+ world_size=4,
175
+ seed=3,
176
+ gradient_accumulation_steps=2,
177
+ )
178
+ batches = list(sampler)
179
+ self.assertEqual(len(batches) % (4 * 2), 0)
180
+ self.assertTrue(all(len(batch) == 2 for batch in batches))
181
+ self.assertTrue(set(range(len(keys))).issubset({index for batch in batches for index in batch}))
182
+ self.assertTrue(all(len({keys[index] for index in batch}) == 1 for batch in batches))
183
+
184
+
185
+ if __name__ == "__main__":
186
+ unittest.main()
tests/test_image_evaluation_workers.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+
11
+ from PIL import Image, ImageDraw
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT / "src"))
15
+
16
+ from wgsr_v9.io import read_jsonl, write_jsonl
17
+
18
+
19
+ class EvaluationWorkerTests(unittest.TestCase):
20
+ def test_parallel_matches_serial_with_missing_and_invalid_predictions(self) -> None:
21
+ with tempfile.TemporaryDirectory() as directory:
22
+ root = Path(directory)
23
+ source, target = root / "source.png", root / "target.png"
24
+ for path, box in ((source, (8, 8, 18, 35)), (target, (5, 4, 24, 38))):
25
+ image = Image.new("RGB", (32, 48), "white")
26
+ ImageDraw.Draw(image).rectangle(box, fill=(40, 120, 50))
27
+ image.save(path)
28
+ invalid = root / "invalid.png"
29
+ invalid.write_bytes(b"not an image")
30
+ dataset = [{"row_index": i, "pair_id": f"pair-{i}", "pair_group_id": f"group-{i}",
31
+ "view": "side0", "split": "val", "source_image_path": str(source),
32
+ "target_image_path": str(target)} for i in range(6)]
33
+ metadata = root / "dataset.jsonl"
34
+ write_jsonl(metadata, dataset)
35
+ complete = root / "complete.jsonl"
36
+ partial = root / "partial.jsonl"
37
+ write_jsonl(complete, [{**row, "output_path": str(source), "status": "completed"} for row in dataset])
38
+ write_jsonl(partial, [{**row, "output_path": str(invalid if row["row_index"] == 2 else target),
39
+ "status": "completed"} for row in dataset if row["row_index"] != 1])
40
+ outputs = []
41
+ for workers in (1, 2):
42
+ output = root / f"workers-{workers}"
43
+ subprocess.run([sys.executable, str(ROOT / "scripts/evaluate_image_results.py"),
44
+ "--dataset-manifest", str(metadata), "--result", f"complete={complete}",
45
+ "--result", f"partial={partial}", "--output-dir", str(output),
46
+ "--workers", str(workers)], check=True, capture_output=True, text=True,
47
+ env={**os.environ, "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"})
48
+ outputs.append(output)
49
+ serial, parallel = (read_jsonl(path / "per_pair_results.jsonl") for path in outputs)
50
+ self.assertEqual(serial, parallel)
51
+ self.assertEqual([row["row_index"] for row in serial], [i for i in range(6) for _ in range(2)])
52
+ summaries = [json.loads((path / "summary.json").read_text())["models"] for path in outputs]
53
+ self.assertEqual(*summaries)
54
+ self.assertEqual(summaries[0]["complete"]["completed"], 6)
55
+ self.assertEqual(summaries[0]["partial"]["completed"], 4)
56
+ self.assertEqual(summaries[0]["partial"]["missing_prediction"], 1)
57
+ self.assertEqual(summaries[0]["partial"]["invalid"], 1)
58
+ required = subprocess.run([sys.executable, str(ROOT / "scripts/evaluate_image_results.py"),
59
+ "--dataset-manifest", str(metadata), "--result", f"partial={partial}",
60
+ "--output-dir", str(root / "required"), "--require-complete"],
61
+ capture_output=True, text=True,
62
+ env={**os.environ, "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"})
63
+ self.assertEqual(required.returncode, 1)
64
+
65
+
66
+ if __name__ == "__main__":
67
+ unittest.main()
tests/test_image_geometry_evaluation.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ sys.path.insert(0, str(ROOT / "src"))
16
+
17
+ from wgsr_v9.evaluation_io import read_jsonl, write_jsonl_atomic
18
+ from wgsr_v9.image_geometry_evaluation import (
19
+ compare_geometry, measure_geometry_image, measure_geometry_mask,
20
+ )
21
+
22
+
23
+ class GeometryDefinitionTests(unittest.TestCase):
24
+ def test_height_uses_image_bottom_and_is_unavailable_for_top_view(self) -> None:
25
+ mask = np.zeros((5, 5), dtype=bool)
26
+ mask[1:4, 1:4] = True
27
+ front = measure_geometry_mask(mask, "side0")
28
+ top = measure_geometry_mask(mask, "top")
29
+ self.assertEqual(front["front_height_pct"], 80.0)
30
+ self.assertEqual(front["visible_extent_y_pct"], 60.0)
31
+ self.assertEqual(front["bottom_gap_pct"], 20.0)
32
+ self.assertEqual(front["measurement_status"], "bottom_gap")
33
+ self.assertIsNone(top["front_height_pct"])
34
+ self.assertEqual(compare_geometry(top, top)["height_metric_status"], "not_applicable")
35
+
36
+ def test_density_detects_internal_fill_at_identical_extent(self) -> None:
37
+ solid = np.zeros((5, 5), dtype=bool)
38
+ solid[1:4, 1:4] = True
39
+ sparse = np.zeros_like(solid)
40
+ sparse[np.ix_([1, 3], [1, 3])] = True
41
+ for view in ("front", "top"):
42
+ target = measure_geometry_mask(solid, view)
43
+ prediction = measure_geometry_mask(sparse, view)
44
+ self.assertEqual(target["visible_extent_y_pct"], prediction["visible_extent_y_pct"])
45
+ self.assertEqual(target["convex_hull_area_pixels"], 9)
46
+ self.assertAlmostEqual(prediction["projection_density_fraction"], 4 / 9)
47
+ self.assertAlmostEqual(compare_geometry(target, prediction)["projection_density_abs_error_pp"], 500 / 9)
48
+
49
+ def test_empty_and_degenerate_masks_have_explicit_missing_values(self) -> None:
50
+ mask = np.zeros((5, 5), dtype=bool)
51
+ empty = measure_geometry_mask(mask, "front")
52
+ self.assertIsNone(empty["front_height_pct"])
53
+ self.assertIsNone(empty["projection_density_fraction"])
54
+ mask[1:4, 2] = True
55
+ line = measure_geometry_mask(mask, "front")
56
+ self.assertEqual(line["front_height_pct"], 80.0)
57
+ self.assertIsNone(line["projection_density_fraction"])
58
+ comparison = compare_geometry(line, empty)
59
+ self.assertIsNone(comparison["front_height_abs_error_pp"])
60
+ self.assertIsNone(comparison["projection_density_abs_error_pp"])
61
+ self.assertIn("prediction:empty_foreground", comparison["density_reason_codes"])
62
+ self.assertIn("target:degenerate_hull", comparison["density_reason_codes"])
63
+
64
+ def test_transparent_background_and_near_white_match_pixel_policy(self) -> None:
65
+ with tempfile.TemporaryDirectory() as directory:
66
+ path = Path(directory) / "rgba.png"
67
+ pixels = np.zeros((5, 5, 4), dtype=np.uint8)
68
+ pixels[1:4, 1:4] = (40, 120, 50, 255)
69
+ pixels[0, 0] = (230, 230, 230, 255)
70
+ Image.fromarray(pixels).save(path)
71
+ result = measure_geometry_image(path, "side0")
72
+ self.assertEqual(result["visible_foreground_pixels"], 9)
73
+ self.assertEqual(result["front_height_pct"], 80.0)
74
+ self.assertEqual(result["projection_density_fraction"], 1.0)
75
+
76
+
77
+ class GeometryAugmentationTests(unittest.TestCase):
78
+ def test_augmentation_preserves_fields_counts_missing_and_resumes(self) -> None:
79
+ with tempfile.TemporaryDirectory() as directory:
80
+ root = Path(directory)
81
+ rgb = np.full((8, 8, 3), 255, dtype=np.uint8)
82
+ rgb[2:6, 2:6] = (40, 120, 50)
83
+ image, blank = root / "plant.png", root / "blank.png"
84
+ Image.fromarray(rgb).save(image)
85
+ Image.new("RGB", (8, 8), "white").save(blank)
86
+ dataset = [
87
+ {"pair_id": f"p{i}", "row_index": i, "view": view,
88
+ "source_image_path": str(image), "target_image_path": str(image)}
89
+ for i, view in enumerate(("side0", "side0", "top"))
90
+ ]
91
+ manifest, ledger = root / "dataset.jsonl", root / "results.jsonl"
92
+ write_jsonl_atomic(manifest, dataset)
93
+ write_jsonl_atomic(ledger, [
94
+ {"pair_id": row["pair_id"], "status": "completed", "output_path": str(blank if i == 1 else image)}
95
+ for i, row in enumerate(dataset)
96
+ ])
97
+ env = {**os.environ, "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1"}
98
+ subprocess.run([
99
+ sys.executable, str(ROOT / "scripts/evaluate_image_results.py"),
100
+ "--dataset-manifest", str(manifest), "--result", f"test={ledger}",
101
+ "--output-dir", str(root / "original"),
102
+ ], check=True, capture_output=True, text=True, env=env)
103
+ old = read_jsonl(root / "original/per_pair_results.jsonl")
104
+ # Legacy merged summaries have no manifest hash; per-row hashes
105
+ # and canonical paths must still provide exact input alignment.
106
+ summary_path = root / "original/summary.json"
107
+ legacy = json.loads(summary_path.read_text())
108
+ legacy["dataset_manifest_sha256"] = None
109
+ summary_path.write_text(json.dumps(legacy))
110
+ command = [
111
+ sys.executable, str(ROOT / "scripts/augment_geometry_metrics.py"),
112
+ "--dataset-manifest", str(manifest), "--evaluation-dir", str(root / "original"),
113
+ "--output-dir", str(root / "augmented"), "--workers", "2",
114
+ ]
115
+ subprocess.run(command, check=True, capture_output=True, text=True, env=env)
116
+ result = read_jsonl(root / "augmented/per_pair_results.jsonl")
117
+ for before, after in zip(old, result, strict=True):
118
+ self.assertEqual(before, {key: after[key] for key in before})
119
+ summary = json.loads((root / "augmented/summary.json").read_text())["models"]["test"]
120
+ self.assertEqual(summary["metrics"]["front_height_abs_error_pp"]["n"], 1)
121
+ self.assertEqual(summary["metrics"]["projection_density_abs_error_pp"]["n"], 2)
122
+ self.assertEqual(summary["height_metric_status"], {"available": 1, "unavailable": 1, "not_applicable": 1})
123
+ resumed = subprocess.run(command, check=True, capture_output=True, text=True, env=env)
124
+ self.assertIn("0 pending", resumed.stdout)
125
+ self.assertEqual(result, read_jsonl(root / "augmented/per_pair_results.jsonl"))
126
+
127
+
128
+ if __name__ == "__main__":
129
+ unittest.main()
tests/test_mainline_protocols.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prevent obsolete inference contracts and missing default teacher schemas."""
2
+ import unittest
3
+
4
+ from wgsr_v9.cot_synthesis import render_cot
5
+ from wgsr_v9.planner_inference import protocol_version_for_cot
6
+
7
+
8
+ class MainlineProtocolTests(unittest.TestCase):
9
+ def test_legacy_planner_contracts_are_rejected_before_inference(self):
10
+ for version, numeric, unit in (
11
+ ("v2", None, None),
12
+ ("v3", None, None),
13
+ ("v3", "metric_named_v1", "weeks"),
14
+ ):
15
+ with self.subTest(version=version, numeric=numeric):
16
+ with self.assertRaisesRegex(ValueError, "mainline"):
17
+ protocol_version_for_cot(version, numeric, unit)
18
+
19
+ def test_default_rice_renderer_uses_named_metrics_for_both_views(self):
20
+ for view, keys in (
21
+ ("front", ("culm", "leaves_area", "plant_density", "panicle", "plant_color_development")),
22
+ ("top", ("leaves_area", "canopy", "panicle", "plant_color_development")),
23
+ ):
24
+ with self.subTest(view=view):
25
+ annotation = {
26
+ "stage_reasoning": {"current_stage": "S1_tillering", "future_stage": "S2_jointing"},
27
+ "growth_plan": {key: {"text": "Plant develops"} for key in keys},
28
+ "target_phenotype": {key: {"text": "Green plant"} for key in keys},
29
+ }
30
+ evidence = {"leaves_area": {
31
+ "qc": {"valid": True},
32
+ "source": {"status": "available", "value": 10},
33
+ "target": {"status": "available", "value": 12},
34
+ }}
35
+ try:
36
+ text, omissions = render_cot(annotation, view=view, metric_evidence=evidence)
37
+ except FileNotFoundError as exc:
38
+ self.fail(f"Default teacher schema is not shipped: {exc}")
39
+ self.assertIn("Metric = Foreground area; Source = 10.00%; Target = 12.00%; Change = +2.00 pp.", text)
40
+ self.assertIn("<GROWTH_COT>", text)
41
+ self.assertIn("Current stage: S1_tillering.", text)
42
+ self.assertNotIn("leaves_area", omissions)
tests/test_release_config.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Catch ignored user paths, invalid GPU topology and checkpoint mix-ups."""
2
+ import json
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ import unittest
8
+
9
+ ROOT=Path(__file__).resolve().parents[1]
10
+
11
+ class ConfigurationTests(unittest.TestCase):
12
+ def test_released_settings_select_matching_planner_and_renderer(self):
13
+ with tempfile.TemporaryDirectory(prefix='agrowm release ') as d:
14
+ p=Path(d).resolve()
15
+ self.assertTrue((ROOT/'configs/released.example.json').is_file(),
16
+ 'A published-model settings example must ship with the code')
17
+ settings=json.loads((ROOT/'configs/released.example.json').read_text())
18
+ for crop in ('rice','maize'):
19
+ self.assertEqual(settings[crop+'_planner_adapter'],f'checkpoints/{crop}/phenoclock')
20
+ self.assertEqual(settings[crop+'_renderer_checkpoint'],
21
+ f'checkpoints/{crop}/rooted_renderer/diffusion_pytorch_model.safetensors')
22
+ settings[crop+'_planner_adapter']=str(p/'model release'/crop/'phenoclock')
23
+ settings[crop+'_renderer_checkpoint']=str(p/'model release'/crop/'renderer.safetensors')
24
+ settings_path=p/'settings.json';settings_path.write_text(json.dumps(settings))
25
+ result=subprocess.run([sys.executable,str(ROOT/'scripts/configure.py'),'--settings',str(settings_path),
26
+ '--output',str(p/'out')],capture_output=True,text=True)
27
+ self.assertEqual(result.returncode,0,result.stderr)
28
+ from wgsr_v9.executor_inference.config import load_config,default_checkpoint
29
+ for crop in ('rice','maize'):
30
+ planner=json.loads((p/'out'/crop/'planner_infer.json').read_text())
31
+ self.assertEqual(planner['adapter'],settings[crop+'_planner_adapter'])
32
+ renderer=load_config(p/'out'/crop/'executor_infer.json')
33
+ selected=Path(settings[crop+'_renderer_checkpoint'])
34
+ self.assertEqual(default_checkpoint(renderer,'predicted_cot'),selected)
35
+ self.assertEqual(default_checkpoint(renderer,'teacher_cot'),selected)
36
+ self.assertNotEqual(default_checkpoint(renderer,'simple'),selected)
37
+ base=load_config(p/'out'/crop/'executor_base.json')
38
+ self.assertNotIn('checkpoints',base)
39
+ self.assertNotIn('executor_training_root',base)
40
+
41
+ def test_renderer_only_override_preserves_other_crop_and_base_controls(self):
42
+ with tempfile.TemporaryDirectory() as d:
43
+ p=Path(d).resolve()
44
+ settings_path=p/'settings.json'
45
+ settings_path.write_text(json.dumps({'rice_renderer_checkpoint':'downloaded/rice.safetensors'}))
46
+ result=subprocess.run([sys.executable,str(ROOT/'scripts/configure.py'),'--settings',str(settings_path),
47
+ '--output',str(p/'out')],capture_output=True,text=True)
48
+ self.assertEqual(result.returncode,0,result.stderr)
49
+ from wgsr_v9.executor_inference.config import load_config,default_checkpoint
50
+ rice=load_config(p/'out/rice/executor_infer.json')
51
+ maize=load_config(p/'out/maize/executor_infer.json')
52
+ self.assertEqual(default_checkpoint(rice,'predicted_cot'),ROOT/'downloaded/rice.safetensors')
53
+ self.assertEqual(default_checkpoint(maize,'predicted_cot'),
54
+ ROOT/'runs/maize/executor_training/teacher_cot/checkpoints/epoch-1.safetensors')
55
+
56
+ def test_settings_relocate_both_crops_and_keep_ours_on_text_checkpoint(self):
57
+ with tempfile.TemporaryDirectory(prefix='agrowm config ') as d:
58
+ p=Path(d).resolve()
59
+ settings={'data_root':str(p/'data'), 'run_root':str(p/'runs'),
60
+ 'planner_model':str(p/'models/planner'), 'image_model':str(p/'models/renderer'),
61
+ 'diffsynth_repo':str(p/'vendor'), 'planner_env':str(p/'p-env'),
62
+ 'renderer_env':str(p/'r-env'), 'rice_planner_adapter':str(p/'rice-adapter'),
63
+ 'maize_planner_adapter':str(p/'maize-adapter')}
64
+ config=p/'settings.json'; config.write_text(json.dumps(settings))
65
+ result=subprocess.run([sys.executable,str(ROOT/'scripts/configure.py'),'--settings',str(config),
66
+ '--output',str(p/'local')],capture_output=True,text=True)
67
+ self.assertEqual(result.returncode,0,result.stderr)
68
+ from wgsr_v9.executor_inference.config import load_config,default_checkpoint
69
+ for crop,count in [('rice',2000),('maize',1600)]:
70
+ cfg=load_config(p/'local'/crop/'executor_infer.json')
71
+ self.assertEqual(cfg['executor_data_root'],str(p/'data'/crop/'executor'))
72
+ self.assertEqual(default_checkpoint(cfg,'predicted_cot'),p/'runs'/crop/'executor_training/teacher_cot/checkpoints/epoch-1.safetensors')
73
+ self.assertEqual(cfg['expected_rows'],count)
74
+ planner=json.loads((p/'local'/crop/'planner_infer.json').read_text())
75
+ self.assertEqual(planner['adapter'],str(p/(crop+'-adapter')))
76
+ self.assertEqual(planner['evaluation_manifest'],str(p/'data'/crop/'evaluation/manifest.jsonl'))
77
+ z=load_config(p/'local'/crop/'executor_base.json')
78
+ self.assertNotIn('checkpoints',z)
79
+ self.assertNotIn('executor_training_root',z)
80
+ self.assertNotEqual(subprocess.run([sys.executable,str(ROOT/'scripts/configure.py'),'--settings',str(config),
81
+ '--output',str(p/'local')],capture_output=True).returncode,0)
82
+
83
+ def test_gpu_count_mismatch_is_rejected(self):
84
+ with tempfile.TemporaryDirectory() as d:
85
+ p=Path(d); cfg=p/'settings.json';cfg.write_text(json.dumps({'renderer_train_gpus':'0,1'}))
86
+ result=subprocess.run([sys.executable,str(ROOT/'scripts/configure.py'),'--settings',str(cfg),'--output',str(p/'out')],capture_output=True,text=True)
87
+ self.assertNotEqual(result.returncode,0)
88
+ self.assertIn('8',result.stderr)
tests/test_text_executor_release.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exercise text inference without optional injection modules or a GPU backend."""
2
+ import builtins
3
+ from contextlib import nullcontext, redirect_stdout
4
+ import copy
5
+ import io
6
+ import json
7
+ from pathlib import Path
8
+ import sys
9
+ import tempfile
10
+ from types import SimpleNamespace
11
+ import unittest
12
+ import warnings
13
+ from unittest.mock import patch
14
+
15
+ from PIL import Image
16
+
17
+ from scripts.configure import configure
18
+ from scripts.prepare_data import prepare
19
+ from tests.test_release_data import make_pairs
20
+ from wgsr_v9.executor_launcher import build_plan
21
+ from wgsr_v9.executor_inference.cli import parse_args
22
+ from wgsr_v9.executor_inference.config import validate_config
23
+ from wgsr_v9.executor_inference import runner
24
+ from wgsr_v9.io import read_jsonl, write_json, write_jsonl, sha256_path, canonical_sha256
25
+
26
+ ROOT = Path(__file__).resolve().parents[1]
27
+
28
+
29
+ class CpuGenerator:
30
+ def __init__(self, *, device):
31
+ self.device = device
32
+
33
+ def manual_seed(self, seed):
34
+ self.seed = seed
35
+ return self
36
+
37
+
38
+ class TextExecutorReleaseTests(unittest.TestCase):
39
+ def test_numeric_training_config_cannot_silently_run_text_training(self):
40
+ config = json.loads((ROOT / 'configs/recipes/rice/executor_teacher_cot.json').read_text())
41
+ config['numeric_condition'] = {'enabled': True}
42
+ try:
43
+ with self.assertRaisesRegex(ValueError, 'Numeric injection is not included'):
44
+ build_plan(config, 'teacher_cot', 'train')
45
+ except FileNotFoundError:
46
+ self.fail('Numeric config reached model loading instead of being rejected')
47
+
48
+ def test_numeric_inference_config_cannot_silently_run_text_inference(self):
49
+ config = json.loads((ROOT / 'configs/recipes/rice/executor_infer.json').read_text())
50
+ config.update(world_size=1, physical_gpu_ids='0')
51
+ for field, value in (
52
+ ('numeric_bundle', 'old-bundle'),
53
+ ('numeric_condition', {'enabled': True}),
54
+ ('condition_dropout', 'drop_numeric'),
55
+ ):
56
+ with self.subTest(field=field):
57
+ changed = {**config, field: value}
58
+ with self.assertRaisesRegex(ValueError, 'Numeric injection is not included'):
59
+ validate_config(changed)
60
+
61
+ def test_mainline_workers_and_completed_resume_without_numeric_module(self):
62
+ # Only the GPU/model boundary is substituted. Preparation, CLI, manifest
63
+ # validation, image I/O, ledgers and resume checks execute normally.
64
+ original_import = builtins.__import__
65
+
66
+ def without_numeric(name, *args, **kwargs):
67
+ if 'executor_numeric' in name.split('.'):
68
+ raise ModuleNotFoundError('optional injection module is unavailable')
69
+ return original_import(name, *args, **kwargs)
70
+
71
+ torch_backend = SimpleNamespace(
72
+ cuda=SimpleNamespace(is_available=lambda: True, set_device=lambda _: None),
73
+ Generator=CpuGenerator, inference_mode=nullcontext,
74
+ )
75
+ for crop, view in (('rice', 'front'), ('rice', 'top'), ('maize', 'sv1')):
76
+ with self.subTest(crop=crop, view=view), tempfile.TemporaryDirectory() as temporary:
77
+ root = Path(temporary).resolve()
78
+ pairs = make_pairs(root, crop)
79
+ size = (672, 896) if crop == 'rice' else (768, 1280)
80
+ if view == 'top':
81
+ size = (896, 672)
82
+ for row in pairs:
83
+ row['view'] = 'top'
84
+ for role in ('source', 'target'):
85
+ Image.new('RGB', size, 'white').save(root / row[role + '_image_path'])
86
+ row['teacher_cot'] = '\n'.join(
87
+ line.replace('Plant density:', 'Canopy:').replace('Metric = Solidity;', 'Metric = Canopy density;')
88
+ for line in row['teacher_cot'].splitlines() if not line.startswith('Culm:'))
89
+ write_jsonl(root / 'pairs.jsonl', pairs)
90
+ package = root / 'data' / crop
91
+ prepare(crop, root / 'pairs.jsonl', package)
92
+ write_json(root / 'settings.json', {'data_root': str(root / 'data'), 'run_root': str(root / 'runs')})
93
+ configure(root / 'settings.json', root / 'configs')
94
+ model = root / 'model'
95
+ (model / 'transformer').mkdir(parents=True)
96
+ write_json(model / 'transformer/config.json', {})
97
+ (model / 'transformer/diffusion_pytorch_model.safetensors').write_bytes(b'base-test-weights')
98
+ checkpoint = root / 'text.safetensors'
99
+ checkpoint.write_bytes(b'text-test-weights')
100
+ predicted = copy.deepcopy(read_jsonl(package / 'executor/teacher_cot/val.jsonl')[0])
101
+ predicted.update(executor_variant='predicted_cot', cot_source='planner_prediction', adapter_sha256='test-planner')
102
+ predicted['prompt'] = predicted['prompt'].replace('Taller culms.', 'Predicted taller culms.').replace('The visible plant develops.', 'Predicted plant development.')
103
+ write_jsonl(root / 'predicted.jsonl', [predicted])
104
+ # A missing target must not prevent source-only image generation.
105
+ (root / 'val_target.png').unlink()
106
+ for variant, pretrained in (('simple', False), ('teacher_cot', False), ('predicted_cot', False),
107
+ ('simple', True), ('predicted_cot', True)):
108
+ with self.subTest(variant=variant, pretrained=pretrained):
109
+ config_path = root / 'configs' / crop / ('executor_base.json' if pretrained else 'executor_infer.json')
110
+ config = json.loads(config_path.read_text())
111
+ config['expected_rows'] = 1
112
+ write_json(config_path, config)
113
+ output = root / (variant + ('_base' if pretrained else '_trained'))
114
+ command = ['infer', '--config', str(config_path), '--variant', variant,
115
+ '--model-path', str(model), '--output-root', str(output), '--world-size', '1', '--gpu-ids', '0']
116
+ if variant == 'predicted_cot':
117
+ command += ['--input-manifest', str(root / 'predicted.jsonl')]
118
+ if not pretrained:
119
+ command += ['--checkpoint', str(checkpoint)]
120
+ else:
121
+ command += ['--pretrained']
122
+ with patch.object(sys, 'argv', command):
123
+ args = parse_args()
124
+ input_rows, input_sha = runner.load_input_rows(args.input_manifest, None)
125
+ expected_prompt = input_rows[0]['prompt']
126
+ calls = []
127
+
128
+ def image_backend(**kwargs):
129
+ calls.append(kwargs)
130
+ return SimpleNamespace(images=[Image.new('RGB', (kwargs['width'], kwargs['height']),
131
+ (kwargs['generator'].seed % 256, 0, 0))])
132
+
133
+ def worker_process(command, **kwargs):
134
+ with patch.object(sys, 'argv', command[1:]):
135
+ worker_args = parse_args()
136
+ status = runner.worker_main(worker_args)
137
+ return SimpleNamespace(pid=1234, poll=lambda: status)
138
+
139
+ with patch.object(builtins, '__import__', without_numeric), \
140
+ patch.dict(sys.modules, {'torch': torch_backend}), \
141
+ patch.object(runner, 'load_pipeline', return_value=(image_backend, {}, 'bf16')), \
142
+ patch.object(runner, 'nvidia_memory', return_value={'0': 0}), \
143
+ patch.object(runner.subprocess, 'Popen', side_effect=worker_process), \
144
+ warnings.catch_warnings(record=True) as notices, \
145
+ redirect_stdout(io.StringIO()):
146
+ warnings.simplefilter('always', ResourceWarning)
147
+ try:
148
+ self.assertEqual(runner.supervisor_main(args), 0)
149
+ except ModuleNotFoundError as exc:
150
+ self.fail(f'Text worker depends on an optional injection module: {exc}')
151
+ self.assertEqual(len(calls), 1)
152
+ self.assertEqual(calls[0]['prompt'], expected_prompt)
153
+ self.assertEqual(calls[0]['image'].size, size)
154
+ self.assertEqual(calls[0]['num_inference_steps'], 20)
155
+ self.assertNotIn('attention_kwargs', calls[0])
156
+ result = read_jsonl(output / 'rank-00/results.jsonl')[0]
157
+ self.assertEqual(result['seed'], 917)
158
+ self.assertEqual(result['output_size'], list(size))
159
+ self.assertEqual(result['prompt'], expected_prompt)
160
+ with Image.open(result['output_path']) as generated:
161
+ self.assertEqual(generated.getpixel((0, 0)), (149, 0, 0))
162
+ # Mainline identities written before module removal include this null field.
163
+ previous_identity = {
164
+ 'variant': variant, 'input_manifest_sha256': input_sha,
165
+ 'checkpoint_sha256': None if pretrained else sha256_path(checkpoint),
166
+ **({'pretrained_transformer': runner.pretrained_transformer_identity(model)} if pretrained else {}),
167
+ 'model_path': str(model), 'selected_indices': [0], 'steps': 20,
168
+ 'dtype': args.dtype, 'use_kv_cache': args.use_kv_cache,
169
+ 'seed_base': args.seed_base, 'seed_manifest_sha256': sha256_path(args.seed_manifest),
170
+ 'numeric_condition': None,
171
+ 'executor_prompt_protocol_version': config['executor_prompt_protocol_version'],
172
+ }
173
+ self.assertEqual(result['run_identity_sha256'], canonical_sha256(previous_identity))
174
+ write_json(output / 'inference_manifest.json', {'status': 'complete', 'run_identity': previous_identity})
175
+ self.assertEqual(runner.supervisor_main(args), 0)
176
+ self.assertEqual(runner.worker_main(args), 0)
177
+ self.assertEqual(len(calls), 1)
178
+ self.assertEqual(len(read_jsonl(output / 'rank-00/results.jsonl')), 1)
179
+ self.assertFalse([n for n in notices if issubclass(n.category, ResourceWarning)])