File size: 6,567 Bytes
dadc4db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
"""CPU fp32 loader for dflow_2b + the 4-step LoRA + dinac3_96 decoder.

The release refuses non-CUDA devices, so this drives its own modules directly.
Autocast is disabled by pointing the packages' compute dtypes at float32
(CPU autocast rejects float32 and turns itself off).
"""
from __future__ import annotations

import math
import sys
import warnings
from pathlib import Path

import torch

SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad")
REL = SP / "repos/dflow_2b"
VAE_DIR = SP / "repos/dinac3_96"
TE_DIR = REL / "text_encoder"
DIT = SP / "w/dit.safetensors"
LORA = SP / "w/lora.safetensors"

sys.path.insert(0, str(REL))
sys.path.insert(0, str(VAE_DIR))
warnings.filterwarnings("ignore", message=".*CPU autocast.*")
warnings.filterwarnings("ignore", message=".*autocast.*not supported.*")

import dflow.modeling as mdl  # noqa: E402
import dflow.text_conditioning as tc_mod  # noqa: E402
import dflow.text_encoder as te_mod  # noqa: E402
from safetensors import safe_open  # noqa: E402

te_mod.COMPUTE_DTYPE = torch.float32
tc_mod.COMPUTE_DTYPE = torch.float32
mdl.AUTOCAST_DTYPE = torch.float32

from dflow.configuration import DFLOW_2B_CONFIG  # noqa: E402
from dflow.modeling import DFlowModel  # noqa: E402
from dflow.schedules import (  # noqa: E402
    ScheduleKind,
    TimeSchedule,
    build_timesteps,
    resolution_log_snr_shift,
)
from dflow.text_conditioning import TextAdapter  # noqa: E402
from dflow.text_encoder import T5Gemma2Encoder  # noqa: E402
from dflow.tokenization import PromptTokenizer  # noqa: E402
from dflow.types import DFlowPath, TextConditioning  # noqa: E402

CPU = torch.device("cpu")
GROUPS = ("prefix_layers", "middle_layers", "suffix_layers")
PROJ = ("attn.qkv", "attn.proj_out", "mlp.up", "mlp.down")


def _f32(module: torch.nn.Module) -> None:
    for t in (*module.parameters(), *module.buffers()):
        t.data = t.data.float()


def load_denoiser(*, lora: bool = True, prefixes: tuple[str, ...] | None = None
                  ) -> tuple[DFlowModel, TextAdapter]:
    """fp32 denoiser (LoRA merged in fp32) and the text adapter.

    ``prefixes`` loads only denoiser tensors whose names start with one of them
    (the rest stay on the meta device), to keep export processes small.
    """
    den: dict[str, torch.Tensor] = {}
    ada: dict[str, torch.Tensor] = {}
    with safe_open(str(DIT), framework="pt") as f:
        for k in f.keys():
            if k.startswith("denoiser."):
                name = k.removeprefix("denoiser.")
                if prefixes is not None and not name.startswith(prefixes):
                    continue
                den[name] = f.get_tensor(k).float()
                continue
            t = f.get_tensor(k).float()
            if k.startswith("denoiser."):
                den[k.removeprefix("denoiser.")] = t
            elif k.startswith("text_adapter."):
                ada[k.removeprefix("text_adapter.")] = t
            else:
                raise KeyError(k)
    if lora:
        merged = 0
        with safe_open(str(LORA), framework="pt") as f:
            keys = set(f.keys())
            for grp in GROUPS:
                depth = getattr(DFLOW_2B_CONFIG, grp.replace("_layers", "_depth"))
                for i in range(depth):
                    for proj in PROJ:
                        base = None
                        for cand in (f"denoiser.{grp}.{i}.{proj}", f"{grp}.{i}.{proj}"):
                            if f"{cand}.lora_down.weight" in keys:
                                base = cand
                        if base is None:
                            continue
                        down = f.get_tensor(f"{base}.lora_down.weight").double()
                        up = f.get_tensor(f"{base}.lora_up.weight").double()
                        rank = down.shape[0]
                        alpha = (float(f.get_tensor(f"{base}.alpha"))
                                 if f"{base}.alpha" in keys else float(rank))
                        if f"{grp}.{i}.{proj}.weight" not in den:
                            merged += 1
                            continue
                        w = den[f"{grp}.{i}.{proj}.weight"]
                        den[f"{grp}.{i}.{proj}.weight"] = (
                            w.double() + (alpha / rank) * (up @ down)).float()
                        merged += 1
        assert merged == 30 * 4, merged
    with torch.device("meta"):
        model = DFlowModel(DFLOW_2B_CONFIG)
    model.load_state_dict(den, strict=prefixes is None, assign=True)
    model.eval().requires_grad_(False)
    adapter = TextAdapter()
    adapter.load_state_dict(ada, strict=True)
    adapter.float().eval().requires_grad_(False)
    return model, adapter


def load_text_encoder() -> tuple[PromptTokenizer, T5Gemma2Encoder]:
    tok = PromptTokenizer.from_directory(TE_DIR)
    enc = T5Gemma2Encoder.from_directory(TE_DIR, device=CPU)
    _f32(enc)
    return tok, enc.eval().requires_grad_(False)


def load_vae():
    from dinac3 import Dinac3
    from dinac3.config import Dinac3Config
    from safetensors.torch import load_file

    cfg = Dinac3Config.load(VAE_DIR / "config.json")
    with torch.device("meta"):
        vae = Dinac3(cfg)
    vae.load_state_dict(load_file(str(VAE_DIR / "model.safetensors")), strict=True, assign=True)
    for t in (*vae.parameters(), *vae.buffers()):
        t.data = t.data.float()
    vae.compute_dtype = torch.float32
    vae.eval().requires_grad_(False)
    vae.decoder.conv_up_head.fold_kernels()
    vae._encode_call = vae.encoder.forward
    vae._decode_call = vae.decoder.forward
    return vae


def gain_for(width: int, height: int) -> float:
    area = float(width) * float(height)
    if area <= 1.05e6:
        return -0.03
    frac = math.log(area / 1.05e6) / math.log(2.5e6 / 1.05e6)
    return -0.03 * max(0.0, 1.0 - frac)


def timesteps(width: int, height: int, steps: int = 4) -> torch.Tensor:
    return build_timesteps(
        TimeSchedule(kind=ScheduleKind.BETA_1_25, steps=steps),
        log_snr_shift=resolution_log_snr_shift(width, height),
        finite_noisy_endpoint=False,
        device=CPU,
    )


def text_conditioning(tok, enc, adapter, prompt: str) -> tuple[list[int], torch.Tensor]:
    ids = list(tok.tokenize(prompt).ids)
    taps = enc(torch.tensor([ids], dtype=torch.int64), weighting=None)
    return ids, adapter.conditioning_tokens(taps)


__all__ = [
    "DFlowPath", "TextConditioning", "load_denoiser", "load_text_encoder", "load_vae",
    "gain_for", "timesteps", "text_conditioning", "SP",
]