MOSS-Image-Edit-OpenVINO / code /ref_te_long.py
aqualaguna's picture
Add files using upload-large-folder tool
4a1ea7b verified
Raw History Blame Contribute Delete
2.1 kB
"""CPU fp32 reference of the text encoder for LONG prompts (the JSON layout prompt of moss_gen.py, ~300 tokens, and a ~1500-token
synthetic prompt) -> /opt/mossimage/work/te_ref_long.npz. Same streaming scheme as ref_te.py (one layer in memory at a time), fp32 only.
Usage: python ref_te_long.py
"""
import json
import sys
import numpy as np
import torch
sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import HF, TE_DIR, WORK, ST, Timer, render_prompt, text_rope # noqa: E402
from moss_gen import LAYOUT # noqa: E402
from ref_te import run # noqa: E402
LONG = " ".join(
f"Section {i}: a detailed description of a scene with a wooden table, a ceramic cup of tea, a window with morning light and a small plant, "
f"the sign on the wall reads \"OPEN {i}\"." for i in range(1, 36))
PROMPTS = {"layout": json.dumps(LAYOUT, ensure_ascii=False), "long": LONG}
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--dtypes", default="f32,bf16")
args = ap.parse_args()
from transformers import AutoTokenizer
torch.set_num_threads(8)
tok = AutoTokenizer.from_pretrained(f"{HF['sft']}/tokenizer")
st = ST(TE_DIR, "model.safetensors.index.json")
emb_table = st.get_f32("language_model.embed_tokens.weight")
res = {}
for name, text in PROMPTS.items():
ids = tok(render_prompt(tok, text), return_tensors="np")["input_ids"][0]
print(name, "tokens:", len(ids), flush=True)
embeds = emb_table[ids]
cos, sin = text_rope(len(ids))
res[f"{name}_ids"] = ids
res[f"{name}_embeds"] = embeds
for dn in args.dtypes.split(","):
with Timer(f"ref {name} {dn}"):
outs, absmax = run(dn, ids, embeds, cos, sin, st)
for k, v in outs.items():
res[f"{name}_{dn}_{k}"] = v
print(f"{name} {dn} residual absmax max {max(absmax):.1f}", flush=True)
np.savez(f"{WORK}/te_ref_long.npz", **res)
print("saved te_ref_long.npz")
if __name__ == "__main__":
main()