File size: 3,169 Bytes
9ec5995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6daa104
9ec5995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Publish a checkpoint and its inference pipeline to a Hugging Face model repo.

    python -m scripts.publish fatmur/dynamicworld-small-cnn \
        artifacts/small_cnn_unet/version_0/checkpoints/last.ckpt

Add --out release/dynamicworld-small-cnn to retain a local export.
The run's config.yaml supplies preprocessing; the checkpoint supplies the
weights and validation chip settings; the run config also freezes its label scheme.
"""

from pathlib import Path

import typer
import yaml

from geosave.ml import RasterPipeline
from geosave.ml.factory import BuildSpec
from geosave.ml.processing.raster.ingestion.sentinel2 import Sentinel2Ingestor
from geosave.ml.processing.raster.postprocessing.dense import SegmentationPostprocessor
from geosave.ml.processing.raster.prediction.dense import DensePredictor
from geosave.ml.processing.raster.preprocessing.base import PREPROCESSORS
from geosave.ml.release import ChainModel
from modules.supervised.module import Module


def main(
    repo_id: str,
    checkpoint: Path,
    out: Path | None = typer.Option(None, help="Optional local release directory."),
) -> None:
    """Publish to repo_id; optionally keep the same release locally."""
    # Lightning writes a run's resolved config beside its checkpoints folder.
    run = checkpoint.parent.parent
    config = yaml.safe_load((run / "config.yaml").read_text())
    labels = config["data"]["train"]["init_args"]["label_scheme"]
    val_labels = config["data"]["val"]["init_args"]["label_scheme"]
    if labels != val_labels:
        raise ValueError("training and validation label schemes differ")

    module = Module.load_from_checkpoint(checkpoint, map_location="cpu")
    module.eval()
    if module.model.head.num_classes != len(labels["classes"]):
        raise ValueError("checkpoint head does not match the run label scheme")

    preprocessor_spec = config["data"]["train"]["init_args"]["preprocessor"]
    preprocessor = PREPROCESSORS.build(BuildSpec.model_validate(preprocessor_spec))

    # The release chips and merges a raster as validation chipped the scenes.
    predictor = DensePredictor(
        size=module.chip_size,
        stride=module.chip_stride,
        mode=module.chip_mode,
        window=module.merge_window,
        batch_size=module.chip_batch_size,
        context=["centroid", "year", "day_of_year"],
        nodes=None,
    )
    postprocessor = SegmentationPostprocessor(
        classes=labels["classes"], colors=labels["colors"], mask=None
    )
    # The images were ingested at 10 m under the node the preprocessor reads.
    ingestor = Sentinel2Ingestor(
        bands=preprocessor.bands, resolution=10.0, name=preprocessor.name
    )

    pipeline = RasterPipeline(
        module.model,
        preprocessor=preprocessor,
        predictor=predictor,
        postprocessor=postprocessor,
        ingestor=ingestor,
    )
    release = ChainModel.from_pipeline(pipeline)
    if out is not None:
        release.save_pretrained(out)
        print(f"Saved local release to {out}")

    commit = release.push_to_hub(repo_id)
    print(f"Released {repo_id} at {commit.oid}")


if __name__ == "__main__":
    typer.run(main)