diff --git a/requirements.txt b/requirements.txt index a93eefd..c0825fe 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,5 +10,7 @@ einops PyYAML Pillow numpy +scikit-image huggingface_hub safetensors +git+https://github.com/openai/CLIP.git diff --git a/scripts/aggregate_phase_b_report.py b/scripts/aggregate_phase_b_report.py old mode 100644 new mode 100755 diff --git a/scripts/build_rich_caption_probe.py b/scripts/build_rich_caption_probe.py old mode 100644 new mode 100755 diff --git a/scripts/convert_pico_jsonl_to_twoframe_manifest.py b/scripts/convert_pico_jsonl_to_twoframe_manifest.py old mode 100644 new mode 100755 diff --git a/scripts/eval_pair_metrics.py b/scripts/eval_pair_metrics.py index a7832f7..eb93cea 100644 --- a/scripts/eval_pair_metrics.py +++ b/scripts/eval_pair_metrics.py @@ -25,8 +25,10 @@ Usage: from __future__ import annotations import argparse +import hashlib import json import logging +import os from pathlib import Path import clip @@ -46,6 +48,34 @@ logging.basicConfig( logger = logging.getLogger(__name__) +def clip_download_root() -> str | None: + root = os.environ.get("CLIP_CACHE_DIR") + if not root and os.environ.get("XDG_CACHE_HOME"): + root = str(Path(os.environ["XDG_CACHE_HOME"]) / "clip") + if root: + Path(root).mkdir(parents=True, exist_ok=True) + return root + + +def load_dinov2_vitl14(device: str) -> torch.nn.Module: + repo = os.environ.get("DINOV2_REPO") + if not repo: + repo = str(Path(torch.hub.get_dir()) / "facebookresearch_dinov2_main") + repo_path = Path(repo) + if repo_path.exists(): + logger.info(f"Loading DINOv2 ViT-L/14 from local torch hub repo: {repo_path}") + model = torch.hub.load(str(repo_path), "dinov2_vitl14", source="local", pretrained=True) + else: + logger.info("Loading DINOv2 ViT-L/14 from torch hub remote repo") + model = torch.hub.load( + "facebookresearch/dinov2", + "dinov2_vitl14", + pretrained=True, + skip_validation=True, + ) + return model.to(device).eval().requires_grad_(False) + + class PairMetrics(nn.Module): """Compute CLIP, DINOv2, SSIM metrics for source-target pairs.""" @@ -55,14 +85,15 @@ class PairMetrics(nn.Module): # CLIP ViT-L/14 logger.info("Loading CLIP ViT-L/14...") - self.clip_model, self.clip_preprocess = clip.load("ViT-L/14", device=device) + self.clip_model, self.clip_preprocess = clip.load( + "ViT-L/14", device=device, download_root=clip_download_root() + ) self.clip_model.eval().requires_grad_(False) self.clip_size = 224 # DINOv2 ViT-L/14 logger.info("Loading DINOv2 ViT-L/14...") - self.dinov2 = torch.hub.load("facebookresearch/dinov2", "dinov2_vitl14", pretrained=True) - self.dinov2 = self.dinov2.to(device).eval().requires_grad_(False) + self.dinov2 = load_dinov2_vitl14(device) self.register_buffer("clip_mean", torch.tensor((0.48145466, 0.4578275, 0.40821073))) self.register_buffer("clip_std", torch.tensor((0.26862954, 0.26130258, 0.27577711))) @@ -164,6 +195,11 @@ def parse_args(): ap.add_argument("--output-dir", required=True) ap.add_argument("--device", default="cuda:0") ap.add_argument("--id-field", default="item_id") + ap.add_argument("--source-fallback-field", default="source_image_abs", + help="Manifest field to use when a method directory has no {id}_source image. " + "Set empty to disable fallback.") + ap.add_argument("--shard-id", type=int, default=0) + ap.add_argument("--num-shards", type=int, default=1) return ap.parse_args() @@ -184,6 +220,13 @@ def main(): for line in f: if line.strip(): eval_items.append(json.loads(line)) + if args.num_shards > 1: + before = len(eval_items) + eval_items = [ + item for item in eval_items + if int(hashlib.md5(str(item[args.id_field]).encode()).hexdigest(), 16) % args.num_shards == args.shard_id + ] + logger.info(f"Shard {args.shard_id}/{args.num_shards}: {len(eval_items)}/{before} items") logger.info(f"Eval manifest: {len(eval_items)} items") # Initialize metrics @@ -203,6 +246,13 @@ def main(): src = find_image(method_dir, item_id, "source") tgt = find_image(method_dir, item_id, "target") + if not src and args.source_fallback_field: + fallback = item.get(args.source_fallback_field, "") + if fallback: + fallback_path = Path(fallback) + if fallback_path.exists(): + src = fallback_path + if not src or not tgt: continue diff --git a/scripts/eval_source_reconstruction.py b/scripts/eval_source_reconstruction.py index 3f867ec..fb2e658 100644 --- a/scripts/eval_source_reconstruction.py +++ b/scripts/eval_source_reconstruction.py @@ -26,6 +26,7 @@ from __future__ import annotations import argparse import json import logging +import os from pathlib import Path import clip @@ -44,18 +45,47 @@ logging.basicConfig( logger = logging.getLogger(__name__) +def clip_download_root() -> str | None: + root = os.environ.get("CLIP_CACHE_DIR") + if not root and os.environ.get("XDG_CACHE_HOME"): + root = str(Path(os.environ["XDG_CACHE_HOME"]) / "clip") + if root: + Path(root).mkdir(parents=True, exist_ok=True) + return root + + +def load_dinov2_vitl14(device: str) -> torch.nn.Module: + repo = os.environ.get("DINOV2_REPO") + if not repo: + repo = str(Path(torch.hub.get_dir()) / "facebookresearch_dinov2_main") + repo_path = Path(repo) + if repo_path.exists(): + logger.info(f"Loading DINOv2 ViT-L/14 from local torch hub repo: {repo_path}") + model = torch.hub.load(str(repo_path), "dinov2_vitl14", source="local", pretrained=True) + else: + logger.info("Loading DINOv2 ViT-L/14 from torch hub remote repo") + model = torch.hub.load( + "facebookresearch/dinov2", + "dinov2_vitl14", + pretrained=True, + skip_validation=True, + ) + return model.to(device).eval().requires_grad_(False) + + class ImageEncoders(nn.Module): def __init__(self, device: str = "cuda:0"): super().__init__() self.device = device logger.info("Loading CLIP ViT-L/14...") - self.clip_model, _ = clip.load("ViT-L/14", device=device) + self.clip_model, _ = clip.load( + "ViT-L/14", device=device, download_root=clip_download_root() + ) self.clip_model.eval().requires_grad_(False) logger.info("Loading DINOv2 ViT-L/14...") - self.dinov2 = torch.hub.load("facebookresearch/dinov2", "dinov2_vitl14", pretrained=True) - self.dinov2 = self.dinov2.to(device).eval().requires_grad_(False) + self.dinov2 = load_dinov2_vitl14(device) self.register_buffer("clip_mean", torch.tensor((0.48145466, 0.4578275, 0.40821073))) self.register_buffer("clip_std", torch.tensor((0.26862954, 0.26130258, 0.27577711))) diff --git a/scripts/infer_9b_lora_twoframe_8gpu.sh b/scripts/infer_9b_lora_twoframe_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/infer_batch_condition.py b/scripts/infer_batch_condition.py index 3aae26b..bd0564d 100644 --- a/scripts/infer_batch_condition.py +++ b/scripts/infer_batch_condition.py @@ -58,6 +58,10 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--output-dir", required=True, help="Output directory.") # Model loading ap.add_argument("--model-id", default="black-forest-labs/FLUX.2-klein-base-9B") + ap.add_argument("--base-model-root", default=None, + help="Local FLUX.2 klein base root. Sets KLEIN_9B_BASE_MODEL_ROOT.") + ap.add_argument("--require-local-base", action="store_true", + help="Fail if the requested local base root is missing.") ap.add_argument("--lora", default=None, help="LoRA adapter path.") ap.add_argument("--transformer-checkpoint", default=None, help="Full transformer checkpoint dir (for full FT models).") @@ -136,6 +140,17 @@ def main() -> None: logger.info("Nothing to do.") return + if args.base_model_root: + base_root = Path(args.base_model_root).expanduser() + if args.require_local_base and not base_root.exists(): + raise FileNotFoundError(f"Local base model root not found: {base_root}") + os.environ["KLEIN_9B_BASE_MODEL_ROOT"] = str(base_root) + os.environ.setdefault( + "KLEIN_9B_BASE_MODEL_PATH", + str(base_root / "flux-2-klein-base-9b.safetensors"), + ) + logger.info(f"Using local base model root: {base_root}") + # Setup device device = torch.device( f"cuda:{args.shard_id % torch.cuda.device_count()}" diff --git a/scripts/infer_batch_multiframe.py b/scripts/infer_batch_multiframe.py old mode 100644 new mode 100755 diff --git a/scripts/infer_batch_twoframe.py b/scripts/infer_batch_twoframe.py old mode 100644 new mode 100755 index be33e67..605c77e --- a/scripts/infer_batch_twoframe.py +++ b/scripts/infer_batch_twoframe.py @@ -38,6 +38,8 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--lora", default=None, help="LoRA adapter path (directory with adapter files).") ap.add_argument("--transformer-checkpoint", default=None, help="Full transformer checkpoint dir (for full FT models).") + ap.add_argument("--aux-path", default=None, + help="Optional twoframe_aux.{safetensors,pt}; defaults to searching the checkpoint/LoRA dir.") ap.add_argument("--model-id", default="black-forest-labs/FLUX.2-klein-base-9B") ap.add_argument("--steps", type=int, default=28) ap.add_argument("--cfg", type=float, default=6.0) @@ -65,6 +67,29 @@ def parse_args() -> argparse.Namespace: return ap.parse_args() +def find_aux_path(*roots: str | None) -> str | None: + """Find saved TwoFrame auxiliary embeddings next to a checkpoint/adapter.""" + for root in roots: + if not root: + continue + path = Path(root).expanduser() + search_dir = path if path.is_dir() else path.parent + for name in ("twoframe_aux.safetensors", "twoframe_aux.pt"): + candidate = search_dir / name + if candidate.exists(): + return str(candidate) + return None + + +def format_twoframe_prompt(template: str, source_caption: str, instruction: str) -> str: + source_blocks = f"[Source Image 1]\n{source_caption or 'reference image 1'}" + return template.format( + source_caption=source_caption, + instruction=instruction, + source_blocks=source_blocks, + ) + + def shard_items(items: list[dict], shard_id: int, num_shards: int) -> list[dict]: """Hash-based sharding for deterministic distribution.""" if num_shards <= 1: @@ -131,6 +156,10 @@ def main() -> None: engine.load_lora(args.lora) else: logger.info("No adapter loaded — using base model.") + aux_candidate = args.aux_path or find_aux_path(args.transformer_checkpoint, args.lora) + if aux_candidate: + engine.load_twoframe_aux(aux_candidate) + logger.info(f"Loaded twoframe aux embeddings: {aux_candidate}") logger.info("Model ready.") need_negative = args.cfg > 1.0 @@ -145,12 +174,14 @@ def main() -> None: try: # Encode text (joint mode) - merged_prompt = args.text_template.format( - source_caption=source_caption, - instruction=instruction, - ) + merged_prompt = format_twoframe_prompt(args.text_template, source_caption, instruction) pos_embeds, text_ids = engine.encode_text_joint( - [merged_prompt], text_t=args.text_t, + [merged_prompt], + text_t=args.text_t, + source_captions=[source_caption], + instructions=[instruction], + text_template=args.text_template, + strict_template=engine.extra_embed_strict_template, ) neg_embeds = neg_text_ids = None if need_negative: diff --git a/scripts/infer_d10_mid_refresh.py b/scripts/infer_d10_mid_refresh.py old mode 100644 new mode 100755 diff --git a/scripts/infer_d5_self_conditioning.py b/scripts/infer_d5_self_conditioning.py old mode 100644 new mode 100755 diff --git a/scripts/infer_d8_oracle_clean_source.py b/scripts/infer_d8_oracle_clean_source.py old mode 100644 new mode 100755 diff --git a/scripts/infer_d9_block_cfg.py b/scripts/infer_d9_block_cfg.py old mode 100644 new mode 100755 diff --git a/scripts/infer_flux_klein_twoframe.py b/scripts/infer_flux_klein_twoframe.py old mode 100644 new mode 100755 diff --git a/scripts/infer_twostep_baseline.py b/scripts/infer_twostep_baseline.py old mode 100644 new mode 100755 index eb8f476..715410c --- a/scripts/infer_twostep_baseline.py +++ b/scripts/infer_twostep_baseline.py @@ -66,6 +66,8 @@ def parse_args() -> argparse.Namespace: ap.add_argument("--model-id", default="black-forest-labs/FLUX.2-klein-base-9B") ap.add_argument("--edit-checkpoint", default=None, help="Checkpoint for the edit step. None = use base model (M1→M1).") + ap.add_argument("--edit-aux-path", default=None, + help="Optional twoframe_aux.{safetensors,pt} for the edit checkpoint.") # T2I step params ap.add_argument("--steps-t2i", type=int, default=28) ap.add_argument("--cfg-t2i", type=float, default=4.0) @@ -95,6 +97,20 @@ def parse_args() -> argparse.Namespace: return ap.parse_args() +def find_aux_path(*roots: str | None) -> str | None: + """Find saved TwoFrame auxiliary embeddings next to a checkpoint/adapter.""" + for root in roots: + if not root: + continue + path = Path(root).expanduser() + search_dir = path if path.is_dir() else path.parent + for name in ("twoframe_aux.safetensors", "twoframe_aux.pt"): + candidate = search_dir / name + if candidate.exists(): + return str(candidate) + return None + + def shard_items(items: list[dict], shard_id: int, num_shards: int) -> list[dict]: if num_shards <= 1: return items @@ -244,6 +260,10 @@ def main() -> None: logger.info(f"Loading edit checkpoint: {args.edit_checkpoint}") n_miss, n_unexp = engine.load_flow_checkpoint(args.edit_checkpoint) logger.info(f" missing={n_miss}, unexpected={n_unexp}") + aux_candidate = args.edit_aux_path or find_aux_path(args.edit_checkpoint) + if aux_candidate: + engine.load_twoframe_aux(aux_candidate) + logger.info(f"Loaded edit twoframe aux embeddings: {aux_candidate}") # Re-encode negative for edit step if need_negative: @@ -282,7 +302,12 @@ def main() -> None: source_caption=source_caption, ) pos_embeds, text_ids = engine.encode_text_joint( - [prompt], text_t=args.text_t, + [prompt], + text_t=args.text_t, + source_captions=[source_caption], + instructions=[instruction], + text_template=args.edit_text_template, + strict_template=engine.extra_embed_strict_template, ) # Encode source as condition diff --git a/scripts/make_multiframe_gallery.py b/scripts/make_multiframe_gallery.py old mode 100644 new mode 100755 diff --git a/scripts/make_multiframe_probe_combo_html.py b/scripts/make_multiframe_probe_combo_html.py old mode 100644 new mode 100755 diff --git a/scripts/make_multiframe_test100_html.py b/scripts/make_multiframe_test100_html.py old mode 100644 new mode 100755 diff --git a/scripts/make_phase2_complex_highscore_html.py b/scripts/make_phase2_complex_highscore_html.py old mode 100644 new mode 100755 diff --git a/scripts/make_reasoning_holdout500_html.py b/scripts/make_reasoning_holdout500_html.py old mode 100644 new mode 100755 diff --git a/scripts/make_reasoning_holdout_sampled_html.py b/scripts/make_reasoning_holdout_sampled_html.py old mode 100644 new mode 100755 diff --git a/scripts/make_reasoning_sample_html.py b/scripts/make_reasoning_sample_html.py old mode 100644 new mode 100755 diff --git a/scripts/measure_pair_consistency.py b/scripts/measure_pair_consistency.py old mode 100644 new mode 100755 diff --git a/scripts/phase_b_master_loop.sh b/scripts/phase_b_master_loop.sh old mode 100644 new mode 100755 diff --git a/scripts/phase_b_status_emit.sh b/scripts/phase_b_status_emit.sh old mode 100644 new mode 100755 diff --git a/scripts/phase_b_watchdog.sh b/scripts/phase_b_watchdog.sh old mode 100644 new mode 100755 diff --git a/scripts/phase_c_status.sh b/scripts/phase_c_status.sh old mode 100644 new mode 100755 diff --git a/scripts/precompute_flux2_vae_cache.py b/scripts/precompute_flux2_vae_cache.py old mode 100644 new mode 100755 diff --git a/scripts/precompute_flux2_vae_cache_8gpu.sh b/scripts/precompute_flux2_vae_cache_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/prepare_benchmark_manifests.py b/scripts/prepare_benchmark_manifests.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_ccb_c8_manifest.py b/scripts/prepare_ccb_c8_manifest.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_eval_manifests.py b/scripts/prepare_eval_manifests.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_phase_a_manifests.py b/scripts/prepare_phase_a_manifests.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_reasoning_holdout_infer_manifest.py b/scripts/prepare_reasoning_holdout_infer_manifest.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_reasoning_holdout_test_manifest.py b/scripts/prepare_reasoning_holdout_test_manifest.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_reasoning_manifest.py b/scripts/prepare_reasoning_manifest.py old mode 100644 new mode 100755 diff --git a/scripts/prepare_short_instruction_manifests.py b/scripts/prepare_short_instruction_manifests.py old mode 100644 new mode 100755 diff --git a/scripts/run0_sonnet_select.py b/scripts/run0_sonnet_select.py old mode 100644 new mode 100755 diff --git a/scripts/run_all_eval.sh b/scripts/run_all_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_all_inference_machine_a.sh b/scripts/run_all_inference_machine_a.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d11_real_source_eval.sh b/scripts/run_d11_real_source_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d1_d2_d3.sh b/scripts/run_d1_d2_d3.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d4_failure_taxonomy.sh b/scripts/run_d4_failure_taxonomy.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d5_self_conditioning.sh b/scripts/run_d5_self_conditioning.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d6_structured_joint.sh b/scripts/run_d6_structured_joint.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d7_text_factorization.sh b/scripts/run_d7_text_factorization.sh old mode 100644 new mode 100755 diff --git a/scripts/run_d8_oracle.sh b/scripts/run_d8_oracle.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_data_quality_6jobs.sh b/scripts/run_eval_data_quality_6jobs.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_imgedit_gedit_mode.sh b/scripts/run_eval_imgedit_gedit_mode.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_machine_a_m3source_wait_m2.sh b/scripts/run_eval_machine_a_m3source_wait_m2.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_machine_a_scoring.sh b/scripts/run_eval_machine_a_scoring.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_machine_a_stage1.sh b/scripts/run_eval_machine_a_stage1.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_machine_c_imgedit.sh b/scripts/run_eval_machine_c_imgedit.sh old mode 100644 new mode 100755 diff --git a/scripts/run_eval_machine_d_gedit.sh b/scripts/run_eval_machine_d_gedit.sh old mode 100644 new mode 100755 diff --git a/scripts/run_exp_k_machine_b_eval.sh b/scripts/run_exp_k_machine_b_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_exp_k_machine_b_infer.sh b/scripts/run_exp_k_machine_b_infer.sh old mode 100644 new mode 100755 diff --git a/scripts/run_generate_twoframe_complex_22k_cfg7_ckpt35k.sh b/scripts/run_generate_twoframe_complex_22k_cfg7_ckpt35k.sh old mode 100644 new mode 100755 diff --git a/scripts/run_infer_c2_8gpu.sh b/scripts/run_infer_c2_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_infer_c3_8gpu.sh b/scripts/run_infer_c3_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_infer_c4_8gpu.sh b/scripts/run_infer_c4_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_infer_node_consolidated_until_done.sh b/scripts/run_infer_node_consolidated_until_done.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m2new_infer_eval.sh b/scripts/run_m2new_infer_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3_cfg7_only.sh b/scripts/run_m3_cfg7_only.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3_s50_eval.sh b/scripts/run_m3_s50_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3ft_35000_8gpu.sh b/scripts/run_m3ft_35000_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3ft_inference.sh b/scripts/run_m3ft_inference.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3ft_missing_resume.sh b/scripts/run_m3ft_missing_resume.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3ft_resume60k.sh b/scripts/run_m3ft_resume60k.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3ft_sweep_eval.sh b/scripts/run_m3ft_sweep_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_m3source_round_end2end.sh b/scripts/run_m3source_round_end2end.sh old mode 100644 new mode 100755 diff --git a/scripts/run_machine_a_eval.sh b/scripts/run_machine_a_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_machine_a_infer.sh b/scripts/run_machine_a_infer.sh old mode 100644 new mode 100755 diff --git a/scripts/run_machine_b_distilled_train.sh b/scripts/run_machine_b_distilled_train.sh old mode 100644 new mode 100755 diff --git a/scripts/run_machine_b_distilled_train_local.sh b/scripts/run_machine_b_distilled_train_local.sh old mode 100644 new mode 100755 diff --git a/scripts/run_missing_inference_resume.sh b/scripts/run_missing_inference_resume.sh old mode 100644 new mode 100755 diff --git a/scripts/run_missing_machine_a.sh b/scripts/run_missing_machine_a.sh old mode 100644 new mode 100755 diff --git a/scripts/run_missing_machine_a_m1_rewrite.sh b/scripts/run_missing_machine_a_m1_rewrite.sh old mode 100644 new mode 100755 diff --git a/scripts/run_missing_machine_b.sh b/scripts/run_missing_machine_b.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_4img_probe10.sh b/scripts/run_multiframe_4img_probe10.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_resample100.sh b/scripts/run_multiframe_resample100.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_smoke_1gpu.sh b/scripts/run_multiframe_smoke_1gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_smoke_8gpu.sh b/scripts/run_multiframe_smoke_8gpu.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_smoke_8gpu_debug.sh b/scripts/run_multiframe_smoke_8gpu_debug.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_test100.sh b/scripts/run_multiframe_test100.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_test100_latest_when_free.sh b/scripts/run_multiframe_test100_latest_when_free.sh old mode 100644 new mode 100755 diff --git a/scripts/run_multiframe_train.sh b/scripts/run_multiframe_train.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase2_refilter_4jobs.sh b/scripts/run_phase2_refilter_4jobs.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_a.sh b/scripts/run_phase_a.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_a_eval.sh b/scripts/run_phase_a_eval.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_a_eval_parallel.sh b/scripts/run_phase_a_eval_parallel.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_a_mllm_eval_sonnet46.sh b/scripts/run_phase_a_mllm_eval_sonnet46.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_b_eval_all.sh b/scripts/run_phase_b_eval_all.sh old mode 100644 new mode 100755 diff --git a/scripts/run_phase_c.sh b/scripts/run_phase_c.sh old mode 100644 new mode 100755 diff --git a/scripts/run_reasoning_holdout500_infer.sh b/scripts/run_reasoning_holdout500_infer.sh old mode 100644 new mode 100755 diff --git a/scripts/run_reasoning_probe.sh b/scripts/run_reasoning_probe.sh old mode 100644 new mode 100755 diff --git a/scripts/run_reasoning_train.sh b/scripts/run_reasoning_train.sh old mode 100644 new mode 100755 diff --git a/scripts/run_rewrite_structured.sh b/scripts/run_rewrite_structured.sh old mode 100644 new mode 100755 diff --git a/scripts/run_rich_caption_probe.sh b/scripts/run_rich_caption_probe.sh old mode 100644 new mode 100755 diff --git a/scripts/run_unified_cfg4_test.sh b/scripts/run_unified_cfg4_test.sh old mode 100644 new mode 100755 diff --git a/scripts/run_v2_instr_filter_2jobs.sh b/scripts/run_v2_instr_filter_2jobs.sh old mode 100644 new mode 100755 diff --git a/scripts/run_watchdog_1h.sh b/scripts/run_watchdog_1h.sh old mode 100644 new mode 100755 diff --git a/scripts/sample_multiframe_4img_probe10.py b/scripts/sample_multiframe_4img_probe10.py old mode 100644 new mode 100755 diff --git a/scripts/sample_multiframe_resample100.py b/scripts/sample_multiframe_resample100.py old mode 100644 new mode 100755 diff --git a/scripts/switch_current_to_machine_b.sh b/scripts/switch_current_to_machine_b.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_base_editlong_pico400k_train20k_bs2_lr1e5_vae_cache_zero2.sh b/scripts/train_4b_base_editlong_pico400k_train20k_bs2_lr1e5_vae_cache_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full.sh b/scripts/train_4b_full.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full_pico400k_opusstage2_long_train20k_bs2_lr1e5_jointtext_t0_zero2.sh b/scripts/train_4b_full_pico400k_opusstage2_long_train20k_bs2_lr1e5_jointtext_t0_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_cfgdrop0.sh b/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_cfgdrop0.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_cfgdrop0_zero2.sh b/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_cfgdrop0_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_jointtext_t0_zero2.sh b/scripts/train_4b_full_pico400k_short_train20k_bs2_lr1e5_jointtext_t0_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_full_pico400k_short_zero2_smoke.sh b/scripts/train_4b_full_pico400k_short_zero2_smoke.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_lora.sh b/scripts/train_4b_lora.sh old mode 100644 new mode 100755 diff --git a/scripts/train_4b_lora_moe_prodigy_pico400k_short_jointtext_t0_bs2_zero2.sh b/scripts/train_4b_lora_moe_prodigy_pico400k_short_jointtext_t0_bs2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_base_editlong_pico400k_train20k_bs2_lr1e6_vae_cache_zero2.sh b/scripts/train_9b_base_editlong_pico400k_train20k_bs2_lr1e6_vae_cache_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full.sh b/scripts/train_9b_full.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_direct_edit_baseline_zero2.sh b/scripts/train_9b_full_direct_edit_baseline_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_direct_edit_baseline_zero3.sh b/scripts/train_9b_full_direct_edit_baseline_zero3.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_pico400k_opusstage2_long_train20k_bs2_lr1e6_jointtext_t0_zero2.sh b/scripts/train_9b_full_pico400k_opusstage2_long_train20k_bs2_lr1e6_jointtext_t0_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_pico57k_corner10k_long_jointtext_zero2.sh b/scripts/train_9b_full_pico57k_corner10k_long_jointtext_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_pico57k_corner10k_long_jointtext_zero3.sh b/scripts/train_9b_full_pico57k_corner10k_long_jointtext_zero3.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_full_twoframe_lr5e6_zero2.sh b/scripts/train_9b_full_twoframe_lr5e6_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora.sh b/scripts/train_9b_lora.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_downstream_edit_combined_zero2.sh b/scripts/train_9b_lora_downstream_edit_combined_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_downstream_edit_phase2_zero2.sh b/scripts/train_9b_lora_downstream_edit_phase2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_fluxfill_icedittargets_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_fluxfill_icedittargets_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_simpletuner_flux2targets_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_simpletuner_flux2targets_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_zero3.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_zero3.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_gc40k_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_nogc_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_long_no_latent_nogc_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_finalmix80k_short_no_latent_nogc_zero2.sh b/scripts/train_9b_lora_moe_prodigy_finalmix80k_short_no_latent_nogc_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_moe_prodigy_pico400k_long_jointtext_t0_bs2_zero2.sh b/scripts/train_9b_lora_moe_prodigy_pico400k_long_jointtext_t0_bs2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_pico57k_corner10k_long_jointtext_zero2.sh b/scripts/train_9b_lora_pico57k_corner10k_long_jointtext_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_smoke_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_smoke_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_textimgemb_full25k_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_textimgemb_full25k_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_v1_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_jointtext_t0_cache40k_bs1ga2_routing_v1_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_icedit6targets_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_long_no_latent_gc40k_bs1ga2_icedit6targets_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_short_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_node2_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_short_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_node2_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_finalmix80k_short_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_zero2.sh b/scripts/train_9b_lora_standard_prodigy_finalmix80k_short_jointtext_t0_cache40k_bs1ga2_routing_render_mod_v2_gcfix_strictoff_full40k_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_9b_lora_standard_prodigy_pico400k_long_jointtext_t0_bs1ga2_icedit6targets_vae_cache_zero2.sh b/scripts/train_9b_lora_standard_prodigy_pico400k_long_jointtext_t0_bs1ga2_icedit6targets_vae_cache_zero2.sh old mode 100644 new mode 100755 diff --git a/scripts/train_exp_e_phase2_only.sh b/scripts/train_exp_e_phase2_only.sh old mode 100644 new mode 100755 diff --git a/scripts/train_exp_f_phase2_pico.sh b/scripts/train_exp_f_phase2_pico.sh old mode 100644 new mode 100755 diff --git a/scripts/train_exp_g_phase2_all.sh b/scripts/train_exp_g_phase2_all.sh old mode 100644 new mode 100755 diff --git a/scripts/wait_then_resume_m3ft60k.sh b/scripts/wait_then_resume_m3ft60k.sh old mode 100644 new mode 100755 diff --git a/scripts/wait_then_run_multiframe_4img_probe10.sh b/scripts/wait_then_run_multiframe_4img_probe10.sh old mode 100644 new mode 100755 diff --git a/scripts/watch_and_run_m3ft_sweep.sh b/scripts/watch_and_run_m3ft_sweep.sh old mode 100644 new mode 100755 diff --git a/scripts/watch_m3ft_35000_launch.sh b/scripts/watch_m3ft_35000_launch.sh old mode 100644 new mode 100755 diff --git a/train.py b/train.py index f7f193e..ab21282 100644 --- a/train.py +++ b/train.py @@ -5,6 +5,7 @@ import argparse import inspect import json import os +import random import time from pathlib import Path @@ -16,6 +17,11 @@ from torch.utils.data import DataLoader from tqdm.auto import tqdm from twoframe.data import TwoFrameEditingDataset, collate_fn +from twoframe.data_bucketed import ( + BucketedFrameDataset, + DistributedBucketBatchSampler, + bucketed_frame_collate_fn, +) from twoframe.data_multiframe import MultiFrameEditingDataset, multiframe_collate_fn from twoframe.modeling import FluxKleinTwoFrame, count_parameters @@ -31,12 +37,24 @@ def apply_env_overrides(cfg: dict) -> dict: cfg["training"]["mixed_precision"] = os.environ["MIXED_PRECISION"] if os.getenv("GRADIENT_ACCUMULATION"): cfg["training"]["gradient_accumulation_steps"] = int(os.environ["GRADIENT_ACCUMULATION"]) + if os.getenv("PER_GPU_BATCH_SIZE"): + cfg["training"]["per_gpu_batch_size"] = int(os.environ["PER_GPU_BATCH_SIZE"]) if os.getenv("GRAD_CLIP"): cfg["training"]["max_grad_norm"] = float(os.environ["GRAD_CLIP"]) if os.getenv("SAVE_EVERY"): cfg["training"]["save_every"] = int(os.environ["SAVE_EVERY"]) + if os.getenv("LOG_EVERY"): + cfg["training"]["log_every"] = int(os.environ["LOG_EVERY"]) if os.getenv("MAX_STEPS"): cfg["training"]["max_steps"] = int(os.environ["MAX_STEPS"]) + if os.getenv("LOAD_TRAINABLE_CHECKPOINT"): + cfg["training"]["load_trainable_checkpoint"] = os.environ["LOAD_TRAINABLE_CHECKPOINT"] + if os.getenv("RESUME_FROM"): + cfg["training"]["resume_from"] = os.environ["RESUME_FROM"] + if os.getenv("OUT"): + cfg["training"]["output_dir"] = os.environ["OUT"] + if os.getenv("OUTPUT_DIR"): + cfg["training"]["output_dir"] = os.environ["OUTPUT_DIR"] return cfg @@ -140,6 +158,236 @@ def latest_checkpoint_path(ckpt_root: Path) -> Path | None: return candidates[-1] +def _dtype_from_name(name: str | None, default: torch.dtype = torch.bfloat16) -> torch.dtype: + key = str(name or "").strip().lower() + if key in {"fp16", "float16", "half"}: + return torch.float16 + if key in {"fp32", "float32", "full"}: + return torch.float32 + if key in {"bf16", "bfloat16"}: + return torch.bfloat16 + return default + + +def _is_ema_enabled(training_cfg: dict) -> bool: + ema_cfg = training_cfg.get("ema", None) + if isinstance(ema_cfg, dict): + return bool(ema_cfg.get("enabled", False)) + if ema_cfg is not None: + return bool(ema_cfg) + return bool(training_cfg.get("use_ema", False)) + + +def _ema_cfg(training_cfg: dict) -> dict: + ema_cfg = training_cfg.get("ema", {}) + if not isinstance(ema_cfg, dict): + ema_cfg = {"enabled": bool(ema_cfg)} + out = dict(ema_cfg) + if "enabled" not in out: + out["enabled"] = _is_ema_enabled(training_cfg) + if "decay" not in out and "ema_decay" in training_cfg: + out["decay"] = training_cfg["ema_decay"] + if "device" not in out and "ema_device" in training_cfg: + out["device"] = training_cfg["ema_device"] + if "dtype" not in out and "ema_dtype" in training_cfg: + out["dtype"] = training_cfg["ema_dtype"] + return out + + +class TrainableEMA: + """EMA for components saved by FluxKleinTwoFrame.save_trainable(). + + EMA checkpoints are written as a parallel trainable directory containing + flow_model.safetensors and optional twoframe_aux.pt, so existing loading + code can use the EMA weights by pointing load_trainable_checkpoint at the + EMA directory. + """ + + def __init__(self, decay: float, device: torch.device, dtype: torch.dtype): + self.decay = float(decay) + self.device = device + self.dtype = dtype + self.num_updates = 0 + self.transformer: dict[str, torch.Tensor] = {} + self.aux_tensors: dict[str, torch.Tensor] = {} + + @staticmethod + def _tensor_for_ema(tensor: torch.Tensor, device: torch.device, dtype: torch.dtype) -> torch.Tensor: + target_dtype = dtype if tensor.is_floating_point() else tensor.dtype + return tensor.detach().to(device=device, dtype=target_dtype).clone() + + @classmethod + def from_model(cls, model: FluxKleinTwoFrame, decay: float, device: torch.device, dtype: torch.dtype): + ema = cls(decay=decay, device=device, dtype=dtype) + ema.copy_from_model(model) + return ema + + def copy_from_model(self, model: FluxKleinTwoFrame) -> None: + module = model.trainable_module + if hasattr(module, "module"): + module = module.module + self.transformer = { + key: self._tensor_for_ema(value, self.device, self.dtype) + for key, value in module.state_dict().items() + } + aux = model._extra_aux_state() + self.aux_tensors = { + key: self._tensor_for_ema(value, self.device, self.dtype) + for key, value in aux.items() + if isinstance(value, torch.Tensor) + } + self.num_updates = 0 + + def update(self, model: FluxKleinTwoFrame) -> None: + module = model.trainable_module + if hasattr(module, "module"): + module = module.module + one_minus_decay = 1.0 - self.decay + with torch.no_grad(): + for key, value in module.state_dict().items(): + if key not in self.transformer: + self.transformer[key] = self._tensor_for_ema(value, self.device, self.dtype) + continue + ema_value = self.transformer[key] + current = value.detach().to(device=ema_value.device, dtype=ema_value.dtype) + if ema_value.is_floating_point(): + ema_value.mul_(self.decay).add_(current, alpha=one_minus_decay) + else: + ema_value.copy_(current) + + aux = model._extra_aux_state() + for key, value in aux.items(): + if not isinstance(value, torch.Tensor): + continue + if key not in self.aux_tensors: + self.aux_tensors[key] = self._tensor_for_ema(value, self.device, self.dtype) + continue + ema_value = self.aux_tensors[key] + current = value.detach().to(device=ema_value.device, dtype=ema_value.dtype) + if ema_value.is_floating_point(): + ema_value.mul_(self.decay).add_(current, alpha=one_minus_decay) + else: + ema_value.copy_(current) + self.num_updates += 1 + + def save(self, model: FluxKleinTwoFrame, output_dir: Path, metadata: dict | None = None) -> None: + from safetensors.torch import save_file as save_safetensors + + output_dir.mkdir(parents=True, exist_ok=True) + transformer_cpu = {key: value.detach().cpu().contiguous() for key, value in self.transformer.items()} + torch.save(transformer_cpu, output_dir / "flow_model.pt") + save_safetensors(transformer_cpu, output_dir / "flow_model.safetensors") + + aux = model._extra_aux_state() + aux_enabled = False + for key, value in self.aux_tensors.items(): + aux[key] = value.detach().cpu().contiguous() + aux_enabled = True + if aux_enabled: + torch.save(aux, output_dir / "twoframe_aux.pt") + safe_aux = {key: value for key, value in aux.items() if isinstance(value, torch.Tensor)} + if safe_aux: + save_safetensors(safe_aux, output_dir / "twoframe_aux.safetensors") + + meta = { + "checkpoint_type": "ema_full_transformer", + "ema_decay": self.decay, + "ema_num_updates": self.num_updates, + "raw_trainable_loader_compatible": True, + "aux_file": "twoframe_aux.pt" if aux_enabled else None, + } + if metadata: + meta.update(metadata) + with (output_dir / "twoframe_checkpoint_meta.json").open("w", encoding="utf-8") as f: + json.dump(meta, f, ensure_ascii=False, indent=2) + + +def _move_to_device(value, device: torch.device): + if torch.is_tensor(value): + return value.to(device, non_blocking=True) + if isinstance(value, list): + return [_move_to_device(item, device) for item in value] + if isinstance(value, tuple): + return tuple(_move_to_device(item, device) for item in value) + if isinstance(value, dict): + return {key: _move_to_device(item, device) for key, item in value.items()} + return value + + +def _build_bucketed_dataset(name: str, data_cfg: dict, common_cfg: dict) -> BucketedFrameDataset: + cfg = {**common_cfg, **dict(data_cfg)} + return BucketedFrameDataset( + manifest_path=cfg["manifest_path"], + num_sources=int(cfg["num_sources"]), + source_max_side=int(cfg["source_max_side"]), + target_max_side=int(cfg["target_max_side"]), + source_bucket_kind=str(cfg.get("source_bucket_kind", "source5")), + target_bucket_kind=str(cfg.get("target_bucket_kind", "target9")), + round_multiple=int(cfg.get("round_multiple", 32)), + bucket_cache_path=cfg.get("bucket_cache_path", None), + build_bucket_index=bool(cfg.get("build_bucket_index", False)), + skip_missing=bool(cfg.get("skip_missing", True)), + max_records=cfg.get("max_records", None), + source_image_field=str(cfg.get("source_image_field", "source_image")), + target_image_field=str(cfg.get("target_image_field", "target_image")), + source_caption_field=str(cfg.get("source_caption_field", "source_caption")), + source_caption_fallback_fields=_as_str_list( + cfg.get("source_caption_fallback_fields", ["source_caption"]), + default=["source_caption"], + ), + instruction_field=str(cfg.get("instruction_field", "instruction")), + instruction_fallback_fields=_as_str_list( + cfg.get("instruction_fallback_fields", ["edit_instruction_short", "edit_prompt_short", "text"]), + default=["edit_instruction_short", "edit_prompt_short", "text"], + ), + ) + + +def _stage_for_step(stages: list[dict], step: int) -> dict: + cursor = 0 + for stage in stages: + cursor += int(stage["steps"]) + if step < cursor: + return stage + return stages[-1] + + +def _sample_weighted_key(weights: dict, rng: random.Random) -> str: + items = [(str(key), float(value)) for key, value in weights.items() if float(value) > 0] + if not items: + raise ValueError("No positive sampling weights configured.") + total = sum(weight for _, weight in items) + draw = rng.random() * total + running = 0.0 + for key, weight in items: + running += weight + if draw <= running: + return key + return items[-1][0] + + +def _dataset_key_for_stage(stage: dict, sampled_k: str) -> str: + dataset_map = stage.get("dataset_map", {}) + if sampled_k in dataset_map: + return str(dataset_map[sampled_k]) + return sampled_k + + +def _sampled_k_from_dataset_key(dataset_key: str) -> str: + key = str(dataset_key) + if key.startswith("K1"): + return "K1" + if key.startswith("K2"): + return "K2" + if key.startswith("K3"): + return "K3" + return key + + +def _stable_name_offset(name: str) -> int: + return sum((idx + 1) * ord(ch) for idx, ch in enumerate(str(name))) % 100000 + + def main(): parser = argparse.ArgumentParser() parser.add_argument("--config", type=str, required=True) @@ -184,7 +432,59 @@ def main(): print("=" * 80) dataset_type = str(cfg["data"].get("dataset_type", "twoframe")).strip().lower() - if dataset_type == "multiframe": + mixed_loaders: dict[str, DataLoader] = {} + mixed_iters: dict[str, object] = {} + mixed_stages: list[dict] = [] + if dataset_type == "mixed_bucketed": + data_common = dict(cfg["data"].get("common", {})) + data_common.setdefault("round_multiple", cfg["data"].get("round_multiple", 32)) + data_common.setdefault("skip_missing", cfg["data"].get("skip_missing", True)) + data_common.setdefault("build_bucket_index", cfg["data"].get("build_bucket_index", False)) + dataset_cfgs = cfg["data"].get("datasets", {}) + if not isinstance(dataset_cfgs, dict) or not dataset_cfgs: + raise ValueError("data.datasets must define bucketed datasets for dataset_type=mixed_bucketed.") + + per_gpu_batch = int(cfg["training"].get("per_gpu_batch_size", 1)) + for name, dataset_cfg in dataset_cfgs.items(): + dataset = _build_bucketed_dataset(str(name), dataset_cfg, data_common) + sampler = DistributedBucketBatchSampler( + bucket_to_indices=dataset.bucket_to_indices, + batch_size=per_gpu_batch, + rank=accelerator.process_index, + world_size=accelerator.num_processes, + seed=int(cfg["training"].get("seed", 42)) + _stable_name_offset(str(name)), + ) + loader = DataLoader( + dataset, + batch_sampler=sampler, + num_workers=int(cfg["data"].get("num_workers", 8)), + pin_memory=True, + collate_fn=bucketed_frame_collate_fn, + persistent_workers=bool(cfg["data"].get("persistent_workers", False)) + and int(cfg["data"].get("num_workers", 8)) > 0, + ) + mixed_loaders[str(name)] = loader + if accelerator.is_main_process: + print( + f"bucketed dataset {name}: records={len(dataset):,} buckets={len(dataset.bucket_to_indices):,}" + ) + + mixed_stages = list(cfg.get("mixed_training", {}).get("stages", [])) + if not mixed_stages: + raise ValueError("mixed_training.stages is required for dataset_type=mixed_bucketed.") + force_dataset_key = os.environ.get("FORCE_DATASET_KEY") + if force_dataset_key: + if force_dataset_key not in mixed_loaders: + raise ValueError( + f"FORCE_DATASET_KEY={force_dataset_key!r} is not one of " + f"{sorted(mixed_loaders.keys())!r}." + ) + if accelerator.is_main_process: + print(f"forcing mixed dataset key for debug: {force_dataset_key}") + used_collate_fn = bucketed_frame_collate_fn + dataset = None + loader = None + elif dataset_type == "multiframe": dataset = MultiFrameEditingDataset( manifest_path=cfg["data"]["manifest_path"], target_resolution=int(cfg["data"].get("target_resolution", 1024)), @@ -231,15 +531,16 @@ def main(): print("data mode: online VAE encoding from images") per_gpu_batch = int(cfg["training"].get("per_gpu_batch_size", 1)) - loader = DataLoader( - dataset, - batch_size=per_gpu_batch, - shuffle=True, - num_workers=int(cfg["data"].get("num_workers", 8)), - pin_memory=True, - drop_last=True, - collate_fn=used_collate_fn, - ) + if dataset_type != "mixed_bucketed": + loader = DataLoader( + dataset, + batch_size=per_gpu_batch, + shuffle=True, + num_workers=int(cfg["data"].get("num_workers", 8)), + pin_memory=True, + drop_last=True, + collate_fn=used_collate_fn, + ) dtype_name = cfg["training"].get("weight_dtype", "bf16").lower() if dtype_name == "fp16": @@ -294,8 +595,22 @@ def main(): extra_embed_joint_policy=str(cfg["model"].get("extra_embed_joint_policy", "binary_full")), extra_embed_zero_init=bool(cfg["model"].get("extra_embed_zero_init", True)), extra_embed_strict_template=bool(cfg["model"].get("extra_embed_strict_template", True)), + image_frame_embed_slots=int(cfg["model"].get("image_frame_embed_slots", 2)), + multiframe_loss_mode=str(cfg["training"].get("multiframe_loss_mode", "frame_average")), ) + trainable_checkpoint = cfg["training"].get("load_trainable_checkpoint", None) + if trainable_checkpoint: + missing, unexpected = model.load_trainable_checkpoint( + trainable_checkpoint, + strict=bool(cfg["training"].get("load_trainable_strict", True)), + ) + if accelerator.is_main_process: + print( + f"loaded trainable checkpoint: {trainable_checkpoint} " + f"missing={missing} unexpected={unexpected}" + ) + total_params, trainable_params = count_parameters(model.trainable_module) if accelerator.is_main_process: print(f"model trainable module total params: {total_params:,}") @@ -319,10 +634,23 @@ def main(): lr_lambda=lambda step: min((step + 1) / max(1, warmup_steps), 1.0), ) - if scheduler is None: - model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + if dataset_type == "mixed_bucketed": + if use_deepspeed and getattr(accelerator.state, "deepspeed_plugin", None) is not None: + ds_cfg = accelerator.state.deepspeed_plugin.deepspeed_config + ds_cfg["train_micro_batch_size_per_gpu"] = per_gpu_batch + ds_cfg["gradient_accumulation_steps"] = int( + cfg["training"].get("gradient_accumulation_steps", 1) + ) + if scheduler is None: + model, optimizer = accelerator.prepare(model, optimizer) + else: + model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + mixed_iters = {} else: - model, optimizer, loader, scheduler = accelerator.prepare(model, optimizer, loader, scheduler) + if scheduler is None: + model, optimizer, loader = accelerator.prepare(model, optimizer, loader) + else: + model, optimizer, loader, scheduler = accelerator.prepare(model, optimizer, loader, scheduler) if accelerator.is_main_process: print(f"optimizer: {optimizer_name}") @@ -343,9 +671,27 @@ def main(): except Exception: start_step = 0 + ema = None + ema_options = _ema_cfg(cfg["training"]) + if bool(ema_options.get("enabled", False)): + ema_decay = float(ema_options.get("decay", 0.999)) + ema_device_name = str(ema_options.get("device", "cuda")).strip().lower() + ema_device = accelerator.device if ema_device_name in {"cuda", "gpu", "accelerator"} else torch.device("cpu") + ema_dtype = _dtype_from_name(str(ema_options.get("dtype", cfg["training"].get("weight_dtype", "bf16")))) + if accelerator.is_main_process: + unwrapped = accelerator.unwrap_model(model) + ema = TrainableEMA.from_model(unwrapped, decay=ema_decay, device=ema_device, dtype=ema_dtype) + print( + f"EMA enabled: decay={ema_decay} device={ema_device} dtype={ema_dtype} " + "init=current_model", + flush=True, + ) + accelerator.wait_for_everyone() + save_every = int(cfg["training"].get("save_every", 5000)) log_every = int(cfg["training"].get("log_every", 10)) grad_clip = float(cfg["training"].get("max_grad_norm", 1.0)) + ema_dir_name = str(ema_options.get("save_dir_name", "trainable_ema")) if accelerator.is_main_process and cfg["training"].get("log_with", None): init_kwargs = {} @@ -359,7 +705,7 @@ def main(): ) step = start_step - data_iter = iter(loader) + data_iter = None if dataset_type == "mixed_bucketed" else iter(loader) progress = tqdm(total=max_steps, disable=not accelerator.is_main_process, initial=start_step) running_loss = 0.0 @@ -367,16 +713,42 @@ def main(): running_src = 0.0 running_count = 0 t_last = time.time() + micro_step = 0 + last_batch_info: dict[str, str] = {} while step < max_steps: - try: - batch = next(data_iter) - except StopIteration: - data_iter = iter(loader) - batch = next(data_iter) + if dataset_type == "mixed_bucketed": + stage = _stage_for_step(mixed_stages, step) + rng = random.Random(int(cfg["training"].get("seed", 42)) + micro_step) + if force_dataset_key: + dataset_key = force_dataset_key + sampled_k = _sampled_k_from_dataset_key(dataset_key) + else: + sampled_k = _sample_weighted_key(stage["k_weights"], rng) + dataset_key = _dataset_key_for_stage(stage, sampled_k) + if dataset_key not in mixed_iters: + mixed_iters[dataset_key] = iter(mixed_loaders[dataset_key]) + try: + batch = next(mixed_iters[dataset_key]) + except StopIteration: + mixed_iters[dataset_key] = iter(mixed_loaders[dataset_key]) + batch = next(mixed_iters[dataset_key]) + batch = _move_to_device(batch, accelerator.device) + last_batch_info = { + "stage": str(stage.get("name", "")), + "sampled_k": sampled_k, + "dataset_key": dataset_key, + "bucket_key": str(batch.get("bucket_key", "")), + } + else: + try: + batch = next(data_iter) + except StopIteration: + data_iter = iter(loader) + batch = next(data_iter) with accelerator.accumulate(model): - if dataset_type == "multiframe": + if dataset_type in {"multiframe", "mixed_bucketed"}: out = model.forward_multiframe( pixel_values_sources=batch["pixel_values_sources"], pixel_values_target=batch["pixel_values_target"], @@ -407,10 +779,13 @@ def main(): if scheduler is not None: scheduler.step() optimizer.zero_grad(set_to_none=True) + micro_step += 1 if accelerator.sync_gradients: step += 1 progress.update(1) + if ema is not None: + ema.update(accelerator.unwrap_model(model)) loss_item = float(loss.detach().item()) tgt_item = float(out.loss_target.detach().item()) @@ -443,6 +818,11 @@ def main(): "grad_norm": grad_norm_val, "step_time_sec": dt / log_every, } + if ema is not None: + payload["ema_decay"] = ema.decay + payload["ema_updates"] = ema.num_updates + if last_batch_info: + payload.update(last_batch_info) accelerator.print(json.dumps(payload, ensure_ascii=False)) if cfg["training"].get("log_with", None): @@ -458,9 +838,18 @@ def main(): if accelerator.is_main_process: unwrapped = accelerator.unwrap_model(model) unwrapped.save_trainable(str(ckpt_dir / "trainable")) + if ema is not None: + ema.save( + unwrapped, + ckpt_dir / ema_dir_name, + metadata={"step": step, "source": "train.py"}, + ) with open(output_dir / "latest_step.txt", "w", encoding="utf-8") as f: f.write(str(step)) print(f"Saved checkpoint at step={step}: {ckpt_dir}") + if ema is not None: + print(f"Saved EMA checkpoint at step={step}: {ckpt_dir / ema_dir_name}") + accelerator.wait_for_everyone() accelerator.wait_for_everyone() if accelerator.is_main_process: diff --git a/twoframe/modeling.py b/twoframe/modeling.py index 8f00154..90308fe 100644 --- a/twoframe/modeling.py +++ b/twoframe/modeling.py @@ -10,6 +10,7 @@ from typing import Iterable, Sequence import torch import torch.nn as nn from einops import rearrange +from safetensors.torch import load_file as load_safetensors from transformers import Qwen2TokenizerFast, Qwen3ForCausalLM from .backbone import load_autoencoder, load_flow_model, normalize_model_size, repo_id_for, spec_for @@ -81,6 +82,8 @@ class FluxKleinTwoFrame(nn.Module): extra_embed_joint_policy: str = "binary_full", extra_embed_zero_init: bool = True, extra_embed_strict_template: bool = True, + image_frame_embed_slots: int = 2, + multiframe_loss_mode: str = "frame_average", ): super().__init__() @@ -122,6 +125,15 @@ class FluxKleinTwoFrame(nn.Module): ) self.extra_embed_zero_init = bool(extra_embed_zero_init) self.extra_embed_strict_template = bool(extra_embed_strict_template) + self.image_frame_embed_slots = int(image_frame_embed_slots) + if self.image_frame_embed_slots < 2: + raise ValueError("image_frame_embed_slots must be >= 2.") + self.multiframe_loss_mode = str(multiframe_loss_mode).strip().lower() + if self.multiframe_loss_mode not in {"frame_average", "block_balanced"}: + raise ValueError( + f"Unsupported multiframe_loss_mode={multiframe_loss_mode}. " + "Choose from ['frame_average', 'block_balanced']." + ) self._warned_non_joint_extra = False self.source_loss_weight = float(source_loss_weight) self.target_loss_weight = float(target_loss_weight) @@ -231,7 +243,7 @@ class FluxKleinTwoFrame(nn.Module): if use_image: if in_channels <= 0: raise ValueError("Failed to detect transformer in_channels for image frame embedding.") - self.image_frame_embed = nn.Embedding(2, in_channels) + self.image_frame_embed = nn.Embedding(self.image_frame_embed_slots, in_channels) if self.extra_embed_zero_init: nn.init.zeros_(self.image_frame_embed.weight) @@ -518,7 +530,12 @@ class FluxKleinTwoFrame(nn.Module): ) -> list[str]: prompts: list[str] = [] for captions, instruction in zip(source_captions, instructions): + source_blocks = "\n\n".join( + f"[Source Image {idx}]\n{caption or f'reference image {idx}'}" + for idx, caption in enumerate(captions, start=1) + ) prompt = self.text_template + prompt = prompt.replace("{source_blocks}", source_blocks) for idx, caption in enumerate(captions, start=1): prompt = prompt.replace( f"{{source{idx}_caption}}", @@ -678,18 +695,24 @@ class FluxKleinTwoFrame(nn.Module): def forward_multiframe( self, - pixel_values_sources: torch.Tensor, + pixel_values_sources: torch.Tensor | list[torch.Tensor], pixel_values_target: torch.Tensor, source_captions_long: list[list[str]], instructions: list[str], ) -> TwoFrameLoss: if self.text_mode != "joint": raise ValueError("forward_multiframe currently supports only text_mode='joint'.") - if pixel_values_sources.ndim != 5: + if isinstance(pixel_values_sources, torch.Tensor) and pixel_values_sources.ndim != 5: raise ValueError( "pixel_values_sources must have shape (B,N,3,H,W), " f"got {tuple(pixel_values_sources.shape)}." ) + if isinstance(pixel_values_sources, list): + if not pixel_values_sources: + raise ValueError("pixel_values_sources list must not be empty.") + if any(tensor.ndim != 4 for tensor in pixel_values_sources): + shapes = [tuple(tensor.shape) for tensor in pixel_values_sources] + raise ValueError(f"source slot tensors must have shape (B,3,H,W), got {shapes}.") if pixel_values_target.ndim != 4: raise ValueError( "pixel_values_target must have shape (B,3,H,W), " @@ -708,7 +731,15 @@ class FluxKleinTwoFrame(nn.Module): f"expected C={expected_channels} (or C={expected_channels // 4} before patchify)." ) - bsz, num_sources = pixel_values_sources.shape[:2] + if isinstance(pixel_values_sources, list): + bsz = pixel_values_target.shape[0] + num_sources = len(pixel_values_sources) + source_pixel_slots = pixel_values_sources + if any(tensor.shape[0] != bsz for tensor in source_pixel_slots): + raise ValueError("All source slot tensors must have the same batch size as target.") + else: + bsz, num_sources = pixel_values_sources.shape[:2] + source_pixel_slots = [pixel_values_sources[:, idx] for idx in range(num_sources)] device = pixel_values_target.device dtype = next(self.transformer.parameters()).dtype @@ -716,8 +747,8 @@ class FluxKleinTwoFrame(nn.Module): target_latents = _ensure_transformer_latent_channels(target_latents.to(device=device), "target") source_latents: list[torch.Tensor] = [] - for idx in range(num_sources): - source_latent = self.encode_image_latents(pixel_values_sources[:, idx]) + for idx, source_pixels in enumerate(source_pixel_slots): + source_latent = self.encode_image_latents(source_pixels) source_latent = _ensure_transformer_latent_channels( source_latent.to(device=device), f"source[{idx}]", @@ -736,12 +767,16 @@ class FluxKleinTwoFrame(nn.Module): packed_parts = [packed_target] img_id_parts = [target_ids] seq_lengths = [packed_target.shape[1]] - source_noise_list: list[torch.Tensor] = [] + source_noise_list: list[torch.Tensor | None] = [] for idx, source_latent in enumerate(source_latents): - source_noise = torch.randn_like(source_latent) + if self.source_input_mode == "condition": + source_noise = None + source_noisy = source_latent + else: + source_noise = torch.randn_like(source_latent) + source_noisy = (1 - sigma_b) * source_latent + sigma_b * source_noise source_noise_list.append(source_noise) - source_noisy = (1 - sigma_b) * source_latent + sigma_b * source_noise source_t_value = self.source_t + idx * self.source_t_step packed_source, source_ids = pack_latents(source_noisy, t_value=source_t_value) packed_parts.append(packed_source) @@ -788,13 +823,16 @@ class FluxKleinTwoFrame(nn.Module): loss_target = torch.mean((pred_target_unpacked - target_vel) ** 2) source_losses: list[torch.Tensor] = [] - for idx, (pred_source, source_ids, source_latent, source_noise) in enumerate( - zip(pred_parts[1:], img_id_parts[1:], source_latents, source_noise_list) - ): - _ = idx - pred_source_unpacked = unpack_latents(pred_source, source_ids) - source_vel = source_noise - source_latent - source_losses.append(torch.mean((pred_source_unpacked - source_vel) ** 2)) + if self.source_input_mode != "condition": + for idx, (pred_source, source_ids, source_latent, source_noise) in enumerate( + zip(pred_parts[1:], img_id_parts[1:], source_latents, source_noise_list) + ): + _ = idx + if source_noise is None: + raise RuntimeError("source_noise unexpectedly missing in denoise mode.") + pred_source_unpacked = unpack_latents(pred_source, source_ids) + source_vel = source_noise - source_latent + source_losses.append(torch.mean((pred_source_unpacked - source_vel) ** 2)) if source_losses: source_losses_tensor = torch.stack(source_losses) @@ -803,16 +841,68 @@ class FluxKleinTwoFrame(nn.Module): source_losses_tensor = None loss_source = torch.zeros((), device=loss_target.device, dtype=loss_target.dtype) - weighted_target = self.target_loss_weight * loss_target - weighted_source = ( - self.source_loss_weight * source_losses_tensor.sum() - if source_losses_tensor is not None - else torch.zeros((), device=loss_target.device, dtype=loss_target.dtype) - ) - normalizer = self.target_loss_weight + self.source_loss_weight * len(source_latents) - loss = (weighted_target + weighted_source) / max(normalizer, 1e-8) + if self.multiframe_loss_mode == "block_balanced": + loss = self.target_loss_weight * loss_target + self.source_loss_weight * loss_source + else: + weighted_target = self.target_loss_weight * loss_target + weighted_source = ( + self.source_loss_weight * source_losses_tensor.sum() + if source_losses_tensor is not None + else torch.zeros((), device=loss_target.device, dtype=loss_target.dtype) + ) + normalizer = self.target_loss_weight + self.source_loss_weight * len(source_latents) + loss = (weighted_target + weighted_source) / max(normalizer, 1e-8) return TwoFrameLoss(loss=loss, loss_target=loss_target, loss_source=loss_source) + def load_trainable_checkpoint(self, checkpoint: str | Path, strict: bool = True) -> tuple[int, int]: + path = Path(checkpoint).expanduser().resolve() + if not path.exists(): + raise FileNotFoundError(f"Trainable checkpoint not found: {path}") + if path.is_dir(): + candidates = [ + path / "flow_model.safetensors", + path / "flow_model.pt", + path / "pytorch_model.bin", + ] + file_path = next((candidate for candidate in candidates if candidate.exists()), None) + if file_path is None: + raise FileNotFoundError( + f"No trainable checkpoint found in {path}; expected flow_model.safetensors or flow_model.pt." + ) + base_dir = path + else: + file_path = path + base_dir = path.parent + + if file_path.suffix == ".safetensors": + state_dict = load_safetensors(str(file_path), device="cpu") + else: + raw = torch.load(file_path, map_location="cpu") + state_dict = raw.get("state_dict", raw) if isinstance(raw, dict) else raw + missing, unexpected = self.transformer.load_state_dict(state_dict, strict=strict) + + aux_path = base_dir / "twoframe_aux.pt" + if aux_path.exists(): + aux = torch.load(aux_path, map_location="cpu") + if self.text_segment_embed is not None and "text_segment_embed.weight" in aux: + self._copy_embedding_weight(self.text_segment_embed, aux["text_segment_embed.weight"]) + if self.image_frame_embed is not None and "image_frame_embed.weight" in aux: + self._copy_embedding_weight(self.image_frame_embed, aux["image_frame_embed.weight"]) + return len(missing), len(unexpected) + + @staticmethod + def _copy_embedding_weight(module: nn.Embedding, weight: torch.Tensor) -> None: + rows = min(module.weight.shape[0], weight.shape[0]) + cols = min(module.weight.shape[1], weight.shape[1]) + with torch.no_grad(): + module.weight[:rows, :cols].copy_(weight[:rows, :cols].to(module.weight.device, module.weight.dtype)) + if module.weight.shape[0] > rows and rows > 0: + for row in range(rows, module.weight.shape[0]): + source_row = min(row, rows - 1) + module.weight[row, :cols].copy_( + weight[source_row, :cols].to(module.weight.device, module.weight.dtype) + ) + def _extra_aux_state(self) -> dict[str, torch.Tensor | str | bool]: state: dict[str, torch.Tensor | str | bool] = { "format_version": "v1", @@ -909,11 +999,13 @@ class FluxKleinTwoFrame(nn.Module): "extra_embeddings": { "mode": self.extra_embed_mode, "policy": self.extra_embed_joint_policy, + "image_frame_embed_slots": self.image_frame_embed_slots, "enabled_text": self.text_segment_embed is not None, "enabled_image": self.image_frame_embed is not None, "strict_template": self.extra_embed_strict_template, "aux_file": "twoframe_aux.pt" if aux_enabled else None, }, + "multiframe_loss_mode": self.multiframe_loss_mode, } with Path(output_dir, "twoframe_checkpoint_meta.json").open("w", encoding="utf-8") as f: json.dump(meta, f, ensure_ascii=False, indent=2) diff --git a/twoframe/native_inference.py b/twoframe/native_inference.py index 8551951..e17122e 100644 --- a/twoframe/native_inference.py +++ b/twoframe/native_inference.py @@ -122,6 +122,7 @@ class Flux2NativeEngine: policy: str = "binary_full", strict_template: bool = True, zero_init: bool = True, + image_slots: int = 2, ) -> None: norm_mode = self._normalize_extra_embed_mode(mode) policy = str(policy).strip().lower() @@ -154,7 +155,7 @@ class Flux2NativeEngine: image_dim = int(getattr(self.flow, "in_channels", 0)) if image_dim <= 0: raise ValueError("Failed to infer in_channels for image frame embedding.") - self.image_frame_embed = torch.nn.Embedding(2, image_dim).to( + self.image_frame_embed = torch.nn.Embedding(int(image_slots), image_dim).to( device=self.device, dtype=self.dtype, ) @@ -338,12 +339,16 @@ class Flux2NativeEngine: elif "image_frame_embed.weight" in aux_state: if mode == "none": mode = "image_only" + image_slots = 2 + if "image_frame_embed.weight" in aux_state: + image_slots = int(aux_state["image_frame_embed.weight"].shape[0]) self.configure_extra_embeddings( mode=mode, policy=policy, strict_template=strict_template, zero_init=False, + image_slots=image_slots, ) if self.text_segment_embed is not None and "text_segment_embed.weight" in aux_state: