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")) sys.path.insert(0, str(ROOT / "scripts")) 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 PREPROCESS_VERSION, image_tensor # noqa: E402 from anima_style_probe.style_dataset import ( # noqa: E402 assigned_shards, iter_prefetched_batches, iter_style_samples, ) from extract_anima_feature_parts import encode_independent_stills # noqa: E402 from extract_anima_introspective import configure_comfy # noqa: E402 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 flush_part( output_dir: Path, worker_index: int, part_index: int, features: list[torch.Tensor], records: list[dict], *, blocks: list[int], sigma: float, noise_seed: int, manifest_sha256: str, selection: str, ) -> None: write_feature_part( output_dir, "anima", worker_index, part_index, {"features": torch.cat(features).to(torch.bfloat16)}, { "kind": f"factor_intervention_anima_{selection}", "blocks": blocks, "sigma": sigma, "noise_seed": noise_seed, "preprocess_version": PREPROCESS_VERSION, "transform_resolution": 768, "manifest_sha256": manifest_sha256, "records": records, }, ) def main() -> int: parser = argparse.ArgumentParser(description="Extract transformed-Anima pilot features.") parser.add_argument("--comfy-root", type=Path, required=True) parser.add_argument("--config", type=Path, required=True) 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=64) parser.add_argument("--source-batch-size", type=int, default=8) parser.add_argument("--decode-workers", type=int, default=8) parser.add_argument("--part-size", type=int, default=1024) parser.add_argument("--image-size", type=int, default=768) parser.add_argument("--blocks", type=int, nargs="+", default=[8, 18, 26]) parser.add_argument("--sigma", type=float, default=0.1) parser.add_argument("--noise-seed", type=int, default=20260715) parser.add_argument("--selection", choices=("pilot", "train", "all"), default="pilot") 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 args.image_size != 768: raise ValueError("the Anima pilot is locked to 768x768") config = json.loads(args.config.read_text(encoding="utf-8")) manifest_sha256 = hashlib.sha256(args.manifest.read_bytes()).hexdigest() all_rows = read_jsonl(args.manifest) if args.selection == "pilot": rows = [row for row in all_rows if row.get("anima_pilot")] elif args.selection == "train": rows = [row for row in all_rows if row.get("split") == "train"] else: rows = all_rows 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[str(row["source_record_id"])].append(row) completed, part_index = completed_part_records( args.output_dir, "anima", args.worker_index ) for path in args.output_dir.glob(f"anima-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} nodes, model_management = configure_comfy(args.comfy_root) if not torch.cuda.is_available(): raise RuntimeError("CUDA is required") run_started = time.perf_counter() torch.cuda.reset_peak_memory_stats() vae = nodes.VAELoader().load_vae(config["comfy"]["vae_name"])[0] clip = nodes.CLIPLoader().load_clip( config["comfy"]["clip_name"], config["comfy"].get("clip_type", "stable_diffusion"), "default", )[0] empty_conditioning = nodes.CLIPTextEncode().encode(clip, "")[0] if len(empty_conditioning) != 1: raise RuntimeError("expected one empty-prompt conditioning item") raw_cross, raw_metadata = empty_conditioning[0] raw_ids = raw_metadata["t5xxl_ids"].flatten().detach().cpu() raw_weights = raw_metadata["t5xxl_weights"].flatten().detach().cpu() raw_cross = raw_cross.detach().cpu() del clip model_management.unload_all_models() model_management.soft_empty_cache() model = nodes.UNETLoader().load_unet(config["comfy"]["unet_name"], "default")[0] model_management.load_models_gpu([model]) device = model.load_device dtype = model.model.get_dtype_inference() diffusion_model = model.model.diffusion_model block_indices = [block - 1 for block in args.blocks] if min(block_indices) < 0 or max(block_indices) >= len(diffusion_model.blocks): raise ValueError(f"invalid blocks for {len(diffusion_model.blocks)}-block Anima model") with torch.inference_mode(): context = diffusion_model.preprocess_text_embeds( raw_cross.to(device=device, dtype=dtype), raw_ids.unsqueeze(0).to(device=device), t5xxl_weights=raw_weights.unsqueeze(0).unsqueeze(-1).to( device=device, dtype=dtype ), ) captured: dict[int, list[torch.Tensor]] = {} def capture(block: int): def hook(_module, _inputs, output): spatial_dims = tuple(range(1, output.ndim - 1)) value = output.detach().float() mean = value.mean(dim=spatial_dims) log_std = value.var(dim=spatial_dims, unbiased=False).clamp_min(1e-8).sqrt().log() captured.setdefault(block, []).append(torch.cat((mean, log_std), dim=-1).cpu()) return hook handles = [ diffusion_model.blocks[index].register_forward_hook(capture(block)) for block, index in zip(args.blocks, block_indices, strict=True) ] decode_pool = ThreadPoolExecutor( max_workers=args.decode_workers, thread_name_prefix="anima-intervention" ) extraction_started = time.perf_counter() processed = 0 feature_parts: list[torch.Tensor] = [] part_records: list[dict] = [] feature_buffer: list[tuple[torch.Tensor, dict]] = [] def decode_source(sample): decoded = [] for spec in pending_by_source[str(sample.metadata["record_id"])]: full, _face = apply_intervention( sample.full_bytes, sample.face_bytes, sample.metadata, spec, size=args.image_size, ) decoded.append( ( image_tensor(full).permute(1, 2, 0), {**spec, "source_shard": sample.shard}, ) ) return decoded def process_batch(batch: list[tuple[torch.Tensor, dict]]) -> None: nonlocal processed, part_index, feature_parts, part_records pixels, records = map(list, zip(*batch, strict=True)) with torch.inference_mode(): latents = encode_independent_stills(vae, pixels, model_management) clean = model.model.process_latent_in(latents).to(device=device, dtype=dtype) if clean.shape[0] != len(batch): raise RuntimeError(f"latent batch has {clean.shape[0]} rows for {len(batch)} records") generator = torch.Generator(device="cpu").manual_seed(args.noise_seed) noise = torch.randn(clean[:1].shape, generator=generator, dtype=torch.float32).to( device=device, dtype=dtype ).expand_as(clean) sigma = torch.full((clean.shape[0],), args.sigma, device=device, dtype=torch.float32) noised = args.sigma * noise + (1.0 - args.sigma) * clean captured.clear() model.model.apply_model( noised, sigma, c_crossattn=context.expand(clean.shape[0], *context.shape[1:]), ) if set(captured) != set(args.blocks): raise RuntimeError(f"captured blocks {sorted(captured)}, expected {args.blocks}") features = torch.stack( [torch.cat(captured[block], dim=0) for block in args.blocks], dim=1 ) if features.shape != (len(batch), len(args.blocks), 4096): raise RuntimeError(f"unexpected Anima feature shape: {tuple(features.shape)}") feature_parts.append(features) part_records.extend(records) processed += len(batch) if len(part_records) >= args.part_size: flush_part( args.output_dir, args.worker_index, part_index, feature_parts, part_records, blocks=args.blocks, sigma=args.sigma, noise_seed=args.noise_seed, manifest_sha256=manifest_sha256, selection=args.selection, ) part_index += 1 feature_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() - extraction_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_batch(feature_buffer[: args.batch_size]) del feature_buffer[: args.batch_size] if feature_buffer: process_batch(feature_buffer) finally: decode_pool.shutdown() for handle in handles: handle.remove() if part_records: flush_part( args.output_dir, args.worker_index, part_index, feature_parts, part_records, blocks=args.blocks, sigma=args.sigma, noise_seed=args.noise_seed, manifest_sha256=manifest_sha256, selection=args.selection, ) if processed + len(completed) != len(rows): raise RuntimeError(f"worker coverage mismatch: {processed} + {len(completed)} != {len(rows)}") summary = { "status": "complete", "worker_index": args.worker_index, "manifest_sha256": manifest_sha256, "records": len(rows), "already_complete": len(completed), "new_records": processed, "setup_seconds": extraction_started - run_started, "elapsed_seconds": time.perf_counter() - extraction_started, "total_seconds": time.perf_counter() - run_started, "peak_vram_bytes": torch.cuda.max_memory_allocated(), "blocks": args.blocks, "sigma": args.sigma, "noise_seed": args.noise_seed, "selection": args.selection, } path = args.output_dir / f"anima-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())