aqualaguna's picture
Add files using upload-large-folder tool
4a1ea7b verified
Raw History Blame Contribute Delete
6.92 kB
"""CPU float32 reference for the DiT using the ORIGINAL classes of pipeline_moss_image.py, with the 42 blocks
streamed from safetensors one at a time (a full fp32 model would need 20 GB of RAM).
forward_ref() is a line-by-line transliteration of MOSSImageTransformer.forward (batch 1, optional skip_layers).
--selftest builds a tiny random MOSSImageTransformer and checks forward_ref == the original forward (exactly).
Usage: python ref_dit.py [--which sft] [--h 32 --w 32] (writes /opt/mossimage/work/dit_ref_<which>.npz)
"""
import argparse
import sys
import numpy as np
import torch
sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import WORK, Timer # noqa: E402
from dit_ops import DIM, HEADS, NUM_LAYERS, build_layers, dit_store, load_orig_module, _small # noqa: E402
class LazyDiT:
"""Real weights, fp32, blocks built on demand."""
def __init__(self, which="sft"):
self.mod = load_orig_module()
self.st = dit_store(which)
d = torch.float32
self.video_embedder = _small(self.mod, torch.nn.Linear, self.st, "video_embedder.", d, 128, DIM)
self.text_embedder = _small(self.mod, self.mod._TextProjection, self.st, "text_embedder.", d, 4096, DIM, 8192, HEADS)
self.rope = self.mod._RoPE(DIM // HEADS, 10000.0)
self.time_embedding = torch.nn.Sequential(torch.nn.Linear(256, DIM), torch.nn.SiLU(), torch.nn.Linear(DIM, DIM))
for i, key in ((0, "time_embedding.0."), (2, "time_embedding.2.")):
self.time_embedding[i].load_state_dict(
{"weight": torch.from_numpy(self.st.get_f32(key + "weight")), "bias": torch.from_numpy(self.st.get_f32(key + "bias"))}
)
self.shared_block_modulation = torch.nn.Linear(DIM, 6 * DIM)
self.shared_block_modulation.load_state_dict({k: torch.from_numpy(self.st.get_f32("shared_block_modulation." + k)) for k in ("weight", "bias")})
self.video_head_modulation = torch.nn.Linear(DIM, 2 * DIM)
self.video_head_modulation.load_state_dict({k: torch.from_numpy(self.st.get_f32("video_head_modulation." + k)) for k in ("weight", "bias")})
self.final_norm_video = _small(self.mod, self.mod._RMSNorm, self.st, "final_norm_video.", d, DIM)
self.final_linear_video = torch.nn.Linear(DIM, 128, bias=False)
self.final_linear_video.load_state_dict({"weight": torch.from_numpy(self.st.get_f32("final_linear_video.weight"))})
self.num_layers = NUM_LAYERS
def layer(self, i):
return build_layers(self.mod, self.st, [i], torch.float32)[0]
class TinyAdapter:
def __init__(self, model):
self.m = model
self.video_embedder = model.video_embedder
self.text_embedder = model.text_embedder
self.rope = model.rope
self.time_embedding = model.time_embedding
self.shared_block_modulation = model.shared_block_modulation
self.video_head_modulation = model.video_head_modulation
self.final_norm_video = model.final_norm_video
self.final_linear_video = model.final_linear_video
self.num_layers = len(model.layers)
def layer(self, i):
return self.m.layers[i]
@torch.no_grad()
def forward_ref(net, latents, timestep, ctx, skip_layers=(), record=None, freq_dim=256):
"""latents [1,128,h,w] f32, ctx [1,L,4096] f32; returns velocity [1,128,h,w]."""
batch, _, height, width = latents.shape
times = torch.as_tensor(timestep, dtype=torch.float32).reshape(-1).expand(batch)
half = freq_dim // 2
freq = 10000 ** (-torch.arange(half, dtype=torch.float64) / half)
phase = times.double()[:, None] * freq
embedding = torch.cat((phase.cos(), phase.sin()), -1).float()
time = net.time_embedding(embedding).float()
mod = net.shared_block_modulation(time).view(batch, 6, -1)
head = net.video_head_modulation(time).view(batch, 2, -1)
context = ctx
video = latents.flatten(2).transpose(1, 2)
video = net.video_embedder(video.contiguous())
rope = net.rope(height, width, context.shape[1], latents.device)
text = net.text_embedder(context, rope[:, height * width:])
if record is not None:
record["text_refine"] = text.numpy().copy()
x = torch.cat((video, text), 1)
for li in range(net.num_layers):
if li in skip_layers:
continue
layer = net.layer(li)
x = layer(x, rope, mod[0:1])
if record is not None and li in (21, 22):
record[f"after_{li}"] = x.numpy().copy()
del layer
x = net.final_norm_video(x[:, :height * width])
x = x * (1 + head[0:1, 1, None]) + head[0:1, 0, None]
x = net.final_linear_video(x)
return x.transpose(1, 2).reshape(1, -1, height, width)
def selftest():
mod = load_orig_module()
torch.manual_seed(0)
tiny = mod.MOSSImageTransformer(dim=256, ffn_dim=512, num_heads=4, num_layers=4, text_dim=64, freq_dim=32, latent_channels=16)
for p in tiny.parameters():
torch.nn.init.normal_(p, std=0.05)
tiny.eval()
lat = torch.randn(1, 16, 6, 8)
ctx = torch.randn(1, 11, 64)
for skip in ((), (2,)):
want = tiny(lat, torch.tensor([700.0]), ctx, None, skip_layers=skip).sample
got = forward_ref(TinyAdapter(tiny), lat, 700.0, ctx, skip_layers=skip, freq_dim=32)
print("selftest skip", skip, "max abs diff", float((want - got).abs().max()), "ref absmax", float(want.abs().max()))
assert torch.allclose(want, got, atol=1e-6), "forward_ref differs from original forward"
print("selftest OK")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--which", default="sft")
ap.add_argument("--h", type=int, default=32)
ap.add_argument("--w", type=int, default=32)
ap.add_argument("--selftest", action="store_true")
args = ap.parse_args()
torch.set_num_threads(8)
if args.selftest:
selftest()
return
te = np.load(f"{WORK}/te_ref.npz")
ctx_scene = torch.from_numpy(te["scene_f32_part3"])[None]
ctx_empty = torch.from_numpy(te["empty_f32_part3"])[None]
g = torch.Generator().manual_seed(1234)
lat = torch.randn(1, 128, args.h, args.w, generator=g)
net = LazyDiT(args.which)
out = {"latents": lat.numpy(), "ctx_scene": ctx_scene.numpy(), "ctx_empty": ctx_empty.numpy()}
cases = [("A", ctx_scene, 1000.0, ()), ("B", ctx_empty, 500.0, (22,)), ("C", ctx_scene, 100.0, ())]
for name, ctx, t, skip in cases:
rec = {}
with Timer(f"dit ref case {name}"):
v = forward_ref(net, lat, t, ctx, skip, record=rec)
out[f"v_{name}"] = v.numpy()
for k, a in rec.items():
out[f"{k}_{name}"] = a
print(name, "t", t, "skip", skip, "v absmax", float(v.abs().max()), "std", float(v.std()), flush=True)
np.savez(f"{WORK}/dit_ref_{args.which}.npz", **out)
print("saved")
if __name__ == "__main__":
main()