File size: 6,733 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
2ad60ce
f877698
 
 
 
2ad60ce
f877698
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
2ad60ce
 
f877698
 
 
 
2ad60ce
f877698
2ad60ce
f877698
 
 
 
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np

from .handoff import write_handoff

CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
GRID_HW = (294, 518)
SCALE = 2
UP_HW = (GRID_HW[0] * SCALE, GRID_HW[1] * SCALE)
MODEL_HW = (592, 1040)


def to_u8(rgb01):
    return (np.clip(np.asarray(rgb01, np.float32), 0, 1) * 255).round().astype(np.uint8)


def up2_rgb(frame_u8):
    from PIL import Image
    f = np.asarray(frame_u8)
    assert f.dtype == np.uint8 and f.shape[:2] == GRID_HW, f.shape
    return np.asarray(Image.fromarray(f).resize((UP_HW[1], UP_HW[0]), Image.LANCZOS))


def up2_mask(mask):
    m = np.asarray(mask, bool)
    assert m.shape == GRID_HW, m.shape
    return np.repeat(np.repeat(m, SCALE, 0), SCALE, 1)


def pad_edge(a, hw=MODEL_HW):
    a = np.asarray(a)
    ph, pw = hw[0] - a.shape[0], hw[1] - a.shape[1]
    assert ph >= 0 and pw >= 0, (a.shape, hw)
    return np.pad(a, ((0, ph), (0, pw)) + ((0, 0),) * (a.ndim - 2), mode='edge')


def crop_pad(a, hw=UP_HW):
    a = np.asarray(a)
    assert a.shape[:2] == MODEL_HW, a.shape
    return a[:hw[0], :hw[1]]


def to_model(frame_u8, mask=None):
    img = pad_edge(up2_rgb(frame_u8))
    m = None if mask is None else pad_edge(up2_mask(mask))
    assert img.shape == (*MODEL_HW, 3) and (m is None or m.shape == MODEL_HW)
    return img, m


def from_model(gen_u8):
    from PIL import Image
    g = crop_pad(np.asarray(gen_u8))
    assert g.dtype == np.uint8 and g.shape == (*UP_HW, 3), g.shape
    out = np.asarray(Image.fromarray(g).resize((GRID_HW[1], GRID_HW[0]), Image.LANCZOS))
    assert out.shape == (*GRID_HW, 3)
    return out


def to_pil(img_u8, mask=None):
    from PIL import Image
    im = Image.fromarray(np.asarray(img_u8, np.uint8))
    return im if mask is None else (im, Image.fromarray(np.where(np.asarray(mask, bool), 255, 0).astype(np.uint8), mode='L'))


def attach_lora(transformer, rank, alpha, targets, init='gaussian', dropout=0.0):
    from peft import LoraConfig
    cfg = LoraConfig(r=rank, lora_alpha=alpha, lora_dropout=dropout, init_lora_weights=init, target_modules=list(targets))
    transformer.add_adapter(cfg)
    return cfg


def load_lora(transformer, path):
    from safetensors import safe_open
    from safetensors.torch import load_file
    with safe_open(str(path), 'pt') as f:
        md = f.metadata()
    attach_lora(transformer, int(md['rank']), float(md['alpha']), md['targets'].split(','))
    sd = load_file(str(path))
    P = {k: p for k, p in transformer.named_parameters() if 'lora_' in k}
    if set(P) != set(sd):
        raise ValueError(f'LoRA keys differ: missing {len(set(P) - set(sd))}, unexpected {len(set(sd) - set(P))}')
    for k, v in sd.items():
        P[k].data = v.to(device=P[k].device, dtype=P[k].dtype)
    return md


def load_pipeline(base, device, dtype_name='bfloat16', lora=None, revision=None):
    import torch
    from diffusers import FluxFillPipeline
    kw = {} if Path(base).is_dir() else {'revision': revision}
    pipe = FluxFillPipeline.from_pretrained(str(base), torch_dtype=getattr(torch, dtype_name), **kw)
    md = load_lora(pipe.transformer, lora) if lora else None
    pipe.to(device)
    pipe.set_progress_bar_config(disable=True)
    return pipe, md


def encode_prompt(pipe, prompt, device, max_sequence_length=512):
    import torch
    with torch.no_grad():
        pe, ppe, _ = pipe.encode_prompt(prompt=prompt, prompt_2=None, device=device, num_images_per_prompt=1,
                                        max_sequence_length=max_sequence_length)
    return pe, ppe


def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
    import torch
    im, m = to_pil(img_u8, mask)
    h, w = np.asarray(img_u8).shape[:2]
    gen = torch.Generator('cpu').manual_seed(int(sampling['seed']))
    out = pipe(image=im, mask_image=m, height=h, width=w, prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds,
               strength=sampling['strength'], num_inference_steps=sampling['steps'], guidance_scale=sampling['guidance_scale'],
               max_sequence_length=sampling['max_sequence_length'], generator=gen, output_type='pil').images[0]
    g = np.asarray(out)
    assert g.shape == (h, w, 3) and g.dtype == np.uint8, g.shape
    return g


def fix_frame(pipe, frame_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
    img, m = to_model(frame_u8, mask)
    return from_model(generate(pipe, img, m, prompt_embeds, pooled_prompt_embeds, sampling))


def main(argv=None):
    import torch
    p = argparse.ArgumentParser(prog='agt.completion.flux_fill')
    p.add_argument('--pass1', required=True, help='reconstruction output directory (frames.npz, observability.npz)')
    p.add_argument('--out', required=True)
    p.add_argument('--config', default=str(CONFIG))
    p.add_argument('--base', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id (default: config)')
    p.add_argument('--lora', default='checkpoints/agt_completion_lora.safetensors')
    p.add_argument('--clips', nargs='+', help='clip ids (default: every clip of --pass1)')
    a = p.parse_args(argv)
    cfg = json.loads(Path(a.config).read_text())
    sampling, position = cfg['sampling'], cfg['position']
    clips = a.clips or sorted(d.name for d in Path(a.pass1).iterdir() if (d / 'observability.npz').is_file())
    out = Path(a.out)
    dev = torch.device('cuda:0')
    t0 = time.time()
    pipe, lora_md = load_pipeline(a.base or cfg['base_model'], dev, cfg['dtype'], a.lora, cfg['base_revision'])
    pe, ppe = encode_prompt(pipe, cfg['prompt'], dev, sampling['max_sequence_length'])
    print(json.dumps(dict(lora=a.lora, lora_meta=lora_md, load_s=round(time.time() - t0, 1))), flush=True)
    for cid in clips:
        with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h:
            frame = h['rgb'][position].astype(np.float32)
        with np.load(Path(a.pass1) / cid / 'observability.npz', allow_pickle=False) as h:
            mask = h['unobserved'][position].astype(bool)
        ti = time.time()
        fixed = fix_frame(pipe, to_u8(frame), mask, pe, ppe, sampling)
        fixed01 = fixed.astype(np.float32) / np.float32(255)
        meta = dict(clip_id=cid, generator='FLUX.1-Fill-dev' + (' + LoRA' if a.lora else ''), prompt=cfg['prompt'],
                    sampling=sampling, dtype=cfg['dtype'], position=position)
        write_handoff(out / f'{cid}.npz', fixed01[None], mask[None], [position], meta)
        print(json.dumps(dict(clip=cid, seconds=round(time.time() - ti, 1), unobserved_fraction=float(mask.mean()))), flush=True)


if __name__ == '__main__':
    main()