"""第 03 章第 03–04 课实测:75 行手写动态宽高比分桶(ARB)+ 离线 .safetensors 预编码缓存显存与吞吐压测。"""
from __future__ import annotations
import gc
import math
import random
import shutil
import time
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn.functional as F
from diffusers import FlowMatchEulerDiscreteScheduler, SanaPipeline
from peft import LoraConfig, get_peft_model
from PIL import Image
from safetensors.torch import load_file, save_file
from prism_studio_synth import RawStudioSample
class AspectRatioBucketManager:
"""从零手写动态宽高比分桶管理器:像素面积预算对齐 + 64 整数倍步长约束 + 最小对数长宽比分配。"""
def __init__(
self,
base_resolution: int = 1024,
stride: int = 64,
min_aspect: float = 0.5,
max_aspect: float = 2.0,
) -> None:
self.area_budget = base_resolution * base_resolution
self.stride = stride
buckets_set: set[tuple[int, int]] = set()
min_side = int(math.floor(math.sqrt(self.area_budget * min_aspect) / stride)) * stride
max_side = int(math.ceil(math.sqrt(self.area_budget * max_aspect) / stride)) * stride
for w in range(max(stride, min_side), max_side + stride, stride):
h = int(round((self.area_budget / float(w)) / stride)) * stride
h = max(stride, h)
ar = w / float(h)
if min_aspect <= ar <= max_aspect and abs(w * h - self.area_budget) <= self.area_budget * 0.12:
buckets_set.add((w, h))
self.buckets: list[tuple[int, int]] = sorted(buckets_set, key=lambda wh: wh[0] / float(wh[1]))
def assign_bucket(self, width: int, height: int) -> tuple[int, int]:
log_ar = math.log(width / float(height))
return min(self.buckets, key=lambda wh: abs(log_ar - math.log(wh[0] / float(wh[1]))))
def resize_and_micro_crop(self, img: Image.Image) -> tuple[Image.Image, dict[str, float]]:
orig_w, orig_h = img.size
bw, bh = self.assign_bucket(orig_w, orig_h)
scale = max(bw / float(orig_w), bh / float(orig_h))
scaled_w = max(bw, int(round(orig_w * scale)))
scaled_h = max(bh, int(round(orig_h * scale)))
resized = img.resize((scaled_w, scaled_h), Image.Resampling.LANCZOS)
left = (scaled_w - bw) // 2
top = (scaled_h - bh) // 2
cropped = resized.crop((left, top, left + bw, top + bh))
preserved_area_ratio = (bw * bh) / float(scaled_w * scaled_h)
return cropped, {
"orig_w": orig_w,
"orig_h": orig_h,
"bucket_w": bw,
"bucket_h": bh,
"preserved_area_ratio": preserved_area_ratio,
}
class ARBBatchSampler:
"""同桶成批采样器(Homogeneous-Bucket BatchSampler):批内张量形状严格一致,彻底消灭跨宽高比 Padding!"""
def __init__(
self,
bucket_to_indices: dict[tuple[int, int], list[int]],
batch_size: int = 2,
seed: int = 42,
drop_last: bool = False,
) -> None:
self.bucket_to_indices = bucket_to_indices
self.batch_size = batch_size
self.seed = seed
self.drop_last = drop_last
def build_epoch_batches(self, epoch: int = 0) -> list[list[int]]:
rng = random.Random(self.seed + epoch)
batches: list[list[int]] = []
for _, idxs in sorted(self.bucket_to_indices.items()):
local = list(idxs)
rng.shuffle(local)
for start in range(0, len(local), self.batch_size):
chunk = local[start : start + self.batch_size]
if len(chunk) == self.batch_size or not self.drop_last:
batches.append(chunk)
rng.shuffle(batches)
return batches
def audit_center_crop_vs_arb(
clean_samples: list[RawStudioSample],
manager: AspectRatioBucketManager,
) -> dict[str, Any]:
"""定量核验:竖幅海报在传统 1024x1024 Center Crop 下的像素裁切率与首尾标题/铭牌断头率 vs ARB。"""
cc_preserved_ratios: list[float] = []
arb_preserved_ratios: list[float] = []
vertical_cc_header_clipped = 0
vertical_arb_header_clipped = 0
vertical_count = 0
for s in clean_samples:
w, h = s.image.size
# 传统正方形 Resize(short=1024) + CenterCrop(1024)
cc_scale = 1024.0 / float(min(w, h))
cc_sw, cc_sh = int(round(w * cc_scale)), int(round(h * cc_scale))
cc_ratio = (1024.0 * 1024.0) / float(cc_sw * cc_sh)
cc_preserved_ratios.append(cc_ratio)
_, arb_meta = manager.resize_and_micro_crop(s.image)
arb_preserved_ratios.append(arb_meta["preserved_area_ratio"])
if s.has_edge_composition_anchors:
vertical_count += 1
# 顶部品牌标题位于 [0.065 * H, 0.13 * H],计算裁剪上边界是否切入 [0, 0.13 * H]
cc_top_frac = ((cc_sh - 1024.0) / 2.0) / float(cc_sh)
if cc_top_frac > 0.065:
vertical_cc_header_clipped += 1
bw, bh = int(arb_meta["bucket_w"]), int(arb_meta["bucket_h"])
arb_scale = max(bw / float(w), bh / float(h))
arb_sh = int(round(h * arb_scale))
arb_top_frac = ((arb_sh - bh) / 2.0) / float(arb_sh)
if arb_top_frac > 0.065:
vertical_arb_header_clipped += 1
return {
"num_candidate_buckets": len(manager.buckets),
"candidate_buckets_wh": [f"{w}x{h}" for w, h in manager.buckets],
"square_center_crop_mean_preserved_area": round(sum(cc_preserved_ratios) / len(cc_preserved_ratios), 4),
"square_center_crop_min_preserved_area": round(min(cc_preserved_ratios), 4),
"arb_mean_preserved_area": round(sum(arb_preserved_ratios) / len(arb_preserved_ratios), 4),
"arb_min_preserved_area": round(min(arb_preserved_ratios), 4),
"vertical_poster_count": vertical_count,
"square_center_crop_decapitation_rate": round(vertical_cc_header_clipped / max(1, vertical_count), 4),
"arb_decapitation_rate": round(vertical_arb_header_clipped / max(1, vertical_count), 4),
}
def _pil_to_norm_tensor(img: Image.Image) -> torch.Tensor:
arr = np.asarray(img, dtype=np.float32) / 127.5 - 1.0
return torch.from_numpy(arr).permute(2, 0, 1).contiguous()
def run_arb_and_safetensors_cache_benchmark(
clean_samples: list[RawStudioSample],
captions: dict[str, str],
device: torch.device,
) -> dict[str, Any]:
"""落地离线 .safetensors 预编码器,并在 L4 上实测对比「在线编码直训」vs「离线缓存直训」的显存与单步延迟。"""
manager = AspectRatioBucketManager(base_resolution=1024, stride=64)
crop_vs_arb = audit_center_crop_vs_arb(clean_samples, manager)
# 1. ARB 分配与同桶采样核验
prepared_items: list[dict[str, Any]] = []
bucket_map: dict[tuple[int, int], list[int]] = {}
for idx, s in enumerate(clean_samples):
cropped_img, meta = manager.resize_and_micro_crop(s.image)
b_wh = (int(meta["bucket_w"]), int(meta["bucket_h"]))
bucket_map.setdefault(b_wh, []).append(idx)
prepared_items.append({
"sample_id": s.sample_id,
"image": cropped_img,
"pixel_tensor": _pil_to_norm_tensor(cropped_img),
"caption": captions[s.sample_id],
"bucket_wh": b_wh,
})
sampler = ARBBatchSampler(bucket_map, batch_size=2, seed=42, drop_last=False)
batches = sampler.build_epoch_batches(epoch=0)
for b_idxs in batches:
shapes = {prepared_items[i]["pixel_tensor"].shape for i in b_idxs}
assert len(shapes) == 1, f"ARB 批内出现不同形状张量: {shapes}"
# 2. 加载真实 Sana-600M 全套管线(AutoencoderDC + Gemma-2-2B + SanaTransformer2DModel)
model_id = "Efficient-Large-Model/Sana_600M_1024px_diffusers"
pipe = SanaPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(device)
pipe.vae.requires_grad_(False).eval()
pipe.text_encoder.requires_grad_(False).eval()
pipe.transformer.requires_grad_(False)
pipe.transformer.enable_gradient_checkpointing()
lora_cfg = LoraConfig(
r=16,
lora_alpha=16,
target_modules=["to_q", "to_k", "to_v", "to_out.0"],
)
pipe.transformer = get_peft_model(pipe.transformer, lora_cfg)
pipe.transformer.train()
flow_sched = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=3.0)
scaling_factor = float(pipe.vae.config.scaling_factor)
# 3. 离线预编码全部 16 条样本并写入 .safetensors 磁盘分片
cache_dir = Path("/tmp/prism_v03_safetensors_cache")
if cache_dir.exists():
shutil.rmtree(cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
t_pre0 = time.perf_counter()
with torch.no_grad():
for idx, item in enumerate(prepared_items):
pix = item["pixel_tensor"].unsqueeze(0).to(device=device, dtype=torch.bfloat16)
vae_out = pipe.vae.encode(pix)
latent = (vae_out.latent if hasattr(vae_out, "latent") else vae_out.latent_dist.sample()) * scaling_factor
p_embeds, p_mask, _, _ = pipe.encode_prompt(
prompt=item["caption"],
do_classifier_free_guidance=False,
device=device,
clean_caption=False,
)
shard_path = cache_dir / f"sample_{idx:03d}.safetensors"
save_file(
{
"latent": latent.squeeze(0).contiguous().cpu(),
"prompt_embeds": p_embeds.squeeze(0).contiguous().cpu(),
"prompt_attention_mask": p_mask.squeeze(0).to(torch.int64).contiguous().cpu(),
},
str(shard_path),
metadata={
"sample_id": item["sample_id"],
"bucket_wh": f"{item['bucket_wh'][0]}x{item['bucket_wh'][1]}",
},
)
item["shard_path"] = shard_path
torch.cuda.synchronize(device)
precache_wall_sec = time.perf_counter() - t_pre0
total_cache_mib = sum(p.stat().st_size for p in cache_dir.glob("*.safetensors")) / float(1024 * 1024)
# 4A. 基准 A:传统「在线编码直训」(VAE + Gemma-2-2B 常驻显存,每步现算潜变量与文本嵌入)
trainable_params = [p for p in pipe.transformer.parameters() if p.requires_grad]
opt_online = torch.optim.AdamW(trainable_params, lr=1e-4)
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
online_step_ms: list[float] = []
num_bench_steps = 16
for step in range(num_bench_steps):
b_idxs = batches[step % len(batches)]
torch.cuda.synchronize(device)
t0 = time.perf_counter()
opt_online.zero_grad(set_to_none=True)
with torch.no_grad():
pix_batch = torch.stack([prepared_items[i]["pixel_tensor"] for i in b_idxs]).to(device, dtype=torch.bfloat16)
v_out = pipe.vae.encode(pix_batch)
latents = (v_out.latent if hasattr(v_out, "latent") else v_out.latent_dist.sample()) * scaling_factor
p_emb, p_msk, _, _ = pipe.encode_prompt(
prompt=[prepared_items[i]["caption"] for i in b_idxs],
do_classifier_free_guidance=False,
device=device,
clean_caption=False,
)
bsz = latents.shape[0]
idx_t = torch.randint(100, 900, (bsz,), device=device)
timesteps = flow_sched.timesteps[idx_t.cpu()].to(device)
sigmas = flow_sched.sigmas[idx_t.cpu()].to(device=device, dtype=latents.dtype).view(bsz, 1, 1, 1)
noise = torch.randn_like(latents)
z_t = (1.0 - sigmas) * latents + sigmas * noise
vel_pred = pipe.transformer(
hidden_states=z_t,
timestep=timesteps,
encoder_hidden_states=p_emb,
encoder_attention_mask=p_msk,
return_dict=False,
)[0]
loss = F.mse_loss(vel_pred.float(), (noise - latents).float())
loss.backward()
opt_online.step()
torch.cuda.synchronize(device)
if step >= 2:
online_step_ms.append((time.perf_counter() - t0) * 1000.0)
online_peak_vram_mib = round(torch.cuda.max_memory_allocated(device) / float(1024 * 1024), 1)
del opt_online
# 4B. 基准 B:卸载并彻底释放 VAE + Gemma-2-2B,直接从 .safetensors 分片零拷贝流式训练!
transformer_only = pipe.transformer
pipe.vae = None
pipe.text_encoder = None
pipe.tokenizer = None
del pipe
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats(device)
opt_cached = torch.optim.AdamW([p for p in transformer_only.parameters() if p.requires_grad], lr=1e-4)
cached_step_ms: list[float] = []
for step in range(num_bench_steps):
b_idxs = batches[step % len(batches)]
torch.cuda.synchronize(device)
t0 = time.perf_counter()
opt_cached.zero_grad(set_to_none=True)
shards = [load_file(str(prepared_items[i]["shard_path"])) for i in b_idxs]
latents = torch.stack([s["latent"] for s in shards]).to(device, dtype=torch.bfloat16)
p_emb = torch.stack([s["prompt_embeds"] for s in shards]).to(device, dtype=torch.bfloat16)
p_msk = torch.stack([s["prompt_attention_mask"] for s in shards]).to(device)
bsz = latents.shape[0]
idx_t = torch.randint(100, 900, (bsz,), device=device)
timesteps = flow_sched.timesteps[idx_t.cpu()].to(device)
sigmas = flow_sched.sigmas[idx_t.cpu()].to(device=device, dtype=latents.dtype).view(bsz, 1, 1, 1)
noise = torch.randn_like(latents)
z_t = (1.0 - sigmas) * latents + sigmas * noise
vel_pred = transformer_only(
hidden_states=z_t,
timestep=timesteps,
encoder_hidden_states=p_emb,
encoder_attention_mask=p_msk,
return_dict=False,
)[0]
loss = F.mse_loss(vel_pred.float(), (noise - latents).float())
loss.backward()
opt_cached.step()
torch.cuda.synchronize(device)
if step >= 2:
cached_step_ms.append((time.perf_counter() - t0) * 1000.0)
cached_peak_vram_mib = round(torch.cuda.max_memory_allocated(device) / float(1024 * 1024), 1)
vram_saved_mib = round(online_peak_vram_mib - cached_peak_vram_mib, 1)
vram_saved_pct = round((vram_saved_mib / online_peak_vram_mib) * 100.0, 2)
online_mean_ms = sum(online_step_ms) / len(online_step_ms)
cached_mean_ms = sum(cached_step_ms) / len(cached_step_ms)
assert vram_saved_pct > 45.0, f"预编码显存节省比例未达 >45% 门禁: {vram_saved_pct}%"
shutil.rmtree(cache_dir, ignore_errors=True)
del opt_cached, transformer_only
gc.collect()
torch.cuda.empty_cache()
return {
"center_crop_vs_arb": crop_vs_arb,
"arb_bucket_distribution": {
f"{w}x{h}": len(idxs) for (w, h), idxs in sorted(bucket_map.items())
},
"arb_homogeneous_batches_count": len(batches),
"cross_aspect_padding_tokens": 0,
"safetensors_precacher_benchmark": {
"backbone": model_id,
"num_cached_shards": len(prepared_items),
"total_cache_disk_mib": round(total_cache_mib, 2),
"one_time_precache_wall_sec": round(precache_wall_sec, 2),
"online_encoding_peak_vram_mib": online_peak_vram_mib,
"offline_cached_peak_vram_mib": cached_peak_vram_mib,
"vram_saved_mib": vram_saved_mib,
"vram_saved_pct": vram_saved_pct,
"online_step_latency_ms": round(online_mean_ms, 2),
"offline_cached_step_latency_ms": round(cached_mean_ms, 2),
"step_speedup_ratio": round(online_mean_ms / max(1e-5, cached_mean_ms), 2),
},
}