File size: 8,046 Bytes
6bad40e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""CropCode inference: run a released model on a sample (or on inputs you prepared the same way).

    python inference.py --list
    python inference.py --model sorghum-generalist --sample samples/sorghum/plant_Sorghum_10756 --source rgb
    python inference.py --model maize-field --sample samples/maize/field_0204_row0936_stop06

A sample folder holds `inputs.npz`, the tensors the model reads, written by the training loaders:
  rgb    (3, 224, 224) float32, ImageNet-normalised photograph (plant pixels on black)
  depth  (1, 224, 224) float32, encoded depth, 0 = background
  pc     (N, 3)        float32, point cloud centred and scaled to the unit sphere
  scale  ()            metres per unit of the cloud frame
and, when known, the truth: `gt_pc` (M, 3) in the same frame, `height_m`, `leaves`.
Writes <out>/pred_cloud.ply (metres, centred like the input cloud), <out>/recipe.json (the written procedural
parameters: plant height, leaf count and one record per leaf) and <out>/summary.json.
"""
import argparse, json, pathlib, sys
import numpy as np
import torch

HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / 'cropcode_model'))
MODALITIES = ('rgb', 'depth', 'pc', 'text')


def build(name, device):
    d = HERE / 'models' / name
    cfg = json.loads((d / 'config.json').read_text()); sp = cfg['species']
    if sp == 'maize':
        import embodied_mae_4m_maize as M
        factory = getattr(M, f"embodied_mae_4m_maize_{cfg.get('model_size', 'base')}"); kw = dict(param_schema=cfg.get('param_schema') or 'v1')
        n_pts, n_leaves = 8192, 28
    else:
        import embodied_mae_4m as M
        factory = getattr(M, f"embodied_mae_4m_{cfg.get('model_size', 'base')}"); kw = {}
        n_pts, n_leaves = 8196, 24
    model = factory(active_modalities=cfg.get('active_modalities'), img_size=cfg.get('img_size', 224), num_pc_tokens=196,
                    target_points=cfg.get('gt_points', cfg.get('num_points', n_pts)), max_leaves=cfg.get('max_leaves', n_leaves),
                    depth_norm_type=cfg.get('depth_norm_type', 'minmax'), pc_loss_name=cfg.get('pc_loss_name', 'qal_loss'),
                    pc_sinkhorn_weight=0.0, text_mask_ratio=cfg.get('text_mask_ratio'), **kw)
    from safetensors.torch import load_file
    model.load_state_dict(load_file(str(d / 'model.safetensors')), strict=True)
    return model.to(device).eval(), cfg


@torch.no_grad()
def predict(model, source, rgb, depth, pc, mask_ratio, seed=0):
    """source 'all': every stream visible at the training mask ratio (the masked regime the model was trained in);
    'rgb' / 'depth' / 'pc': that stream alone, fully visible, the others hidden. The procedural parameters are never
    an input: a zero tensor stands in for them."""
    torch.manual_seed(seed)
    act = set(model.active_modalities)
    zeros = torch.zeros(1, model.pos_embed_text.shape[1], model.param_embed.proj.in_features, device=rgb.device)
    if source == 'all':
        out = model.forward_encoder_select(rgb, depth, pc, zeros, visible={'rgb', 'depth', 'pc'} & act, source_mask_ratio=mask_ratio)
    else:
        out = model.forward_encoder_select(rgb, depth, pc, zeros, visible={source}, source_mask_ratio=0.0)
    latent, rests, nvis = out[0], out[5:9], dict(zip(MODALITIES, out[9:13]))
    _, _, pred_pc, pred_par = model.forward_decoder(latent, *rests, *nvis.values())
    return pred_pc[0].float().cpu().numpy(), pred_par[0].float().cpu().numpy()


def decode_recipe(sp, par, cfg):
    """normalised (1 + K, n_params) -> height (m), leaf count and per-leaf fields in the generator's units"""
    par = np.clip(np.asarray(par, np.float64), 0, 1); rf = cfg.get('real_finetune') or {}
    if sp == 'sorghum':
        import embodied_mae_4m as S
        nf = len(S.LEAF_FIELDS); H = float(par[0, 0] * S._PLANT_SCALE[0] - S._PLANT_SHIFT[0])
        raw = par[1:, :nf] * S._LEAF_SCALE[:nf] - S._LEAF_SHIFT[:nf]
        if rf.get('count_slots'):                        # leaf-count model: the leaves are the slots longer than the threshold
            keep = raw[:, list(S.LEAF_FIELDS).index('length')] > float(rf.get('count_threshold_m') or 0.05); raw = raw[keep]
        else:                                            # synthetic sorghum: the leaf count follows the stem length
            raw = raw[:int(np.clip(np.rint((H + 0.001) / 0.05), 0, len(raw)))]
        return dict(height_m=H, leaves=len(raw), leaf_fields=list(S.LEAF_FIELDS), leaf=[[float(x) for x in r] for r in raw])
    import embodied_mae_4m_maize as M
    sc = np.array(rf.get('leaf_scale', M._LEAF_SCALE_V2), np.float64); sh = np.array(rf.get('leaf_shift', M._LEAF_SHIFT_V2), np.float64)
    p = par[0] * M._PLANT_SCALE_V2 - M._PLANT_SHIFT_V2; nf = len(M.LEAF_FIELDS_V2)
    n = int(np.clip(np.rint(p[M.PLANT_FIELDS_V2.index('leafCount')]), 0, par.shape[0] - 1))
    raw = par[1:1 + n, :nf] * sc[:nf] - sh[:nf]
    return dict(height_m=float(p[M.PLANT_FIELDS_V2.index('height')]), leaves=n,
                stem_internode_sum_m=float(p[M.PLANT_FIELDS_V2.index('stemInternodeSum')]),
                leaf_fields=list(M.LEAF_FIELDS_V2), leaf=[[float(x) for x in r] for r in raw])


