File size: 3,378 Bytes
8ba5a96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
make_text_table.py —— 把池子里出现过的所有 prompt 串缓存成 UMT5 文本表

训练时不再挂 11 GB 的 UMT5:DiT 直接查这张表。
表必须覆盖池里每一个 prompt 串,缺一个训练就会在中途 KeyError。

串的分组(与旧交付一致):
    bare          9 条    场景 dropout 后的裸串(9 个动作)
    scene_action  ≤162 条 18 场景 × 9 动作里实际出现过的组合
    trigger_*     转场语料的从句(burn / hardcut),由 burn_corpus.py 追加
"""
from __future__ import annotations

import argparse
import glob
import os
import sys
import time

import torch

sys.path.insert(0, "/nfs/zhiyangdeng/Incantation/wan")      # 只读:modules.t5

CKPT = "/data/zhiyangdeng/wan_base/Wan2.2-TI2V-5B"


def collect(latent_dir: str) -> list[str]:
    need = set()
    files = sorted(glob.glob(os.path.join(latent_dir, "clip_*.pt")))
    for i, f in enumerate(files):
        d = torch.load(f, map_location="cpu", weights_only=False)
        need.update(d["prompts"])
        need.update(d["prompts_bossdrop"])
        if (i + 1) % 2000 == 0:
            print(f"  扫描 {i+1:,}/{len(files):,} ... 当前 {len(need):,} 个不同串", flush=True)
    return sorted(need)


def main():
    ap = argparse.ArgumentParser(description="UMT5 文本表")
    ap.add_argument("--latent", default="/data/zhiyangdeng/data_eybx/latent/pool")
    ap.add_argument("--out", default=None, help="默认 <latent>/../text_table_eybx.pt")
    ap.add_argument("--extra", nargs="*", default=[], help="额外要加入的串(转场语料)")
    ap.add_argument("--t5_pth", default=os.path.join(CKPT, "models_t5_umt5-xxl-enc-bf16.pth"))
    ap.add_argument("--tok", default=os.path.join(CKPT, "google/umt5-xxl"))
    ap.add_argument("--text_len", type=int, default=512)
    ap.add_argument("--batch", type=int, default=16)
    ap.add_argument("--device", default="cuda")
    args = ap.parse_args()

    out = args.out or os.path.join(os.path.dirname(args.latent.rstrip("/")),
                                   "text_table_eybx.pt")
    print("扫描池里的 prompt 串 ...", flush=True)
    keys = collect(args.latent)
    for e in args.extra:
        if e not in keys:
            keys.append(e)
    keys = sorted(set(keys))
    print(f"{len(keys):,} 个不同串 -> {out}", flush=True)

    from modules.t5 import T5EncoderModel
    t5 = T5EncoderModel(text_len=args.text_len, dtype=torch.bfloat16, device=args.device,
                        checkpoint_path=args.t5_pth, tokenizer_path=args.tok)
    table = {}
    t0 = time.time()
    for i in range(0, len(keys), args.batch):
        chunk = keys[i:i + args.batch]
        with torch.no_grad():
            outs = t5(chunk, args.device)
        for k, v in zip(chunk, outs):
            # 统一 pad 到 text_len,训练侧直接 stack
            e = torch.zeros(args.text_len, v.shape[-1], dtype=torch.bfloat16)
            e[:v.shape[0]] = v.to(torch.bfloat16).cpu()
            table[k] = e
        if (i // args.batch) % 20 == 0:
            el = time.time() - t0
            print(f"  {i+len(chunk):,}/{len(keys):,} · {el/60:.1f} min", flush=True)
    torch.save(table, out)
    sz = os.path.getsize(out) / 1e9
    print(f"DONE  {len(table):,} 键 · {sz:.2f} GB -> {out}")


if __name__ == "__main__":
    main()