File size: 5,691 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""End-to-end MOSS-Image generation on the card: five fixed-seed prompts (plain scene, anime character, English sign text,
Chinese text rendering, structured JSON layout). Writes PNG + sidecar JSON per prompt and a run summary.

Usage: python moss_gen.py [--size 1024] [--steps 50] [--only a,b] [--out /opt/mossimage/work/e2e] [--device GPU]
"""
import argparse
import json
import os
import sys
import time

import numpy as np

sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import hwm_gb  # noqa: E402

LAYOUT = {
    "summary": {
        "meta": ["poster"],
        "canvas": "single",
        "caption": "A minimalist travel poster with a cream paper background, a flat blue mountain illustration with a small orange sun, and the title EXPLORE at the top with a smaller subtitle below the mountain.",
    },
    "items": [
        {"label": "text", "caption": "Large dark-blue uppercase title centered at the top.", "text": "EXPLORE", "bbox": [-416, -384, -288, 384]},
        {"label": "object", "caption": "A flat blue mountain illustration with snowy peaks in the lower center.", "bbox": [-192, -288, 384, 288]},
        {"label": "object", "caption": "A small orange sun above the left shoulder of the mountain.", "bbox": [-224, -320, -128, -224]},
        {"label": "text", "caption": "Small gray sans-serif subtitle centered under the mountain.", "text": "NORTHERN RANGE - SINCE 1962", "bbox": [416, -288, 464, 288]},
    ],
    "bbox_coord_space": "abs_centralized",
    "bbox_format": "yxyx",
}

PROMPTS = [
    ("scene", 1001, "A quiet harbor town at dawn, small fishing boats moored along a stone quay, soft mist over the water, warm light in the windows of the old houses, gulls in the pale sky, photorealistic, natural colors"),
    ("anime", 1002, "Anime illustration of a girl with long silver twin-tails and a navy sailor uniform standing on a school rooftop at sunset, wind in her hair, cherry blossom petals drifting, detailed eyes, clean lineart, vivid colors, best quality"),
    ("sign_en", 1003, 'A weathered wooden road sign on a country road at golden hour, the sign reads "WELCOME TO WILLOW CREEK" on the first line and "POP. 412" on the second line, hand-painted white letters, shallow depth of field, photograph'),
    ("text_zh", 1004, "一张复古风格的茶馆海报,画面中央用毛笔字写着“清茶一盏”,下方一行小字“欢迎光临 · 营业时间 上午九点至晚上九点”,红色和米色配色,扁平插画风格,纸张质感"),
    ("layout", 1005, json.dumps(LAYOUT, ensure_ascii=False)),
]
NEGATIVE = ""
MODEL_NOTE = {"sft": "MOSS-Image-SFT (OpenVINO fp16, Arc Pro B60)", "sft-int8": "MOSS-Image-SFT, NNCF per-channel int8 weights with the ffn_down projections in fp16 (OpenVINO, Arc Pro B60)"}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--size", type=int, default=1024)
    ap.add_argument("--width", type=int, default=0)
    ap.add_argument("--height", type=int, default=0)
    ap.add_argument("--steps", type=int, default=0, help="0 = the variant's default (30)")
    ap.add_argument("--variant", default="sft")
    ap.add_argument("--te-precision", default="")
    ap.add_argument("--guidance", type=float, default=3.0)
    ap.add_argument("--only", default="")
    ap.add_argument("--out", default="/opt/mossimage/work/e2e")
    ap.add_argument("--device", default="GPU")
    ap.add_argument("--tag", default="")
    ap.add_argument("--te-resident", action="store_true")
    args = ap.parse_args()
    from moss_pipeline import MossImage
    from PIL import Image

    os.makedirs(args.out, exist_ok=True)
    t0 = time.time()
    pipe = MossImage(device=args.device, log=lambda *a: print("[pipe]", *a, flush=True), te_resident=args.te_resident, variant=args.variant,
                     te_precision=args.te_precision or None)
    from moss_pipeline import VARIANTS

    steps = args.steps or VARIANTS[args.variant]["default_steps"]
    init_s = time.time() - t0
    print(f"[init] {time.time() - t0:.1f}s", flush=True)
    want = [x for x in args.only.split(",") if x]
    summary = []
    for name, seed, prompt in PROMPTS:
        if want and name not in want:
            continue
        done = [0]

        def prog(i, n):
            if i % 10 == 0 or i == n:
                print(f"  [{name}] step {i}/{n}  {time.time() - ts:.0f}s", flush=True)

        ts = time.time()
        W, H = (args.width or args.size), (args.height or args.size)
        img, st = pipe.generate(prompt, NEGATIVE, W, H, steps, args.guidance, seed, progress=prog)
        stem = f"{name}{args.tag}_{W}x{H}_s{steps}" if (args.width or args.height) else f"{name}{args.tag}_{args.size}_s{steps}"
        Image.fromarray(img).save(f"{args.out}/{stem}.png")
        side = {"prompt": prompt, "negative_prompt": NEGATIVE, "seed": seed, "steps": steps, "guidance": args.guidance,
                "width": W, "height": H, "model": args.variant, "model_note": MODEL_NOTE.get(args.variant, args.variant), "stats": st, "process_init_s": round(init_s, 1), "first_image_of_process": not summary,
                "host_hwm_gb": round(hwm_gb(), 1)}
        json.dump(side, open(f"{args.out}/{stem}.json", "w"), indent=1, ensure_ascii=False)
        print(f"[done] {stem}: {json.dumps(st)}  host_hwm={hwm_gb():.1f}GB  pixel mean={img.mean():.1f} std={img.std():.1f}", flush=True)
        summary.append({"name": name, **{k: st[k] for k in ("total_s", "denoise_s", "s_per_step", "text_encoder_s", "vae_s", "finite")}})
    json.dump(summary, open(f"{args.out}/summary{args.tag}_{args.size}_s{steps}.json", "w"), indent=1)


if __name__ == "__main__":
    main()