File size: 6,521 Bytes
eabea76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
"""
Pre-compute VAE latents and text embeddings for Flux training.
Removes VAE/CLIP/T5 from GPU during training, saving ~10GB VRAM per GPU.
"""
import argparse
import io
from pathlib import Path

import torch
import webdataset as wds
from PIL import Image
from torchvision import transforms
from tqdm import tqdm


def get_transform(resolution=1024):
    return transforms.Compose([
        transforms.Resize(resolution, interpolation=transforms.InterpolationMode.LANCZOS),
        transforms.CenterCrop(resolution),
        transforms.ToTensor(),
        transforms.Normalize([0.5], [0.5]),
    ])


def main():
    parser = argparse.ArgumentParser(description="Pre-compute embeddings for Flux training")
    parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
    parser.add_argument("--data-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/shards"))
    parser.add_argument("--output-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings"))
    parser.add_argument("--resolution", type=int, default=1024)
    parser.add_argument("--batch-size", type=int, default=8)
    parser.add_argument("--cache-dir", default="/data0/models")
    parser.add_argument("--device", default="cuda:0")
    args = parser.parse_args()

    args.output_dir.mkdir(parents=True, exist_ok=True)
    device = torch.device(args.device)
    transform = get_transform(args.resolution)

    # Load pipeline components
    print("Loading Flux pipeline components...")
    from diffusers import FluxPipeline
    pipe = FluxPipeline.from_pretrained(
        args.model_name,
        torch_dtype=torch.bfloat16,
        cache_dir=args.cache_dir,
    )

    vae = pipe.vae.to(device).eval()
    text_encoder = pipe.text_encoder.to(device).eval()
    text_encoder_2 = pipe.text_encoder_2.to(device).eval()
    tokenizer = pipe.tokenizer
    tokenizer_2 = pipe.tokenizer_2

    vae_shift = vae.config.shift_factor
    vae_scale = vae.config.scaling_factor

    # Find tar shards
    tar_files = sorted(args.data_dir.glob("*.tar"))
    if not tar_files:
        raise ValueError(f"No tar files found in {args.data_dir}")
    print(f"Found {len(tar_files)} shards")

    def decode_sample(sample):
        try:
            img = sample["jpg"]
            if isinstance(img, bytes):
                img = Image.open(io.BytesIO(img)).convert("RGB")
            caption = sample.get("txt", b"")
            if isinstance(caption, bytes):
                caption = caption.decode("utf-8")
            return {"image": transform(img), "caption": caption, "key": sample["__key__"]}
        except:
            return None

    dataset = (
        wds.WebDataset([str(f) for f in tar_files])
        .decode("pil")
        .map(decode_sample)
        .select(lambda x: x is not None)
    )

    dataloader = torch.utils.data.DataLoader(
        dataset, batch_size=None, num_workers=4, pin_memory=True
    )

    # Process in batches
    batch_images = []
    batch_captions = []
    batch_keys = []
    sample_idx = 0
    shard_idx = 0
    shard_data = []
    samples_per_shard = 1000

    print(f"Pre-computing embeddings (batch_size={args.batch_size})...")

    def save_shard(shard_data, shard_idx):
        shard_path = args.output_dir / f"shard-{shard_idx:06d}.pt"
        torch.save(shard_data, shard_path)
        return shard_idx + 1

    def process_batch(images, captions, keys):
        imgs = torch.stack(images).to(device, dtype=torch.bfloat16)

        with torch.no_grad():
            latents = vae.encode(imgs).latent_dist.sample()
            latents = (latents - vae_shift) * vae_scale

            # Pack latents: (B, C, H, W) -> (B, H/2*W/2, C*4)
            b, c, h, w = latents.shape
            packed = latents.view(b, c, h // 2, 2, w // 2, 2)
            packed = packed.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)

            # Text embeddings
            text_ids = tokenizer(
                captions, padding="max_length", max_length=77,
                truncation=True, return_tensors="pt"
            ).input_ids.to(device)
            pooled = text_encoder(text_ids, output_hidden_states=False).pooler_output

            text_ids_2 = tokenizer_2(
                captions, padding="max_length", max_length=256,
                truncation=True, return_tensors="pt"
            ).input_ids.to(device)
            hidden_states = text_encoder_2(text_ids_2)[0]

            # Latent image IDs
            latent_h, latent_w = h // 2, w // 2
            img_ids = torch.zeros(latent_h, latent_w, 3, device=device)
            img_ids[..., 1] = torch.arange(latent_h)[:, None].float()
            img_ids[..., 2] = torch.arange(latent_w)[None, :].float()
            img_ids = img_ids.reshape(latent_h * latent_w, 3)

            # Text IDs
            txt_ids = torch.zeros(hidden_states.shape[1], 3, device=device)

        results = []
        for i in range(b):
            results.append({
                "key": keys[i],
                "packed_latents": packed[i].cpu(),
                "pooled_prompt_embeds": pooled[i].cpu(),
                "encoder_hidden_states": hidden_states[i].cpu(),
                "img_ids": img_ids.cpu(),
                "txt_ids": txt_ids.cpu(),
            })
        return results

    total_processed = 0
    for sample in dataloader:
        batch_images.append(sample["image"])
        batch_captions.append(sample["caption"])
        batch_keys.append(sample["key"])

        if len(batch_images) >= args.batch_size:
            results = process_batch(batch_images, batch_captions, batch_keys)
            shard_data.extend(results)
            total_processed += len(results)

            if len(shard_data) >= samples_per_shard:
                shard_idx = save_shard(shard_data, shard_idx)
                print(f"  Saved shard {shard_idx - 1} ({total_processed} samples total)")
                shard_data = []

            batch_images = []
            batch_captions = []
            batch_keys = []

    # Process remaining
    if batch_images:
        results = process_batch(batch_images, batch_captions, batch_keys)
        shard_data.extend(results)
        total_processed += len(results)

    if shard_data:
        shard_idx = save_shard(shard_data, shard_idx)
        print(f"  Saved shard {shard_idx - 1} ({total_processed} samples total)")

    print(f"\nDone! {total_processed} samples saved to {args.output_dir} ({shard_idx} shards)")


if __name__ == "__main__":
    main()