File size: 10,339 Bytes
02443ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
from __future__ import annotations

import argparse
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import sys
import time

import torch


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from anima_style_probe.factor_interventions import apply_intervention  # noqa: E402
from anima_style_probe.feature_parts import completed_part_records, write_feature_part  # noqa: E402
from anima_style_probe.image_preprocess import image_tensor  # noqa: E402
from anima_style_probe.style_dataset import (  # noqa: E402
    assigned_shards,
    iter_prefetched_batches,
    iter_style_samples,
)
from extract_style_backbone_features import (  # noqa: E402
    compact_feature_map,
    forward_intermediates,
    load_model,
)


def read_jsonl(path: Path) -> list[dict]:
    with path.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def save_image_atomic(image, path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.is_file():
        return
    temporary = path.with_suffix(path.suffix + ".tmp")
    image.save(temporary, format="WEBP", quality=90, method=4)
    temporary.replace(path)


def flush_part(
    output_dir: Path,
    worker_index: int,
    part_index: int,
    full: list[torch.Tensor],
    face: list[torch.Tensor],
    face_mask: list[torch.Tensor],
    records: list[dict],
    *,
    manifest_sha256: str,
    layer_indices: list[int],
) -> None:
    write_feature_part(
        output_dir,
        "intervention",
        worker_index,
        part_index,
        {
            "full": torch.cat(full).to(torch.bfloat16),
            "face": torch.cat(face).to(torch.bfloat16),
            "face_mask": torch.cat(face_mask).to(torch.bool),
        },
        {
            "kind": "factor_intervention_full_face",
            "backbone": "siglip2_so400m",
            "layer_indices": layer_indices,
            "manifest_sha256": manifest_sha256,
            "records": records,
        },
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="Extract resumable factor-intervention features.")
    parser.add_argument("--dataset-root", type=Path, required=True)
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--worker-index", type=int, required=True)
    parser.add_argument("--num-workers", type=int, default=4)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--source-batch-size", type=int, default=16)
    parser.add_argument("--decode-workers", type=int, default=16)
    parser.add_argument("--part-size", type=int, default=4096)
    parser.add_argument("--image-size", type=int, default=512)
    parser.add_argument("--mode", choices=("panel", "full"), default="full")
    parser.add_argument("--panel-dir", type=Path)
    parser.add_argument("--anima-pilot-dir", type=Path)
    args = parser.parse_args()
    if min(args.batch_size, args.source_batch_size, args.decode_workers, args.part_size) < 1:
        raise ValueError("batch and worker sizes must be positive")
    if not torch.cuda.is_available():
        raise RuntimeError("CUDA is required")

    manifest_sha256 = hashlib.sha256(args.manifest.read_bytes()).hexdigest()
    rows = read_jsonl(args.manifest)
    if args.mode == "panel":
        rows = [row for row in rows if row.get("panel")]
    worker_shards = {
        path.name
        for path in assigned_shards(args.dataset_root, args.worker_index, args.num_workers)
    }
    rows = [row for row in rows if row["shard"] in worker_shards]
    by_source: dict[str, list[dict]] = defaultdict(list)
    for row in rows:
        by_source[row["source_record_id"]].append(row)

    completed, part_index = completed_part_records(
        args.output_dir, "intervention", args.worker_index
    )
    for path in args.output_dir.glob(f"intervention-w{args.worker_index}-p*.json"):
        metadata = json.loads(path.read_text(encoding="utf-8"))
        if metadata.get("manifest_sha256") != manifest_sha256:
            raise RuntimeError(f"manifest mismatch with completed part: {path}")
    pending_by_source = {
        source_id: [row for row in variants if row["record_id"] not in completed]
        for source_id, variants in by_source.items()
    }
    pending_by_source = {key: value for key, value in pending_by_source.items() if value}

    device = torch.device("cuda")
    dtype = torch.bfloat16
    model, depth = load_model("siglip2_so400m", device, dtype)
    layer_indices = [round(0.25 * (depth - 1)), round(0.55 * (depth - 1)), depth - 1]
    decode_pool = ThreadPoolExecutor(
        max_workers=args.decode_workers, thread_name_prefix="intervention"
    )
    started = time.perf_counter()
    processed = 0
    full_parts: list[torch.Tensor] = []
    face_parts: list[torch.Tensor] = []
    mask_parts: list[torch.Tensor] = []
    part_records: list[dict] = []
    feature_buffer: list[tuple[torch.Tensor, torch.Tensor, bool, dict]] = []

    def decode_source(sample):
        decoded = []
        for spec in pending_by_source[sample.metadata["record_id"]]:
            full_image, face_image = apply_intervention(
                sample.full_bytes,
                sample.face_bytes,
                sample.metadata,
                spec,
                size=args.image_size,
            )
            if args.panel_dir is not None and spec.get("panel"):
                save_image_atomic(
                    full_image,
                    args.panel_dir / spec["source"] / spec["factor"] / f"{spec['record_id']}.webp",
                )
            if args.anima_pilot_dir is not None and spec.get("anima_pilot"):
                save_image_atomic(full_image, args.anima_pilot_dir / f"{spec['record_id']}.webp")
            full_tensor = image_tensor(full_image)
            face_tensor = torch.zeros_like(full_tensor) if face_image is None else image_tensor(face_image)
            record = {
                **spec,
                "source_shard": sample.shard,
                "content_id": sample.metadata.get("content_id") or sample.metadata.get("cell_id"),
                "seed": sample.metadata.get("seed"),
                "face_present": face_image is not None,
            }
            decoded.append((full_tensor, face_tensor, face_image is not None, record))
        return decoded

    def process_features(batch) -> None:
        nonlocal processed, part_index, full_parts, face_parts, mask_parts, part_records
        full_pixels, face_pixels, masks, records = map(list, zip(*batch, strict=True))
        pixels = torch.cat((torch.stack(full_pixels), torch.stack(face_pixels))).to(
            device=device, dtype=dtype
        )
        with torch.inference_mode(), torch.autocast("cuda", dtype=dtype):
            maps = forward_intermediates(model, "siglip2_so400m", pixels, layer_indices)
            compact = torch.cat(
                [
                    compact_feature_map(value, pool)
                    for value, pool in zip(maps, (2, 4, 2), strict=True)
                ],
                dim=1,
            ).to(device="cpu", dtype=torch.bfloat16)
        size = len(batch)
        full_parts.append(compact[:size])
        face_parts.append(compact[size:])
        mask_parts.append(torch.tensor(masks, dtype=torch.bool))
        part_records.extend(records)
        processed += size
        if len(part_records) >= args.part_size:
            flush_part(
                args.output_dir,
                args.worker_index,
                part_index,
                full_parts,
                face_parts,
                mask_parts,
                part_records,
                manifest_sha256=manifest_sha256,
                layer_indices=layer_indices,
            )
            part_index += 1
            full_parts, face_parts, mask_parts, part_records = [], [], [], []
        print(
            json.dumps(
                {
                    "worker": args.worker_index,
                    "new_records": processed,
                    "expected": len(rows),
                    "already_complete": len(completed),
                    "elapsed_seconds": round(time.perf_counter() - started, 1),
                }
            ),
            flush=True,
        )

    try:
        samples = iter_style_samples(
            args.dataset_root,
            worker_index=args.worker_index,
            num_workers=args.num_workers,
            include_record_ids=set(pending_by_source),
        )
        for source_batch in iter_prefetched_batches(samples, args.source_batch_size):
            for group in decode_pool.map(decode_source, source_batch):
                feature_buffer.extend(group)
                while len(feature_buffer) >= args.batch_size:
                    process_features(feature_buffer[: args.batch_size])
                    del feature_buffer[: args.batch_size]
        if feature_buffer:
            process_features(feature_buffer)
    finally:
        decode_pool.shutdown()

    if part_records:
        flush_part(
            args.output_dir,
            args.worker_index,
            part_index,
            full_parts,
            face_parts,
            mask_parts,
            part_records,
            manifest_sha256=manifest_sha256,
            layer_indices=layer_indices,
        )
    if processed + len(completed) != len(rows):
        raise RuntimeError(
            f"worker coverage mismatch: {processed} + {len(completed)} != {len(rows)}"
        )
    summary = {
        "status": "complete",
        "mode": args.mode,
        "worker_index": args.worker_index,
        "manifest_sha256": manifest_sha256,
        "records": len(rows),
        "already_complete": len(completed),
        "new_records": processed,
        "elapsed_seconds": time.perf_counter() - started,
        "peak_vram_bytes": torch.cuda.max_memory_allocated(),
    }
    path = args.output_dir / f"intervention-worker-{args.worker_index}.json"
    path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(summary, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())