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