def chamfer(a, b):
    """symmetric squared Chamfer (mean of both directions), same units as the clouds squared"""
    a, b = torch.as_tensor(a, dtype=torch.float32), torch.as_tensor(b, dtype=torch.float32)
    d = torch.cdist(a, b) ** 2
    return float(d.min(1).values.mean() + d.min(0).values.mean())


def write_ply(path, xyz):
    xyz = np.asarray(xyz, np.float32)
    with open(path, 'wb') as f:
        f.write(f'ply\nformat binary_little_endian 1.0\nelement vertex {len(xyz)}\n'
                'property float x\nproperty float y\nproperty float z\nend_header\n'.encode())
        f.write(xyz.tobytes())


def run(model_name, sample, source='all', out=None, device='cpu', seed=0, model=None, cfg=None):
    if model is None: model, cfg = build(model_name, device)
    z = np.load(pathlib.Path(sample) / 'inputs.npz')
    t = lambda k: torch.from_numpy(z[k]).float()[None].to(device)
    P, par = predict(model, source, t('rgb'), t('depth'), t('pc'), float(cfg.get('mask_ratio', 0.8)), seed)
    rec = decode_recipe(cfg['species'], par, cfg); scale = float(z['scale'])
    res = dict(model=model_name, sample=pathlib.Path(sample).name, source=source, seed=seed,
               pred_height_m=round(rec['height_m'], 3), pred_leaves=rec['leaves'])
    if 'gt_pc' in z.files: res['chamfer_1e-4_m2'] = round(chamfer(P, z['gt_pc']) * scale ** 2 * 1e4, 2)
    for k in ('height_m', 'leaves'):
        if k in z.files: res['true_' + k] = round(float(z[k]), 3) if k == 'height_m' else int(z[k])
    if out:
        out = pathlib.Path(out); out.mkdir(parents=True, exist_ok=True)
        write_ply(out / 'pred_cloud.ply', P * scale)
        (out / 'recipe.json').write_text(json.dumps(rec, indent=1)); (out / 'summary.json').write_text(json.dumps(res, indent=1))
    return res


if __name__ == '__main__':
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--model'); ap.add_argument('--sample')
    ap.add_argument('--source', default='all', choices=('all', 'rgb', 'depth', 'pc'))
    ap.add_argument('--out', default=None, help='default: predictions/<sample>__<model>__<source>')
    ap.add_argument('--seed', type=int, default=0); ap.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
    ap.add_argument('--list', action='store_true', help='list the models and samples')
    a = ap.parse_args()
    if a.list or not (a.model and a.sample):
        print('models: ', ' '.join(sorted(p.name for p in (HERE / 'models').iterdir())))
        print('samples:', ' '.join(sorted(str(p.relative_to(HERE)) for p in (HERE / 'samples').glob('*/*') if p.is_dir())))
        sys.exit(0)
    out = a.out or HERE / 'predictions' / f'{pathlib.Path(a.sample).name}__{a.model}__{a.source}'
    print(json.dumps(run(a.model, a.sample, a.source, out, a.device, a.seed), indent=1)); print('wrote', out)