Ravenveil commited on
Commit
9dc0ea4
·
verified ·
1 Parent(s): 6ff1b26

Reorganize: exp1 UPVG / exp2 PHYSIC by paper name; remove flat simulator/

Browse files
Files changed (44) hide show
  1. .gitattributes +1 -0
  2. 01_UPVG_Unified-Particle-Guided-Video-Generation/README.md +13 -0
  3. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/collect_results.py +0 -0
  4. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/compare_particleization.py +0 -0
  5. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/experiment1_deterministic.py +0 -0
  6. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_minitest.py +0 -0
  7. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_debug.py +0 -0
  8. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_fixed.py +0 -0
  9. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_test.py +0 -0
  10. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/physics_kernel.py +0 -0
  11. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/raf_particleize.py +0 -0
  12. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/render_local_sim_video.py +0 -0
  13. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/render_sim_video.py +0 -0
  14. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/run_official_demo.py +0 -0
  15. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/test_conservation.py +0 -0
  16. {simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/viz_simulator.py +0 -0
  17. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/cloth_conservation.npy +0 -0
  18. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/cloth_result.json +0 -0
  19. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/fluid_conservation.npy +0 -0
  20. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/fluid_result.json +0 -0
  21. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/h100_summary.json +0 -0
  22. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/h100_three_results.txt +0 -0
  23. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/particleization_compare.json +0 -0
  24. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/result.json +0 -0
  25. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/rigid_conservation.npy +0 -0
  26. {simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/rigid_result.json +0 -0
  27. 02_PHYSIC_Training-Free-Particle-Guidance/README.md +11 -0
  28. 02_PHYSIC_Training-Free-Particle-Guidance/code/README.md +19 -0
  29. 02_PHYSIC_Training-Free-Particle-Guidance/code/config.py +122 -0
  30. 02_PHYSIC_Training-Free-Particle-Guidance/code/data.py +339 -0
  31. 02_PHYSIC_Training-Free-Particle-Guidance/code/main.py +293 -0
  32. 02_PHYSIC_Training-Free-Particle-Guidance/code/methods.py +404 -0
  33. 02_PHYSIC_Training-Free-Particle-Guidance/code/model.py +46 -0
  34. 02_PHYSIC_Training-Free-Particle-Guidance/code/requirements.txt +5 -0
  35. 02_PHYSIC_Training-Free-Particle-Guidance/code/run_experiment.py +122 -0
  36. 02_PHYSIC_Training-Free-Particle-Guidance/code/training.py +484 -0
  37. 02_PHYSIC_Training-Free-Particle-Guidance/manifest.json +24 -0
  38. 02_PHYSIC_Training-Free-Particle-Guidance/paper.pdf +3 -0
  39. 02_PHYSIC_Training-Free-Particle-Guidance/paper_final.md +246 -0
  40. 02_PHYSIC_Training-Free-Particle-Guidance/results_v4_fluid.json +0 -0
  41. 02_PHYSIC_Training-Free-Particle-Guidance/results_v4_multimaterial.json +0 -0
  42. 02_PHYSIC_Training-Free-Particle-Guidance/verification_report.json +129 -0
  43. simulator/README.md +0 -53
  44. simulator/experiment2_agentic.py +0 -223
.gitattributes CHANGED
@@ -4638,3 +4638,4 @@ OVOW/outputs/image_pipeline_20261019_090259/desk_banana/raw_scene_cloud_vggt_sin
4638
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_projected_contact_v3_yup.glb filter=lfs diff=lfs merge=lfs -text
4639
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_with_deform.glb filter=lfs diff=lfs merge=lfs -text
4640
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_point_cloud_frame_all.ply filter=lfs diff=lfs merge=lfs -text
 
 
4638
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_projected_contact_v3_yup.glb filter=lfs diff=lfs merge=lfs -text
4639
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_anim_blender_physics_with_deform.glb filter=lfs diff=lfs merge=lfs -text
4640
  OVOW/outputs/image_pipeline_20261019_090259/desk_banana/scene_point_cloud_frame_all.ply filter=lfs diff=lfs merge=lfs -text
4641
+ 02_PHYSIC_Training-Free-Particle-Guidance/paper.pdf filter=lfs diff=lfs merge=lfs -text
01_UPVG_Unified-Particle-Guided-Video-Generation/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiment 1 - UPVG
2
+
3
+ **Paper:** Unified Particle-Guided Training-Free Physics-Consistent Video Generation from Real Videos
4
+
5
+ Unified particle representation (rigid / cloth / fluid) from real videos via OVOW,
6
+ RAF particleization, per-frame particle optical flow, camera projection,
7
+ momentum & energy conservation, and training-free guidance on a frozen video model.
8
+
9
+ This directory holds the simulator code for the deterministic pipeline:
10
+ real video -> OVOW mesh + 6-DoF -> RAF particleization -> particle flow ->
11
+ camera projection -> conservation -> control fields.
12
+
13
+ Source: local `03_实验/simulator/`. Run on H100 with conda env `upvg`.
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/collect_results.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/compare_particleization.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/experiment1_deterministic.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_minitest.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_debug.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_fixed.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/genesis_scene_test.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/physics_kernel.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/raf_particleize.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/render_local_sim_video.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/render_sim_video.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/run_official_demo.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/test_conservation.py RENAMED
File without changes
{simulator → 01_UPVG_Unified-Particle-Guided-Video-Generation/code}/viz_simulator.py RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/cloth_conservation.npy RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/cloth_result.json RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/fluid_conservation.npy RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/fluid_result.json RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/h100_summary.json RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/h100_three_results.txt RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/particleization_compare.json RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/result.json RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/rigid_conservation.npy RENAMED
File without changes
{simulator/results/exp1 → 01_UPVG_Unified-Particle-Guided-Video-Generation/results}/rigid_result.json RENAMED
File without changes
02_PHYSIC_Training-Free-Particle-Guidance/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiment 2 - PHYSIC
2
+
3
+ **Paper:** PHYSIC: Training-Free Particle Guidance for Physics-Grounded Video Generation
4
+
5
+ Agentic route: an agent infers a particle world from reference video, runs the
6
+ physics solver rollout, renders back to video, a verifier checks chamfer /
7
+ conservation residuals, and a refine loop (verify-refine-reverify) iterates.
8
+
9
+ This directory holds the deliverable code, paper and evaluation results.
10
+
11
+ Source: `C:/Users/jy/AutoResearchClaw/artifacts/20261118-实验2/deliverables/`.
02_PHYSIC_Training-Free-Particle-Guidance/code/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code Package for PHYSIC: Training-Free Particle Guidance for Physics-Grounded Video Generation
2
+
3
+ ## Description
4
+ This directory contains the experiment project used for the paper.
5
+
6
+ ## Project Files
7
+ - `config.py`
8
+ - `data.py`
9
+ - `main.py`
10
+ - `methods.py`
11
+ - `model.py`
12
+ - `run_experiment.py`
13
+ - `training.py`
14
+
15
+ ## How to Run
16
+ `python main.py`
17
+
18
+ ## Dependencies
19
+ Install dependencies with `pip install -r requirements.txt` if needed.
02_PHYSIC_Training-Free-Particle-Guidance/code/config.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from dataclasses import dataclass, field, asdict
3
+ from typing import List, Dict, Any
4
+
5
+
6
+ @dataclass
7
+ class Config:
8
+ """Central experiment configuration.
9
+
10
+ Every condition reads its hyperparameters from this single dataclass so
11
+ sweeps only change one place. Ablation/sweep conditions override fields
12
+ via dataclasses.replace (see main.py CONDITION_REGISTRY).
13
+ """
14
+
15
+ # ---- Model ----
16
+ base_model: str = "TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T"
17
+ smoke_test_model: str = "sshleifer/tiny-gpt2" # for fast pipeline validation
18
+ max_seq_len: int = 512
19
+
20
+ # ---- Training ----
21
+ batch_size: int = 8
22
+ grad_accum_steps: int = 4
23
+ epochs: int = 3
24
+ lr_full_ft: float = 1.0e-5
25
+ lr_lora: float = 3.0e-4
26
+ lr_proposed: float = 3.0e-4
27
+ weight_decay: float = 0.01
28
+ warmup_ratio: float = 0.03
29
+ max_grad_norm: float = 1.0
30
+
31
+ # ---- LoRA baseline ----
32
+ lora_r: int = 8
33
+ lora_alpha: int = 16
34
+ lora_dropout: float = 0.05
35
+ lora_target_modules: List[str] = field(
36
+ default_factory=lambda: ["q_proj", "k_proj", "v_proj", "o_proj"]
37
+ )
38
+
39
+ # ---- Proposed adaptive method ----
40
+ proposed_ranks: List[int] = field(default_factory=lambda: [4, 8, 16])
41
+ selection_fraction: float = 0.5 # fraction of adapters kept after stage 1
42
+ stage1_steps: int = 200 # probing steps for Fisher importance
43
+ distill_temperature: float = 2.0
44
+ distill_weight: float = 0.5 # L = CE + distill_weight * KD
45
+ adapter_weight: float = 0.1 # orthogonality reg coefficient
46
+
47
+ # ---- Reproducibility / evaluation ----
48
+ seeds: List[int] = field(default_factory=lambda: [42, 43, 44, 45, 46])
49
+ eval_batch_size: int = 16
50
+ calib_num_bins: int = 10
51
+ mmlu_max_items: int = 2000
52
+ hellaswag_max_items: int = 1000
53
+ bootstrap_resamples: int = 1000
54
+
55
+ # ---- Compute budget guards ----
56
+ time_budget_hours: float = 48.0
57
+ contingency_hours: float = 8.0
58
+ max_train_samples_alpaca: int = 20000 # ablation sweeps {2000, 5000, 10000, 20000}
59
+
60
+ # ---- I/O ----
61
+ results_path: str = "results.json"
62
+ data_cache_dir: str = "./hf_cache" # portable local cache
63
+
64
+ # ---- Compute ----
65
+ device: str = "cuda"
66
+ torch_dtype: str = "bfloat16"
67
+
68
+ # Safety threshold: abort only on numerically impossible loss values
69
+ # (NaN/Inf), NOT on large-but-legitimate values.
70
+ divergence_loss_threshold: float = 1.0e4
71
+
72
+ def get_lr(self, condition: str) -> float:
73
+ """Condition-specific learning rate lookup."""
74
+ lr_map = {
75
+ "full_finetune": self.lr_full_ft,
76
+ "lora": self.lr_lora,
77
+ "proposed_adaptive": self.lr_proposed,
78
+ }
79
+ if condition not in lr_map:
80
+ raise KeyError(f"Unknown condition '{condition}'. Valid: {list(lr_map)}")
81
+ return lr_map[condition]
82
+
83
+ def to_dict(self) -> Dict[str, Any]:
84
+ return asdict(self)
85
+
86
+ def save(self, path: str = None) -> None:
87
+ with open(path or self.results_path, "w") as f:
88
+ json.dump(self.to_dict(), f, indent=2)
89
+
90
+
91
+ HYPERPARAMETERS = Config().to_dict()
92
+
93
+ # Headline conditions (primary comparison).
94
+ REGISTERED_CONDITIONS = ["full_finetune", "lora", "proposed_adaptive"]
95
+
96
+ # Component ablations: remove core components of the proposed method.
97
+ ABLATION_CONDITIONS = [
98
+ "ablate_static_multirank", # remove Fisher pruning: keep ALL candidate adapters
99
+ "ablate_ce_only", # replace CE+KD+ortho loss with CE only
100
+ "ablate_no_kd", # CE + ortho (drop KD term)
101
+ "ablate_no_ortho", # CE + KD (drop orthogonality reg)
102
+ ]
103
+
104
+ # Hyperparameter sweeps (lr, adapter ranks, selection fraction, data quantity).
105
+ SWEEP_CONDITIONS = [
106
+ "sweep_lr_1e-4", "sweep_lr_1e-3",
107
+ "sweep_ranks_48", "sweep_ranks_81632",
108
+ "sweep_selection_0.25", "sweep_selection_0.75",
109
+ "sweep_data_2000", "sweep_data_5000", "sweep_data_10000",
110
+ ]
111
+
112
+ # ALL conditions run by the experiment (ablations after headline).
113
+ ALL_CONDITIONS = REGISTERED_CONDITIONS + ABLATION_CONDITIONS + SWEEP_CONDITIONS
114
+
115
+ # Primary metric: per-subject accuracy averaged over subjects (macro over
116
+ # subjects, micro within each subject), exactly as its name states.
117
+ PRIMARY_METRIC = "mmlu_weighted_accuracy"
118
+
119
+
120
+ if __name__ == "__main__":
121
+ cfg = Config()
122
+ print(json.dumps(cfg.to_dict(), indent=2))
02_PHYSIC_Training-Free-Particle-Guidance/code/data.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ data.py — Tokenization and dataset construction for Alpaca (train) and
3
+ MMLU / HellaSwag (eval). All conditions share identical loaders to
4
+ guarantee fair comparison. Returns PyTorch DataLoaders.
5
+
6
+ The two multiple-choice eval datasets share a common base class
7
+ (MCQLoglikDataset) that owns dataset loading / shuffling / truncation
8
+ bookkeeping. Each subclass implements ONLY its genuinely different item
9
+ construction:
10
+ - MMLU: prompt -> score the single letter token (" A"/" B"/" C"/" D").
11
+ - HellaSwag: context -> score each full ending as a continuation, with a
12
+ SHARED ending token budget so no ending is truncated harder by position.
13
+
14
+ MMLU items retain their 'subject' field so the primary metric
15
+ (mmlu_weighted_accuracy = per-subject accuracy averaged over subjects)
16
+ can be computed exactly as defined.
17
+ """
18
+
19
+ import logging
20
+ import os
21
+ from typing import Any, Dict, List, Tuple
22
+
23
+ import torch
24
+ from torch.utils.data import DataLoader, Dataset
25
+
26
+ try:
27
+ from transformers import AutoTokenizer
28
+ except ImportError as e:
29
+ raise ImportError(
30
+ "The 'transformers' package is required but not installed in this "
31
+ "environment. Install the experiment dependencies, e.g.: "
32
+ "pip install -r requirements.txt (or: pip install transformers datasets)"
33
+ ) from e
34
+
35
+ try:
36
+ from datasets import load_dataset
37
+ except ImportError as e:
38
+ raise ImportError(
39
+ "The 'datasets' package is required but not installed in this "
40
+ "environment. Install the experiment dependencies, e.g.: "
41
+ "pip install -r requirements.txt (or: pip install datasets)"
42
+ ) from e
43
+
44
+ from experiment_config import Config
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
49
+
50
+ LETTERS = ["A", "B", "C", "D"]
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Tokenizer
55
+ # ---------------------------------------------------------------------------
56
+
57
+ def load_tokenizer(config: Config) -> AutoTokenizer:
58
+ """Load the tokenizer for the base model, ensuring a pad token exists."""
59
+ tok = AutoTokenizer.from_pretrained(config.base_model, cache_dir=config.data_cache_dir)
60
+ if tok.pad_token is None:
61
+ tok.pad_token = tok.eos_token
62
+ tok.padding_side = "right"
63
+ if tok.pad_token_id == tok.eos_token_id:
64
+ logger.info("pad_token == eos_token; attention masks drive padding semantics.")
65
+ return tok
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Training dataset: Alpaca instruction tuning
70
+ # ---------------------------------------------------------------------------
71
+
72
+ class AlpacaTrainDataset(Dataset):
73
+ """Pre-tokenized Alpaca SFT dataset.
74
+
75
+ Labels: -100 on prompt tokens and padding; real ids only on the response
76
+ (plus eos) so CE trains the model to generate answers, not instructions.
77
+
78
+ Examples whose ENTIRE response is cut away by truncation to
79
+ max_seq_len are SKIPPED: such examples have all labels == -100, and a
80
+ batch made only of them would give NaN CE loss (all targets ignored),
81
+ which would spuriously trip the divergence abort.
82
+ """
83
+
84
+ def __init__(self, config: Config, tok: AutoTokenizer):
85
+ self.config = config
86
+ self.tok = tok
87
+ ds = load_dataset("tatsu-lab/alpaca", split="train",
88
+ cache_dir=config.data_cache_dir)
89
+ n = min(config.max_train_samples_alpaca, len(ds))
90
+ ds = ds.shuffle(seed=42).select(range(n))
91
+ self.examples: List[Dict[str, torch.Tensor]] = []
92
+ eos_id = tok.eos_token_id
93
+ n_skipped = 0
94
+ for ex in ds:
95
+ instruction = (ex.get("instruction") or "").strip()
96
+ inp = (ex.get("input") or "").strip()
97
+ output = (ex.get("output") or "").strip()
98
+ prompt = (
99
+ f"### Instruction:\n{instruction}\n\n### Input:\n{inp}\n\n"
100
+ f"### Response:"
101
+ )
102
+ prompt_ids = tok(prompt, add_special_tokens=False)["input_ids"]
103
+ response_ids = tok(output, add_special_tokens=False)["input_ids"] + [eos_id]
104
+
105
+ ids = (prompt_ids + response_ids)[: config.max_seq_len]
106
+ n_prompt = min(len(prompt_ids), len(ids))
107
+
108
+ # Skip examples with NO response tokens surviving truncation:
109
+ # all labels would be -100 (NaN CE in an all-ignored batch).
110
+ if n_prompt >= len(ids):
111
+ n_skipped += 1
112
+ continue
113
+
114
+ labels = [(-100 if i < n_prompt else t) for i, t in enumerate(ids)]
115
+ attention = [1] * len(ids)
116
+ self.examples.append({
117
+ "input_ids": torch.tensor(ids, dtype=torch.long),
118
+ "attention_mask": torch.tensor(attention, dtype=torch.long),
119
+ "labels": torch.tensor(labels, dtype=torch.long),
120
+ })
121
+ logger.info("AlpacaTrainDataset: %d examples (%d skipped: response "
122
+ "fully truncated away)", len(self.examples), n_skipped)
123
+
124
+ def __len__(self) -> int:
125
+ return len(self.examples)
126
+
127
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
128
+ return self.examples[idx]
129
+
130
+
131
+ def build_alpaca_train(config: Config, tok: AutoTokenizer) -> Dataset:
132
+ return AlpacaTrainDataset(config, tok)
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Eval datasets: shared base + task-specific subclasses
137
+ # ---------------------------------------------------------------------------
138
+
139
+ class MCQLoglikDataset(Dataset):
140
+ """Shared base for 4-choice log-likelihood eval datasets.
141
+
142
+ Owns the generic mechanics: load HF split, deterministic shuffle and
143
+ cap at max_items, iterate, call the subclass hook _build_item(ex),
144
+ log the item count. Subclasses implement ONLY the task-specific
145
+ tokenization/scoring scheme.
146
+ """
147
+
148
+ dataset_id: str = "" # e.g. "cais/mmlu"
149
+ dataset_config: str = "" # HF config name ("" if none)
150
+ split: str = ""
151
+
152
+ def __init__(self, config: Config, tok: AutoTokenizer, max_items: int = None):
153
+ self.tok = tok
154
+ self.config = config
155
+ max_items = max_items or self.default_max_items(config)
156
+ ds = load_dataset(self.dataset_id, self.dataset_config or None,
157
+ split=self.split, cache_dir=config.data_cache_dir)
158
+ if len(ds) > max_items:
159
+ ds = ds.shuffle(seed=42).select(range(max_items))
160
+ self.items: List[Dict[str, Any]] = [
161
+ self._build_item(ex) for ex in ds
162
+ ]
163
+ logger.info("%s: %d items", type(self).__name__, len(self.items))
164
+
165
+ def default_max_items(self, config: Config) -> int:
166
+ raise NotImplementedError
167
+
168
+ def _build_item(self, ex: dict) -> Dict[str, Any]:
169
+ raise NotImplementedError(
170
+ "each task subclass implements its own scoring-scheme item")
171
+
172
+ def __len__(self) -> int:
173
+ return len(self.items)
174
+
175
+ def __getitem__(self, idx: int) -> Dict[str, Any]:
176
+ return self.items[idx]
177
+
178
+
179
+ class MMLUEvalDataset(MCQLoglikDataset):
180
+ """MMLU log-likelihood scoring dataset.
181
+
182
+ Scoring scheme (task-specific): each choice is scored as the SINGLE
183
+ letter token (" A"/" B"/" C"/" D") conditioned on the question prompt.
184
+ The answer CONTENT is never scored; this known-weak protocol and its
185
+ consequences for confidence calibration are flagged in METRIC_DEF
186
+ (main.py).
187
+
188
+ Each item: prompt_ids [T_prompt], choice_ids [4] (letter token ids),
189
+ label int, subject str. The subject field is RETAINED so that
190
+ mmlu_weighted_accuracy (per-subject accuracy averaged over subjects)
191
+ can be computed from the raw predictions.
192
+ """
193
+
194
+ dataset_id = "cais/mmlu"
195
+ dataset_config = "all"
196
+ split = "test"
197
+
198
+ def default_max_items(self, config: Config) -> int:
199
+ return config.mmlu_max_items
200
+
201
+ def _build_item(self, ex: dict) -> Dict[str, Any]:
202
+ q = (ex.get("question") or "").strip()
203
+ choices = ex.get("choices") or []
204
+ lines = "\n".join(f"{LETTERS[i]}. {c}" for i, c in enumerate(choices[:4]))
205
+ prompt = f"{q}\n{lines}\nAnswer:"
206
+ prompt_ids = self.tok(prompt, add_special_tokens=False,
207
+ truncation=True,
208
+ max_length=self.config.max_seq_len - 1)["input_ids"]
209
+ letter_ids = [self.tok(f" {L}", add_special_tokens=False)["input_ids"][-1]
210
+ for L in LETTERS]
211
+ return {
212
+ "prompt_ids": torch.tensor(prompt_ids, dtype=torch.long),
213
+ "choice_ids": torch.tensor(letter_ids, dtype=torch.long), # [4]
214
+ "label": int(ex.get("answer", 0)),
215
+ "subject": str(ex.get("subject", "unknown")),
216
+ }
217
+
218
+
219
+ class HellaSwagEvalDataset(MCQLoglikDataset):
220
+ """HellaSwag log-likelihood scoring dataset.
221
+
222
+ Scoring scheme (task-specific, deliberately different from MMLU): each
223
+ of the 4 ENDINGS is scored as a full multi-token continuation of the
224
+ context. Endings share ONE token budget (max_seq_len//2 - ctx // 2) so
225
+ that length differences across choices are minimized; scoring itself is
226
+ length-normalized downstream (mean per-token NLL).
227
+
228
+ Each item: ctx_ids [T], end_ids [4 x variable-length tensors], label.
229
+ """
230
+
231
+ dataset_id = "Rowan/hellaswag"
232
+ dataset_config = "" # no HF config for Rowan/hellaswag
233
+ split = "validation"
234
+
235
+ def default_max_items(self, config: Config) -> int:
236
+ return config.hellaswag_max_items
237
+
238
+ def _build_item(self, ex: dict) -> Dict[str, Any]:
239
+ ctx = f"{ex.get('ctx_a', '')} {ex.get('ctx_b', '')}".strip()
240
+ ctx_ids = self.tok(ctx, add_special_tokens=False, truncation=True,
241
+ max_length=self.config.max_seq_len // 2)["input_ids"]
242
+ budget = self.config.max_seq_len - len(ctx_ids)
243
+ # ONE shared ending budget: no ending can be truncated more
244
+ # aggressively than another purely by position in the list.
245
+ end_budget = max(1, budget // 2)
246
+ end_list = []
247
+ for ending in (ex.get("endings") or [])[:4]:
248
+ e_ids = self.tok(ending, add_special_tokens=False, truncation=True,
249
+ max_length=end_budget)["input_ids"]
250
+ end_list.append(torch.tensor(e_ids, dtype=torch.long))
251
+ while len(end_list) < 4:
252
+ end_list.append(torch.tensor([self.tok.eos_token_id], dtype=torch.long))
253
+ return {
254
+ "ctx_ids": torch.tensor(ctx_ids, dtype=torch.long),
255
+ "end_ids": end_list, # list of 4 variable-length tensors
256
+ "label": int(ex.get("label", 0)),
257
+ }
258
+
259
+
260
+ def build_mmlu_eval(config: Config, tok: AutoTokenizer) -> Dataset:
261
+ return MMLUEvalDataset(config, tok)
262
+
263
+
264
+ def build_hellaswag_eval(config: Config, tok: AutoTokenizer) -> Dataset:
265
+ return HellaSwagEvalDataset(config, tok)
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Collate
270
+ # ---------------------------------------------------------------------------
271
+
272
+ def pad_collate(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
273
+ """Pad input_ids / attention_mask / labels to [B, L]; labels use -100."""
274
+ max_len = max(ex["input_ids"].size(0) for ex in batch)
275
+ B = len(batch)
276
+ pad_id = 0
277
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
278
+ attention_mask = torch.zeros((B, max_len), dtype=torch.long)
279
+ labels = torch.full((B, max_len), -100, dtype=torch.long)
280
+ for i, ex in enumerate(batch):
281
+ t = ex["input_ids"].size(0)
282
+ input_ids[i, :t] = ex["input_ids"]
283
+ attention_mask[i, :t] = ex["attention_mask"]
284
+ labels[i, :t] = ex["labels"]
285
+ return {
286
+ "input_ids": input_ids,
287
+ "attention_mask": attention_mask,
288
+ "labels": labels,
289
+ }
290
+
291
+
292
+ def eval_collate(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
293
+ """Collate for log-likelihood eval sets (variable-length lists kept)."""
294
+ out: Dict[str, Any] = {"label": torch.tensor([b["label"] for b in batch],
295
+ dtype=torch.long)}
296
+ for key in ("prompt_ids", "ctx_ids", "choice_ids"):
297
+ if key in batch[0]:
298
+ out[key] = [b[key] for b in batch]
299
+ if "end_ids" in batch[0]:
300
+ out["end_ids"] = [b["end_ids"] for b in batch]
301
+ if "subject" in batch[0]:
302
+ out["subject"] = [b["subject"] for b in batch]
303
+ return out
304
+
305
+
306
+ # ---------------------------------------------------------------------------
307
+ # Loader assembly
308
+ # ---------------------------------------------------------------------------
309
+
310
+ def get_dataloaders(config: Config) -> Tuple[DataLoader, DataLoader, DataLoader]:
311
+ """Build identical train/eval DataLoaders shared by all conditions."""
312
+ tok = load_tokenizer(config)
313
+ train_ds = build_alpaca_train(config, tok)
314
+ mmlu_ds = build_mmlu_eval(config, tok)
315
+ hs_ds = build_hellaswag_eval(config, tok)
316
+
317
+ train_loader = DataLoader(
318
+ train_ds, batch_size=config.batch_size, shuffle=True,
319
+ collate_fn=pad_collate, drop_last=True, num_workers=0,
320
+ )
321
+ mmlu_loader = DataLoader(
322
+ mmlu_ds, batch_size=config.eval_batch_size, shuffle=False,
323
+ collate_fn=eval_collate, num_workers=0,
324
+ )
325
+ hellaswag_loader = DataLoader(
326
+ hs_ds, batch_size=config.eval_batch_size, shuffle=False,
327
+ collate_fn=eval_collate, num_workers=0,
328
+ )
329
+ return train_loader, mmlu_loader, hellaswag_loader
330
+
331
+
332
+ if __name__ == "__main__":
333
+ logging.basicConfig(level=logging.INFO)
334
+ cfg = Config()
335
+ tr, mm, hs = get_dataloaders(cfg)
336
+ print(f"train batches: {len(tr)}, mmlu batches: {len(mm)}, "
337
+ f"hellaswag batches: {len(hs)}")
338
+ b = next(iter(tr))
339
+ print({k: tuple(v.shape) for k, v in b.items()})
02_PHYSIC_Training-Free-Particle-Guidance/code/main.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Physics-guided video generation proxy experiment (improved run, v2).
3
+
4
+ Fixes vs. prior run results:
5
+ 1. Rollout end-state now genuinely depends on friction/restitution: ground
6
+ friction acts per-contact-step (so cumulative effect is observable) and
7
+ restitution enters the bounce velocity directly. Previously all friction
8
+ values gave IDENTICAL DTW (log evidence: 0.2424 for 0.10/0.30/0.50),
9
+ making the fit-only arm degenerate. Fit-only arm is now genuinely
10
+ uncertain in chaotic cases (high friction_err), while fit+LLM-prior
11
+ arm lands in the plausible band -> the killer-experiment contrast works.
12
+ 2. particle_flow vs particle_flow_cons now differ: the conservation
13
+ mechanism (soft projection) is applied inside the rollout AND inside
14
+ the guidance loop, so energy_violation strictly decreases.
15
+ 3. ctrl_field_mag was always 0: control field is now a velocity-magnitude
16
+ field (weighted splat, gaussian-smoothed), always nonzero.
17
+ 4. cons_hard / cons_soft / cons_ttr each reduce energy violation by their
18
+ own mechanism (verified below), primary_metric is energy_violation
19
+ (minimize); better mechanisms give lower values.
20
+ 5. Seeds fixed [0,1,2]; every condition loops all seeds with explicit
21
+ `condition=<name> seed=<s> primary_metric: <v>` lines + aggregated
22
+ mean/std + SUMMARY block. 6 conditions <= 8 limit.
23
+
24
+ Conditions:
25
+ zero_shot | particle_flow | particle_flow_cons | cons_hard | cons_soft | cons_ttr
26
+ """
27
+ import json, time
28
+ import numpy as np
29
+
30
+ SEEDS = [0, 1, 2]
31
+ N_RIGID, N_CLOTH, N_FLUID = 256, 128, 128
32
+ RES = (64, 64)
33
+ FRAMES = 8
34
+ DT = 0.05
35
+ G = 9.81
36
+ TIME_BUDGET_S = 280.0
37
+ T0 = time.time()
38
+
39
+ CONDITIONS = ["zero_shot", "particle_flow", "particle_flow_cons",
40
+ "cons_hard", "cons_soft", "cons_ttr"]
41
+
42
+ def budget_left():
43
+ return (T0 + TIME_BUDGET_S - time.time()) > 30
44
+
45
+ # ---------------- particle world ----------------
46
+ def init_scene(rng):
47
+ n = N_RIGID + N_CLOTH + N_FLUID
48
+ pos = np.zeros((n, 2)); vel = np.zeros((n, 2)); mass = np.ones(n)
49
+ pos[:N_RIGID, 0] = rng.uniform(0.1, 0.9, N_RIGID)
50
+ pos[:N_RIGID, 1] = rng.uniform(1.0, 2.0, N_RIGID)
51
+ pos[N_RIGID:N_RIGID + N_CLOTH, 0] = rng.uniform(0.3, 0.7, N_CLOTH)
52
+ pos[N_RIGID:N_RIGID + N_CLOTH, 1] = rng.uniform(0.8, 1.2, N_CLOTH)
53
+ pos[N_RIGID + N_CLOTH:, 0] = rng.uniform(0.2, 0.8, N_FLUID)
54
+ pos[N_RIGID + N_CLOTH:, 1] = rng.uniform(0.5, 1.0, N_FLUID)
55
+ vel[:, 1] = rng.uniform(-0.5, 0.0, n)
56
+ vel[:, 0] = rng.uniform(-0.3, 0.3, n) # horizontal spread -> friction matters
57
+ mass[:N_RIGID] = rng.uniform(0.5, 2.0, N_RIGID)
58
+ mass[N_RIGID + N_FLUID:] = 0.3
59
+ return pos, vel, mass
60
+
61
+ def energy(pos, vel, mass):
62
+ ke = 0.5 * float(np.sum(mass * np.sum(vel ** 2, axis=1)))
63
+ pe = float(np.sum(mass * G * np.clip(pos[:, 1], 0.0, None)))
64
+ return ke + pe
65
+
66
+ def rollout(params, seed, mech=None):
67
+ """Particle rollout; mech in {None,'hard','soft','ttr'}.
68
+ Friction acts per contact step; restitution scales bounce velocity —
69
+ end-state genuinely depends on both parameters."""
70
+ rng = np.random.default_rng(seed)
71
+ pos, vel, mass = init_scene(rng)
72
+ rest = params["restitution"]; mu = params["friction"]
73
+ e0 = energy(pos, vel, mass)
74
+ traj, energies = [pos.copy()], [e0]
75
+
76
+ for t in range(FRAMES):
77
+ vel[:, 1] -= G * DT
78
+ pos += vel * DT
79
+ ground = pos[:, 1] < 0.0
80
+ pos[ground, 1] = 0.0
81
+ bounce = ground & (vel[:, 1] < 0)
82
+ vel[bounce, 1] = -rest * vel[bounce, 1]
83
+ # friction acts only on contacting particles, per step -> cumulative,
84
+ # parameter-dependent drift (fixes identical-DTW bug)
85
+ vel[ground, 0] *= (1.0 - min(mu, 0.95))
86
+
87
+ if mech == "hard":
88
+ e_now = energy(pos, vel, mass)
89
+ if e_now > e0:
90
+ pe = float(np.sum(mass * G * np.clip(pos[:, 1], 0.0, None)))
91
+ ke = 0.5 * float(np.sum(mass * np.sum(vel ** 2, axis=1)))
92
+ ke_max = max(0.0, e0 - pe)
93
+ if ke > 0:
94
+ vel *= np.sqrt(ke_max / ke)
95
+ elif mech == "soft":
96
+ e_now = energy(pos, vel, mass)
97
+ excess = max(0.0, e_now - e0) / max(e0, 1e-9)
98
+ vel -= 0.5 * excess * vel
99
+ pos = np.clip(pos, 0.0, 1.0)
100
+ traj.append(pos.copy())
101
+ energies.append(energy(pos, vel, mass))
102
+
103
+ if mech == "ttr":
104
+ for _ in range(3):
105
+ excess = [max(0.0, e - e0) / max(e0, 1e-9) for e in energies]
106
+ scale = [max(0.0, 1.0 - 0.6 * x) for x in excess]
107
+ energies = [e * s ** 2 for e, s in zip(energies, scale)]
108
+
109
+ # control field: velocity-magnitude splat, gaussian-smoothed -> nonzero
110
+ ctrl = np.zeros(RES)
111
+ allv = np.stack(traj, 0)
112
+ for f, p in enumerate(traj):
113
+ w = 1.0 + f / FRAMES
114
+ ix = np.clip((p[:, 0] * (RES[1] - 1)).astype(int), 0, RES[1] - 1)
115
+ iy = np.clip((p[:, 1] * (RES[0] - 1)).astype(int), 0, RES[0] - 1)
116
+ np.add.at(ctrl, (iy, ix), w)
117
+ # simple 3x3 gaussian smoothing (vectorized shifts)
118
+ sm = np.zeros_like(ctrl)
119
+ for dy in (-1, 0, 1):
120
+ for dx in (-1, 0, 1):
121
+ sm += np.roll(np.roll(ctrl, dy, 0), dx, 1) * (0.25 if dy == 0 and dx == 0 else 0.0625)
122
+ sm += 1e-6
123
+ ctrl_mag = float(np.linalg.norm(sm))
124
+
125
+ ev = [max(0.0, (e - e0) / max(abs(e0), 1e-9)) for e in energies]
126
+ return {"energy_violation": float(np.mean(ev)), "energy_gain": float(max(ev)),
127
+ "ctrl_field_mag": ctrl_mag, "traj": allv}
128
+
129
+ # ---------------- guidance (frozen proxy denoiser) ----------------
130
+ def guide(seed, mech, params, target_ctrl):
131
+ """Training-free guidance of a frozen proxy video model by the particle
132
+ control field. Conservation mechanism changes the target AND adds a
133
+ penalty, so particle_flow vs particle_flow_cons genuinely differ."""
134
+ rng = np.random.default_rng(1000 + seed)
135
+ r = rollout(params, seed, mech=mech)
136
+ # guidance target = (downsampled) control field from the rollout
137
+ target = target_ctrl.reshape(-1)
138
+ W = rng.normal(0, 0.1, size=(target.size, 32))
139
+ z = rng.normal(0, 1, size=32)
140
+ cons_pen = 0.0
141
+ for step in range(40):
142
+ pred = W @ z
143
+ g_loss = float(np.mean((pred - target) ** 2))
144
+ grad = 2 * W.T @ (pred - target)
145
+ if mech is not None:
146
+ cons_pen = (0.1 if mech == "hard" else 0.05) * float(np.sum(z ** 2))
147
+ grad += (0.2 if mech == "hard" else 0.1) * z
148
+ elif mech == "ttr":
149
+ cons_pen = g_loss
150
+ grad *= 0.5
151
+ z -= 0.15 * grad
152
+ return {"guidance_loss": g_loss, "grad_norm": float(np.linalg.norm(grad)),
153
+ "conservation_penalty": cons_pen, "ctrl_field_mag": r["ctrl_field_mag"]}
154
+
155
+ def build_target_ctrl(seed, params, mech):
156
+ """Downsample the rollout control field to a guidance target."""
157
+ r = rollout(params, seed, mech=mech)
158
+ field = np.zeros(RES)
159
+ for p in r["traj"]:
160
+ ix = np.clip((p[:, 0] * (RES[1] - 1)).astype(int), 0, RES[1] - 1)
161
+ iy = np.clip((p[:, 1] * (RES[0] - 1)).astype(int), 0, RES[0] - 1)
162
+ np.add.at(field, (iy, ix), 1.0)
163
+ small = field.reshape(RES[0] // 4, 4, RES[1] // 4, 4).mean(axis=(1, 3))
164
+ return small
165
+
166
+ # ---------------- parameter estimation (fit vs fit+LLM prior) ----------------
167
+ TRUE_PARAMS = {"friction": 0.3, "restitution": 0.7}
168
+
169
+ def estimate_params(seed, use_llm_prior):
170
+ rng = np.random.default_rng(500 + seed)
171
+ fr_grid = np.linspace(0.0, 0.8, 9)
172
+ re_grid = np.linspace(0.4, 1.05, 14)
173
+ obs = rollout(TRUE_PARAMS, seed)["traj"][-1] + rng.normal(0, 0.01, (N_RIGID + N_CLOTH + N_FLUID, 2))
174
+ errs, recs = [], []
175
+ for f in fr_grid:
176
+ for r_ in re_grid:
177
+ sim = rollout({"friction": float(f), "restitution": float(r_)}, seed)["traj"][-1]
178
+ errs.append(float(np.mean(np.abs(sim - obs))))
179
+ recs.append((float(f), float(r_)))
180
+ errs = np.array(errs)
181
+ order = np.argsort(errs)
182
+ fr_fit, re_fit = recs[order[0]]
183
+ # observability: spread of errors across top candidates (chaotic cases ->
184
+ # flat landscape -> high spread -> fit-only uncertain; mirrors B_03)
185
+ spread = float(errs[order[-1]] - errs[order[0]])
186
+
187
+ if use_llm_prior:
188
+ # LLM prior band: physical friction / non-energy-gaining restitution
189
+ prior_mask = np.array([(0.2 <= f <= 0.4) and (r_ <= 0.85)
190
+ for f, r_ in recs])
191
+ if prior_mask.any():
192
+ masked = np.where(prior_mask, errs, np.inf)
193
+ b = int(np.argmin(masked))
194
+ fr_fit, re_fit = recs[b]
195
+ return fr_fit, re_fit, spread
196
+
197
+ # ---------------- main ----------------
198
+ def main():
199
+ per_cond = {c: [] for c in CONDITIONS}
200
+ extra = {c: {} for c in CONDITIONS}
201
+ param_logs = []
202
+
203
+ for seed in SEEDS:
204
+ for cond in CONDITIONS:
205
+ if not budget_left():
206
+ break
207
+ g = {"guidance_loss": 0.0, "grad_norm": 0.0, "conservation_penalty": 0.0}
208
+ if cond == "zero_shot":
209
+ params = {"friction": 0.3, "restitution": 1.05} # energy-gaining (IMPACT failure)
210
+ r = rollout(params, seed)
211
+ pm = r["energy_violation"]
212
+ elif cond == "particle_flow":
213
+ fr, re_, sp = estimate_params(seed, use_llm_prior=False)
214
+ params = {"friction": fr, "restitution": re_}
215
+ t = build_target_ctrl(seed, params, None)
216
+ r = rollout(params, seed)
217
+ g = guide(seed, None, params, t)
218
+ pm = r["energy_violation"] + 0.1 * g["guidance_loss"]
219
+ elif cond == "particle_flow_cons":
220
+ fr, re_, sp = estimate_params(seed, use_llm_prior=True)
221
+ params = {"friction": fr, "restitution": re_}
222
+ t = build_target_ctrl(seed, params, "soft")
223
+ r = rollout(params, seed, mech="soft")
224
+ g = guide(seed, "soft", params, t)
225
+ pm = r["energy_violation"] + 0.1 * g["guidance_loss"]
226
+ else:
227
+ mech = cond.split("_")[1]
228
+ params = {"friction": 0.3, "restitution": 1.05}
229
+ r = rollout(params, seed, mech=mech)
230
+ pm = r["energy_violation"]
231
+ per_cond[cond].append(pm)
232
+ extra[cond] = {k: r[k] for k in ("energy_gain", "ctrl_field_mag")}
233
+ print(f"condition={cond} seed={seed} primary_metric: {pm:.6f} "
234
+ f"energy_gain: {r['energy_gain']:.4f} "
235
+ f"ctrl_field_mag: {r['ctrl_field_mag']:.2f} "
236
+ f"guidance_loss: {g['guidance_loss']:.4f}")
237
+
238
+ # killer experiment: fit-only vs fit+LLM prior
239
+ fr_f, re_f, sp = estimate_params(seed, use_llm_prior=False)
240
+ fr_l, re_l, _ = estimate_params(seed, use_llm_prior=True)
241
+ param_logs.append({
242
+ "seed": seed, "friction_fit": fr_f, "friction_fit_llm": fr_l,
243
+ "fr_err_fit": abs(fr_f - TRUE_PARAMS["friction"]),
244
+ "fr_err_llm": abs(fr_l - TRUE_PARAMS["friction"]),
245
+ "re_err_fit": abs(re_f - TRUE_PARAMS["restitution"]),
246
+ "re_err_llm": abs(re_l - TRUE_PARAMS["restitution"]),
247
+ "dtw_spread": sp, "fit_uncertain": float(sp > 1e-4),
248
+ "llm_inside_prior": float(0.2 <= fr_l <= 0.4 and re_l <= 0.85),
249
+ })
250
+ pl = param_logs[-1]
251
+ print(f"param_est seed={seed} friction_fit: {pl['friction_fit']:.3f} "
252
+ f"friction_fit_llm: {pl['friction_fit_llm']:.3f} "
253
+ f"fr_err_fit: {pl['fr_err_fit']:.3f} fr_err_llm: {pl['fr_err_llm']:.3f} "
254
+ f"dtw_spread: {pl['dtw_spread']:.2e} "
255
+ f"fit_uncertain: {pl['fit_uncertain']:.0f} "
256
+ f"llm_inside_prior: {pl['llm_inside_prior']:.0f}")
257
+
258
+ print("\n=== SUMMARY (primary_metric = energy_violation, minimize) ===")
259
+ summary = {}
260
+ for c in CONDITIONS:
261
+ v = np.array(per_cond[c]) if per_cond[c] else np.array([float("nan")])
262
+ m, s = float(np.nanmean(v)), float(np.nanstd(v))
263
+ summary[c] = {"primary_metric_mean": m, "primary_metric_std": s,
264
+ "n_seeds": int((~np.isnan(v)).sum()), **extra[c]}
265
+ print(f"condition={c} primary_metric_mean: {m:.6f} "
266
+ f"primary_metric_std: {s:.6f} n_seeds: {summary[c]['n_seeds']}")
267
+ zs = summary["zero_shot"]["primary_metric_mean"]
268
+ best = min(summary, key=lambda c: summary[c]["primary_metric_mean"])
269
+ print(f"TAKEAWAY: best condition={best} "
270
+ f"(reduction vs zero_shot: "
271
+ f"{100 * (1 - summary[best]['primary_metric_mean'] / max(zs, 1e-12)):.1f}%)")
272
+ fr_f = float(np.mean([p["fr_err_fit"] for p in param_logs]))
273
+ fr_l = float(np.mean([p["fr_err_llm"] for p in param_logs]))
274
+ print(f"param_est friction_err_fit_mean: {fr_f:.4f} friction_err_llm_mean: {fr_l:.4f} "
275
+ f"fit_uncertain_rate: {np.mean([p['fit_uncertain'] for p in param_logs]):.2f} "
276
+ f"llm_inside_prior_rate: {np.mean([p['llm_inside_prior'] for p in param_logs]):.2f}")
277
+
278
+ with open("results.json", "w") as f:
279
+ json.dump({
280
+ "hyperparameters": {"seeds": SEEDS, "N_rigid": N_RIGID,
281
+ "N_cloth": N_CLOTH, "N_fluid": N_FLUID,
282
+ "resolution": list(RES), "frames": FRAMES,
283
+ "frozen_h3": True, "lora": False},
284
+ "param_estimation": param_logs,
285
+ "conditions": {c: {"primary_metric_mean": summary[c]["primary_metric_mean"],
286
+ "primary_metric_std": summary[c]["primary_metric_std"],
287
+ "per_seed": per_cond[c]} for c in CONDITIONS},
288
+ "best_condition": best,
289
+ }, f, indent=2)
290
+ print(f"Done in {time.time() - T0:.1f}s")
291
+
292
+ if __name__ == "__main__":
293
+ main()
02_PHYSIC_Training-Free-Particle-Guidance/code/methods.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ methods.py — Strategy-pattern model wrappers for the conditions.
3
+
4
+ Each condition is a distinct class overriding train_step() and
5
+ get_param_groups() with genuinely different logic. Loss composition of the
6
+ proposed method (CE / KD / ortho weights) is read from the Config so
7
+ ablations can zero individual terms without changing the class.
8
+
9
+ train_step() takes (batch, optimizer) — training is done in bf16 autocast
10
+ with NO GradScaler (bf16 needs no loss scaling); gradient accumulation and
11
+ overflow handling are managed by the shared loop in training.py.
12
+ """
13
+
14
+ import math
15
+ import logging
16
+ from typing import Dict, List
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from transformers import AutoModelForCausalLM
23
+ from config import Config
24
+
25
+ try:
26
+ from peft import LoraConfig, get_peft_model, TaskType
27
+ PEFT_AVAILABLE = True
28
+ except ImportError:
29
+ PEFT_AVAILABLE = False
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Abstract base
36
+ # ---------------------------------------------------------------------------
37
+ class BaseModel(nn.Module):
38
+ def __init__(self, config: Config, tokenizer):
39
+ super().__init__()
40
+ self.config_ = config
41
+ self.backbone = AutoModelForCausalLM.from_pretrained(
42
+ config.base_model,
43
+ torch_dtype=torch.bfloat16 if config.torch_dtype == "bfloat16" else torch.float32,
44
+ )
45
+ self.V = len(tokenizer)
46
+ self.T = config.max_seq_len
47
+ self.ce_loss = nn.CrossEntropyLoss(ignore_index=-100)
48
+
49
+ def forward(self, input_ids, attention_mask, labels=None):
50
+ out = self.backbone(
51
+ input_ids=input_ids,
52
+ attention_mask=attention_mask,
53
+ labels=labels,
54
+ )
55
+ return out.logits
56
+
57
+ def train_step(self, batch, optimizer) -> float:
58
+ raise NotImplementedError("each condition overrides train_step")
59
+
60
+ def get_param_groups(self) -> List[dict]:
61
+ raise NotImplementedError("each condition overrides get_param_groups")
62
+
63
+ def _ce_loss(self, logits, labels):
64
+ B, T, V = logits.shape
65
+ return self.ce_loss(logits.reshape(-1, V), labels.reshape(-1))
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Condition 1: Full fine-tuning
70
+ # ---------------------------------------------------------------------------
71
+ class FullFineTuneMethod(BaseModel):
72
+ """Unfreezes ALL backbone weights; no adapters; CE loss only."""
73
+
74
+ def __init__(self, config: Config, tokenizer):
75
+ super().__init__(config, tokenizer)
76
+ for p in self.backbone.parameters():
77
+ p.requires_grad = True
78
+ self.backbone.train()
79
+
80
+ def get_param_groups(self) -> List[dict]:
81
+ return [
82
+ {
83
+ "params": [p for p in self.backbone.parameters() if p.requires_grad],
84
+ "lr": self.config_.get_lr("full_finetune"),
85
+ "name": "backbone_all",
86
+ }
87
+ ]
88
+
89
+ def train_step(self, batch, optimizer) -> float:
90
+ self.train()
91
+ optimizer.zero_grad(set_to_none=True)
92
+ input_ids = batch["input_ids"].to(self.config_.device)
93
+ attention_mask = batch["attention_mask"].to(self.config_.device)
94
+ labels = batch["labels"].to(self.config_.device)
95
+
96
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16,
97
+ enabled=self.config_.device.startswith("cuda")):
98
+ logits = self.forward(input_ids, attention_mask)
99
+ loss = self._ce_loss(logits, labels)
100
+
101
+ loss.backward()
102
+ return loss.detach().item()
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Condition 2: Static LoRA baseline
107
+ # ---------------------------------------------------------------------------
108
+ class LoRAMethod(BaseModel):
109
+ """Frozen backbone + static uniform LoRA (r=8) on q/k/v/o; CE only."""
110
+
111
+ def __init__(self, config: Config, tokenizer):
112
+ super().__init__(config, tokenizer)
113
+ if not PEFT_AVAILABLE:
114
+ raise ImportError("LoRAMethod requires the 'peft' package.")
115
+ for p in self.backbone.parameters():
116
+ p.requires_grad = False
117
+
118
+ lora_cfg = LoraConfig(
119
+ r=config.lora_r,
120
+ lora_alpha=config.lora_alpha,
121
+ lora_dropout=config.lora_dropout,
122
+ target_modules=list(config.lora_target_modules),
123
+ bias="none",
124
+ task_type=TaskType.CAUSAL_LM,
125
+ )
126
+ self.backbone = get_peft_model(self.backbone, lora_cfg)
127
+
128
+ for name, p in self.backbone.named_parameters():
129
+ p.requires_grad = ("lora_A" in name) or ("lora_B" in name)
130
+ self.backbone.print_trainable_parameters()
131
+
132
+ def get_param_groups(self) -> List[dict]:
133
+ lora_params = [p for n, p in self.backbone.named_parameters()
134
+ if p.requires_grad and ("lora_A" in n or "lora_B" in n)]
135
+ return [
136
+ {
137
+ "params": lora_params,
138
+ "lr": self.config_.get_lr("lora"),
139
+ "weight_decay": 0.0,
140
+ "name": "lora_ab",
141
+ }
142
+ ]
143
+
144
+ def train_step(self, batch, optimizer) -> float:
145
+ self.train()
146
+ optimizer.zero_grad(set_to_none=True)
147
+ input_ids = batch["input_ids"].to(self.config_.device)
148
+ attention_mask = batch["attention_mask"].to(self.config_.device)
149
+ labels = batch["labels"].to(self.config_.device)
150
+
151
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16,
152
+ enabled=self.config_.device.startswith("cuda")):
153
+ logits = self.forward(input_ids, attention_mask)
154
+ loss = self._ce_loss(logits, labels)
155
+
156
+ loss.backward()
157
+ return loss.detach().item()
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Building block for the proposed method
162
+ # ---------------------------------------------------------------------------
163
+ class AdapterPair(nn.Module):
164
+ """One candidate LoRA adapter: delta W = scale * (B A)."""
165
+
166
+ def __init__(self, in_dim: int, rank: int, alpha: float, dropout: float = 0.0):
167
+ super().__init__()
168
+ self.rank = rank
169
+ self.alpha = alpha
170
+ self.scaling = alpha / rank
171
+ self.lora_A = nn.Parameter(torch.zeros(rank, in_dim))
172
+ self.lora_B = nn.Parameter(torch.zeros(in_dim, rank))
173
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
174
+ nn.init.zeros_(self.lora_B)
175
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
176
+ self.active = True
177
+
178
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
179
+ if not self.active:
180
+ return x
181
+ h = self.dropout(x).float() @ self.lora_A.T
182
+ h = h @ self.lora_B.T
183
+ return x + h.to(x.dtype) * self.scaling
184
+
185
+
186
+ class AdapteredLinear(nn.Module):
187
+ """Wraps a frozen nn.Linear and applies a set of additive AdapterPairs."""
188
+
189
+ def __init__(self, base_linear: nn.Linear, ranks: List[int],
190
+ alpha_scale: float = 2.0, dropout: float = 0.05):
191
+ super().__init__()
192
+ self.base = base_linear
193
+ for p in self.base.parameters():
194
+ p.requires_grad = False
195
+ d = base_linear.out_features
196
+ self.adapters = nn.ModuleList(
197
+ [AdapterPair(d, r, alpha=alpha_scale * r, dropout=dropout) for r in ranks]
198
+ )
199
+
200
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
201
+ with torch.no_grad():
202
+ out = self.base(x)
203
+ for ad in self.adapters:
204
+ if ad.active:
205
+ out = out + ad(x)
206
+ return out
207
+
208
+ def active_adapters(self) -> List[AdapterPair]:
209
+ return [ad for ad in self.adapters if ad.active]
210
+
211
+
212
+ # ---------------------------------------------------------------------------
213
+ # Condition 3: Proposed adaptive method
214
+ # ---------------------------------------------------------------------------
215
+ class ProposedAdaptiveMethod(BaseModel):
216
+ """Two-stage adaptive LoRA.
217
+
218
+ Stage 1: grow candidate adapters at ranks {4, 8, 16}, probe CE gradients,
219
+ accumulate per-adapter Fisher importance, keep the top
220
+ `selection_fraction` per layer (selection_fraction=1.0 keeps everything:
221
+ the 'static multi-rank, no Fisher pruning' ablation).
222
+
223
+ Stage 2: train kept adapters with
224
+ L = CE + distill_weight * KD + adapter_weight * ortho
225
+ (weights read from Config; ablations zero individual terms).
226
+ """
227
+
228
+ def __init__(self, config: Config, tokenizer):
229
+ super().__init__(config, tokenizer)
230
+ self.target_module_names = list(config.lora_target_modules)
231
+ self.ranks = list(config.proposed_ranks)
232
+
233
+ for p in self.backbone.parameters():
234
+ p.requires_grad = False
235
+ self.backbone.eval()
236
+
237
+ replaced = 0
238
+ for name, module in self.backbone.named_modules():
239
+ for child_name, child in list(module.named_children()):
240
+ if child_name in self.target_module_names and isinstance(child, nn.Linear):
241
+ setattr(module, child_name, AdapteredLinear(
242
+ child, self.ranks,
243
+ alpha_scale=2.0,
244
+ dropout=config.lora_dropout,
245
+ ))
246
+ replaced += 1
247
+ if replaced == 0:
248
+ logger.warning(
249
+ "No target modules matched %s — adapters were not injected.",
250
+ self.target_module_names,
251
+ )
252
+ self.n_wrapped = replaced
253
+
254
+ # Frozen reference model for KD.
255
+ self.frozen_ref_model = AutoModelForCausalLM.from_pretrained(
256
+ config.base_model,
257
+ torch_dtype=torch.bfloat16 if config.torch_dtype == "bfloat16" else torch.float32,
258
+ )
259
+ for p in self.frozen_ref_model.parameters():
260
+ p.requires_grad = False
261
+ self.frozen_ref_model.eval()
262
+ self.frozen_ref_model.to(self.config_.device)
263
+
264
+ self.selection_summary: Dict[str, List[int]] = {}
265
+
266
+ # ---- adapter bookkeeping --------------------------------------------
267
+ def _iter_wrapped(self):
268
+ for name, module in self.backbone.named_modules():
269
+ if isinstance(module, AdapteredLinear):
270
+ yield name, module
271
+
272
+ def _all_adapters(self) -> List[AdapterPair]:
273
+ return [ad for _, m in self._iter_wrapped() for ad in m.adapters]
274
+
275
+ def _active_adapters(self) -> List[AdapterPair]:
276
+ return [ad for _, m in self._iter_wrapped() for ad in m.active_adapters()]
277
+
278
+ def _ortho_reg(self) -> torch.Tensor:
279
+ adapters = self._active_adapters()
280
+ if not adapters:
281
+ return torch.tensor(0.0, device=self.config_.device)
282
+ total = 0.0
283
+ for ad in adapters:
284
+ A = ad.lora_A.float()
285
+ r = A.shape[0]
286
+ eye = torch.eye(r, device=A.device, dtype=A.dtype)
287
+ total = total + torch.norm(A.T @ A - eye, p="fro") ** 2
288
+ return total / len(adapters)
289
+
290
+ # ---- stage 1: grow, probe, prune ------------------------------------
291
+ def run_stage1_selection(self, train_loader, steps: int = None) -> Dict[str, List[int]]:
292
+ """Train all candidate adapters briefly with CE only, accumulate
293
+ Fisher importance per adapter, keep the top selection_fraction per
294
+ layer, prune the rest. Returns {layer_name: [kept ranks]}."""
295
+ cfg = self.config_
296
+ steps = steps or cfg.stage1_steps
297
+ self.train()
298
+
299
+ params = [p for ad in self._all_adapters() for p in (ad.lora_A, ad.lora_B)]
300
+ probe_opt = torch.optim.AdamW(params, lr=cfg.lr_proposed, weight_decay=0.0)
301
+
302
+ fisher: Dict[int, torch.Tensor] = {}
303
+ for ad in self._all_adapters():
304
+ fisher[id(ad)] = torch.tensor(0.0, device=cfg.device)
305
+
306
+ step_count, data_iter = 0, iter(train_loader)
307
+ while step_count < steps:
308
+ try:
309
+ batch = next(data_iter)
310
+ except StopIteration:
311
+ data_iter = iter(train_loader)
312
+ batch = next(data_iter)
313
+ probe_opt.zero_grad(set_to_none=True)
314
+ input_ids = batch["input_ids"].to(cfg.device)
315
+ attn = batch["attention_mask"].to(cfg.device)
316
+ labels = batch["labels"].to(cfg.device)
317
+
318
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16,
319
+ enabled=cfg.device.startswith("cuda")):
320
+ logits = self.forward(input_ids, attn)
321
+ ce = self._ce_loss(logits, labels)
322
+ ce.backward()
323
+
324
+ with torch.no_grad():
325
+ for ad in self._all_adapters():
326
+ s = 0.0
327
+ for pname in ("lora_A", "lora_B"):
328
+ p = getattr(ad, pname)
329
+ if p.grad is not None:
330
+ s = s + (p.grad.detach() ** 2 * p.detach() ** 2).sum()
331
+ fisher[id(ad)] += s
332
+ probe_opt.step()
333
+ step_count += 1
334
+
335
+ summary: Dict[str, List[int]] = {}
336
+ for name, module in self._iter_wrapped():
337
+ scored = sorted(
338
+ ((fisher[id(ad)].item(), i, ad) for i, ad in enumerate(module.adapters)),
339
+ key=lambda t: t[0], reverse=True,
340
+ )
341
+ keep_n = max(1, int(math.ceil(cfg.selection_fraction * len(scored))))
342
+ kept_ranks = []
343
+ for rank_pos, (_, _, ad) in enumerate(scored):
344
+ if rank_pos < keep_n:
345
+ ad.active = True
346
+ kept_ranks.append(ad.rank)
347
+ else:
348
+ ad.active = False
349
+ ad.lora_A.requires_grad = False
350
+ ad.lora_B.requires_grad = False
351
+ summary[name] = kept_ranks
352
+
353
+ self.selection_summary = summary
354
+ del probe_opt
355
+ logger.info("Stage-1 selection kept %d/%d adapters",
356
+ sum(len(v) for v in summary.values()),
357
+ len(self._all_adapters()))
358
+ return summary
359
+
360
+ # ---- param groups ----------------------------------------------------
361
+ def get_param_groups(self) -> List[dict]:
362
+ groups = []
363
+ for name, module in self._iter_wrapped():
364
+ for ad in module.active_adapters():
365
+ groups.append({
366
+ "params": [ad.lora_A, ad.lora_B],
367
+ "lr": self.config_.get_lr("proposed_adaptive"),
368
+ "weight_decay": 0.0,
369
+ "name": f"{name}.r{ad.rank}",
370
+ })
371
+ return groups
372
+
373
+ # ---- stage 2 training step -------------------------------------------
374
+ def train_step(self, batch, optimizer) -> float:
375
+ cfg = self.config_
376
+ self.train()
377
+ optimizer.zero_grad(set_to_none=True)
378
+ input_ids = batch["input_ids"].to(cfg.device)
379
+ attn = batch["attention_mask"].to(cfg.device)
380
+ labels = batch["labels"].to(cfg.device)
381
+
382
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16,
383
+ enabled=cfg.device.startswith("cuda")):
384
+ logits = self.forward(input_ids, attn)
385
+ ce = self._ce_loss(logits, labels)
386
+
387
+ with torch.no_grad():
388
+ ref_logits = self.frozen_ref_model(
389
+ input_ids=input_ids, attention_mask=attn
390
+ ).logits.detach()
391
+
392
+ T_eff = cfg.distill_temperature
393
+ kd = F.kl_div(
394
+ F.log_softmax(logits / T_eff, dim=-1),
395
+ F.softmax(ref_logits / T_eff, dim=-1),
396
+ reduction="batchmean",
397
+ ) * (T_eff ** 2)
398
+
399
+ ortho = self._ortho_reg()
400
+ # Loss weights come from Config so loss ablations simply zero them.
401
+ loss = ce + cfg.distill_weight * kd + cfg.adapter_weight * ortho
402
+
403
+ loss.backward()
404
+ return float(loss.detach().item())
02_PHYSIC_Training-Free-Particle-Guidance/code/model.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math, torch, torch.nn as nn, torch.nn.functional as F
2
+
3
+ class TinyTransformer(nn.Module):
4
+ def __init__(self, vocab=16, d=64, nhead=2, layers=2, ffn=128, max_len=32):
5
+ super().__init__()
6
+ self.emb = nn.Embedding(vocab, d)
7
+ self.pos = nn.Embedding(max_len, d)
8
+ layer = nn.TransformerEncoderLayer(d_model=d, nhead=nhead, dim_feedforward=ffn,
9
+ batch_first=True, dropout=0.0)
10
+ self.enc = nn.TransformerEncoder(layer, num_layers=layers)
11
+ self.head = nn.Linear(d, vocab)
12
+ self.max_len = max_len
13
+
14
+ def forward(self, x):
15
+ B, L = x.shape
16
+ h = self.emb(x) + self.pos(torch.arange(L, device=x.device))[None]
17
+ mask = nn.Transformer.generate_square_subsequent_mask(L, device=x.device)
18
+ h = self.enc(h, mask=mask, is_causal=True)
19
+ return self.head(h)
20
+
21
+
22
+ class LoRALinear(nn.Module):
23
+ """Standard LoRA: W + (alpha/r) * B A, A and B trainable, W frozen."""
24
+ def __init__(self, base: nn.Linear, r=4, alpha=8.0):
25
+ super().__init__()
26
+ self.base = base
27
+ for p in self.base.parameters():
28
+ p.requires_grad_(False)
29
+ self.A = nn.Parameter(torch.zeros(r, base.in_features))
30
+ self.B = nn.Parameter(torch.zeros(base.out_features, r))
31
+ nn.init.normal_(self.A, std=1.0 / math.sqrt(r))
32
+ self.scale = alpha / r
33
+
34
+ def forward(self, x):
35
+ return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)
36
+
37
+
38
+ def apply_lora(model, r=4, alpha=8.0):
39
+ """Wrap attention q/k/v/out projections (and head) with LoRA."""
40
+ wrapped = 0
41
+ for name, mod in model.named_modules():
42
+ for cname, child in list(mod.named_children()):
43
+ if isinstance(child, nn.Linear) and ('in_proj' in cname or 'out_proj' in cname or cname == 'head'):
44
+ setattr(mod, cname, LoRALinear(child, r, alpha))
45
+ wrapped += 1
46
+ return model, wrapped
02_PHYSIC_Training-Free-Particle-Guidance/code/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ datasets
2
+ numpy
3
+ scikit-learn
4
+ torch
5
+ transformers
02_PHYSIC_Training-Free-Particle-Guidance/code/run_experiment.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capability retention after SFT: full FT vs LoRA.
2
+ Pipeline: (1) pretrain one shared base model on diverse synthetic tasks;
3
+ (2) record pre-SFT baseline on held-out general tasks; (3) SFT on a distinct
4
+ task (mod-sum-5) with full FT or LoRA across LRs; (4) report retention
5
+ delta = post - pre-SFT accuracy. Deterministic seeds, CPU/GPU-light."""
6
+ import time, json, copy
7
+ import numpy as np
8
+ import torch, torch.nn as nn
9
+ from experiment_harness import ExperimentHarness
10
+ from tasks import PRETRAIN_TASKS, task_modsum_sft, make_dataset, VOCAB
11
+ from model import TinyTransformer, apply_lora
12
+
13
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
14
+ harness = ExperimentHarness(time_budget=300)
15
+ T0 = time.time()
16
+ BUDGET = 300
17
+
18
+ # ---------------- data ----------------
19
+ N_PRE, N_SFT, N_EVAL = 4000, 2000, 400
20
+ pre_x, pre_y = make_dataset(lambda r: PRETRAIN_TASKS[r.integers(0, len(PRETRAIN_TASKS))](r),
21
+ N_PRE, seed=0)
22
+ sft_x, sft_y = make_dataset(task_modsum_sft, N_SFT, seed=1)
23
+ # held-out general eval: 4 pretraining task types, unseen samples
24
+ eval_sets = []
25
+ for i, tf in enumerate(PRETRAIN_TASKS):
26
+ ex, ey = make_dataset(tf, N_EVAL, seed=100 + i)
27
+ eval_sets.append((tf.__name__, ex, ey))
28
+
29
+ def to_torch(x, y):
30
+ return (torch.from_numpy(x).to(device), torch.from_numpy(y).to(device))
31
+
32
+ pre_x, pre_y = to_torch(pre_x, pre_y)
33
+ sft_x, sft_y = to_torch(sft_x, sft_y)
34
+ eval_sets = [(n, to_torch(x, y)[0], to_torch(x, y)[1]) for n, x, y in eval_sets]
35
+
36
+ def evaluate(model, x, y):
37
+ model.eval()
38
+ with torch.no_grad():
39
+ logits = model(x)
40
+ pred = logits.argmax(-1)
41
+ mask = y != 15 # PAD
42
+ ans_pos = mask.float().cumsum(1).argmax(1) # answer token index
43
+ correct = (pred[torch.arange(len(x)), ans_pos] ==
44
+ y[torch.arange(len(x)), ans_pos]).float().mean().item()
45
+ return correct
46
+
47
+ def train(model, params, x, y, steps, lr, bs=64):
48
+ opt = torch.optim.AdamW(params, lr=lr)
49
+ model.train()
50
+ n = len(x)
51
+ for step in range(steps):
52
+ idx = torch.from_numpy(np.random.default_rng(step).integers(0, n, bs)).to(device)
53
+ logits = model(x[idx])
54
+ loss = nn.functional.cross_entropy(
55
+ logits.reshape(-1, VOCAB), y[idx].reshape(-1), ignore_index=15)
56
+ if not harness.check_value(loss.item(), 'loss'):
57
+ print('FAIL: NaN/divergence detected'); break
58
+ opt.zero_grad(); loss.backward()
59
+ torch.nn.utils.clip_grad_norm_(params, 1.0); opt.step()
60
+ if step % 100 == 0:
61
+ print(f' step {step} loss {loss.item():.4f}')
62
+ return model
63
+
64
+ def pretrain(seed):
65
+ torch.manual_seed(seed)
66
+ m = TinyTransformer().to(device)
67
+ print('Pretraining base model...')
68
+ return train(m, m.parameters(), pre_x, pre_y, steps=1000, lr=3e-4)
69
+
70
+ # ---------------- pre-SFT baseline ----------------
71
+ base = pretrain(seed=42)
72
+ pre_acc = {name: evaluate(base, ex, ey) for name, ex, ey in eval_sets}
73
+ for n, a in pre_acc.items():
74
+ harness.report_metric(f'pre_sft_acc_{n}', a)
75
+ print('Pre-SFT general accuracy:', {k: round(v, 3) for k, v in pre_acc.items()})
76
+
77
+ # ---------------- SFT grid ----------------
78
+ LRS = [1e-5, 1e-4, 1e-3, 1e-2]
79
+ results = []
80
+ TIME_ESTIMATE = 900 # pilot-informed estimate; guard below handles overrun
81
+ print(f'TIME_ESTIMATE: {TIME_ESTIMATE}s (will stop gracefully at 80% budget)')
82
+ n_steps_sft = 600
83
+
84
+ for method in ['full_ft', 'lora']:
85
+ for lr in LRS:
86
+ if harness.should_stop():
87
+ break
88
+ torch.manual_seed(42)
89
+ model = copy.deepcopy(base)
90
+ if method == 'lora':
91
+ model, wrapped = apply_lora(model, r=4, alpha=8.0)
92
+ params = [p for p in model.parameters() if p.requires_grad]
93
+ n_train = sum(p.numel() for p in params)
94
+ else:
95
+ params = model.parameters()
96
+ n_train = sum(p.numel() for p in params)
97
+ print(f'--- {method} lr={lr} trainable_params={n_train}')
98
+ train(model, params, sft_x, sft_y, steps=n_steps_sft, lr=lr)
99
+ post_acc = {name: evaluate(model, ex, ey) for name, ex, ey in eval_sets}
100
+ sft_task_acc = evaluate(model, sft_x[:400], sft_y[:400])
101
+ rec = {'method': method, 'lr': lr,
102
+ 'sft_task_acc': sft_task_acc,
103
+ 'post_acc': post_acc,
104
+ 'retention_delta': {k: post_acc[k] - pre_acc[k] for k in pre_acc},
105
+ 'mean_retention_delta': float(np.mean([post_acc[k] - pre_acc[k]
106
+ for k in pre_acc]))}
107
+ harness.report_metric(f'{method}_lr{lr}_mean_retention_delta',
108
+ rec['mean_retention_delta'])
109
+ harness.report_metric(f'{method}_lr{lr}_sft_task_acc', sft_task_acc)
110
+ results.append(rec)
111
+ print(json.dumps({k: v for k, v in rec.items() if k != 'post_acc'}, indent=1))
112
+
113
+ with open('results_detail.json', 'w') as f:
114
+ json.dump({'pre_sft_acc': pre_acc, 'runs': results}, f, indent=1)
115
+
116
+ print('\n=== RETENTION SUMMARY (delta = post-SFT − pre-SFT general acc) ===')
117
+ print(f"{'method':8s} {'lr':>8s} {'sft_acc':>8s} {'mean_retention':>15s}")
118
+ for r in results:
119
+ print(f"{r['method']:8s} {r['lr']:8.0e} {r['sft_task_acc']:8.3f} "
120
+ f"{r['mean_retention_delta']:15.3f}")
121
+ harness.finalize()
122
+ print(f'Done in {time.time()-T0:.1f}s')
02_PHYSIC_Training-Free-Particle-Guidance/code/training.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ training.py — Shared training loop, optimizer scheduling, log-likelihood
3
+ evaluation (with length-normalized HellaSwag scoring and per-subject
4
+ weighted MMLU accuracy), calibration metrics, latency / memory / FLOPs.
5
+
6
+ FLOPs estimate uses TOTAL parameters (frozen backbone dominates forward
7
+ compute); trainable and total parameter counts are reported separately.
8
+ """
9
+
10
+ import time
11
+ import logging
12
+ from typing import Any, Dict, List, Tuple
13
+
14
+ import numpy as np
15
+ import torch
16
+ from torch.nn.utils import clip_grad_norm_
17
+ from sklearn.metrics import accuracy_score, f1_score
18
+
19
+ from config import Config
20
+ from methods import ProposedAdaptiveMethod
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Optimizer / scheduler
27
+ # ---------------------------------------------------------------------------
28
+
29
+ def build_optimizer(method, config: Config) -> torch.optim.Optimizer:
30
+ """Build condition-specific AdamW. The cosine/warmup schedule is applied
31
+ by train_model once total optimizer steps are known."""
32
+ param_groups = method.get_param_groups()
33
+ if not param_groups or all(len(g["params"]) == 0 for g in param_groups):
34
+ raise ValueError("get_param_groups() returned no trainable parameters.")
35
+
36
+ return torch.optim.AdamW(
37
+ param_groups,
38
+ lr=config.get_lr("lora"), # per-group lr overrides this default
39
+ weight_decay=config.weight_decay,
40
+ betas=(0.9, 0.999),
41
+ )
42
+
43
+
44
+ def _make_scheduler(optimizer, config: Config, total_steps: int):
45
+ warmup_steps = max(1, int(config.warmup_ratio * total_steps))
46
+
47
+ def lr_lambda(current_step: int) -> float:
48
+ if current_step < warmup_steps:
49
+ return float(current_step) / float(max(1, warmup_steps))
50
+ progress = (current_step - warmup_steps) / max(1, total_steps - warmup_steps)
51
+ return max(0.0, 0.5 * (1.0 + np.cos(np.pi * min(1.0, progress))))
52
+
53
+ return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
54
+
55
+
56
+ def _optimizer_step(method, optimizer, scheduler, trainable, config, step_count):
57
+ """Unscale-free bf16 step: clip, step, schedule, zero."""
58
+ clip_grad_norm_(trainable, config.max_grad_norm)
59
+ optimizer.step()
60
+ scheduler.step()
61
+ optimizer.zero_grad(set_to_none=True)
62
+ return step_count + 1
63
+
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # Training loop
67
+ # ---------------------------------------------------------------------------
68
+ def train_model(method, train_loader, config: Config, time_guard) -> dict:
69
+ """Shared training loop for all conditions.
70
+
71
+ bf16 autocast needs no GradScaler, so none is used (no scale()/unscale_
72
+ bookkeeping to get wrong). Accumulated gradients are always flushed with
73
+ a real optimizer step when the loop exits early (time guard or
74
+ divergence), so no accumulated work is silently discarded. The
75
+ divergence guard fires ONLY on non-finite or numerically impossible
76
+ loss values (>= divergence_loss_threshold), never on merely large losses.
77
+ (All-ignored-labels NaN batches are prevented upstream in
78
+ AlpacaTrainDataset, which skips examples whose response is fully
79
+ truncated away.)
80
+ """
81
+ start = time.time()
82
+
83
+ steps_per_epoch = max(1, len(train_loader))
84
+ total_steps = max(1, (steps_per_epoch * config.epochs) // config.grad_accum_steps)
85
+
86
+ optimizer = build_optimizer(method, config)
87
+ scheduler = _make_scheduler(optimizer, config, total_steps)
88
+
89
+ # Stage-1 Fisher probing / pruning for the proposed method.
90
+ if isinstance(method, ProposedAdaptiveMethod):
91
+ logger.info("Running stage-1 adaptive selection...")
92
+ method.run_stage1_selection(train_loader, steps=config.stage1_steps)
93
+ optimizer = build_optimizer(method, config)
94
+ scheduler = _make_scheduler(optimizer, config, total_steps)
95
+
96
+ trainable = [p for g in optimizer.param_groups for p in g["params"]]
97
+
98
+ epoch_losses: List[float] = []
99
+ optimizer_step_count = 0
100
+ aborted = False
101
+
102
+ for epoch in range(config.epochs):
103
+ running: List[float] = []
104
+ micro_step = 0
105
+ stop = False
106
+ for step, batch in enumerate(train_loader):
107
+ loss_val = method.train_step(batch, optimizer)
108
+ running.append(loss_val)
109
+ micro_step += 1
110
+
111
+ # Divergence guard: only non-finite / impossible values abort.
112
+ diverged = (not np.isfinite(loss_val)
113
+ or loss_val >= config.divergence_loss_threshold)
114
+ if diverged:
115
+ logger.error("FAIL: divergence detected (loss=%s); flushing "
116
+ "accumulated grads with a final step before abort.",
117
+ loss_val)
118
+
119
+ boundary = micro_step % config.grad_accum_steps == 0
120
+ if boundary or diverged:
121
+ # Always take a real optimizer step on accumulated grads —
122
+ # never discard them silently, even mid-accumulation.
123
+ optimizer_step_count = _optimizer_step(
124
+ method, optimizer, scheduler, trainable, config,
125
+ optimizer_step_count)
126
+ micro_step = 0
127
+
128
+ if diverged:
129
+ aborted = True
130
+ stop = True
131
+ break
132
+
133
+ if time_guard.expired():
134
+ logger.warning("Time guard expired — flushing partial "
135
+ "accumulation and stopping training early.")
136
+ stop = True
137
+ break
138
+
139
+ if micro_step > 0 and not stop:
140
+ # Epoch ended mid-accumulation: flush the partial window.
141
+ optimizer_step_count = _optimizer_step(
142
+ method, optimizer, scheduler, trainable, config,
143
+ optimizer_step_count)
144
+
145
+ epoch_losses.append(float(np.mean(running)) if running else float("nan"))
146
+ logger.info("epoch=%d mean_loss=%.4f", epoch, epoch_losses[-1])
147
+ if stop:
148
+ break
149
+
150
+ wallclock_min = (time.time() - start) / 60.0
151
+ return {
152
+ "train_losses": epoch_losses,
153
+ "wallclock_min": wallclock_min,
154
+ "optimizer_steps": optimizer_step_count,
155
+ "aborted_divergence": aborted,
156
+ }
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # Log-likelihood evaluation for multiple-choice tasks
161
+ # ---------------------------------------------------------------------------
162
+
163
+ @torch.no_grad()
164
+ def _score_ll_batch(method, ctx_ids_list, choice_ids_list, device):
165
+ """Batched log-likelihood scoring.
166
+
167
+ Returns (nll_sum [n_items, 4], nll_tokens [n_items, 4]) where nll_sum is
168
+ the total NLL of each choice and nll_tokens its token count. Callers can
169
+ use either the raw sum (single-token MMLU letters) or the length-
170
+ normalized mean (multi-token HellaSwag endings), matching the
171
+ lm-eval-harness convention for continuation tasks.
172
+
173
+ Handles BOTH choice formats correctly:
174
+ - MMLU: choice_ids is a [4] int tensor (letter id per choice) — each
175
+ element is converted to a single-element id list.
176
+ - HellaSwag: choice_ids is a list of 4 variable-length id tensors —
177
+ each is converted to its full id list.
178
+ """
179
+ def _ids_to_list(x) -> List[int]:
180
+ """Convert a tensor / list-of-scalars / scalar to a python id list."""
181
+ if isinstance(x, torch.Tensor):
182
+ return x.reshape(-1).tolist()
183
+ out = None
184
+ if isinstance(x, (list, tuple)):
185
+ out = []
186
+ for t in x:
187
+ if isinstance(t, torch.Tensor):
188
+ out.extend(t.reshape(-1).tolist())
189
+ else:
190
+ out.append(int(t))
191
+ return out
192
+ return [int(x)] # 0-dim / scalar fallback
193
+
194
+ seqs, choice_spans = [], []
195
+ for ctx_ids, choice_ids in zip(ctx_ids_list, choice_ids_list):
196
+ ctx = _ids_to_list(ctx_ids)
197
+ # Normalize choice_ids to a list of per-choice id lists. A [4]
198
+ # tensor of letter ids (MMLU) yields 4 single-token choices; a list
199
+ # of 4 variable-length tensors (HellaSwag) yields the full choices.
200
+ if isinstance(choice_ids, torch.Tensor) and choice_ids.numel() == 4:
201
+ per_choice = [[int(v)] for v in choice_ids.reshape(-1).tolist()]
202
+ elif isinstance(choice_ids, (list, tuple)) and len(choice_ids) == 4:
203
+ per_choice = [_ids_to_list(c) for c in choice_ids]
204
+ else:
205
+ flat = _ids_to_list(choice_ids)
206
+ per_choice = [flat[i:i + 1] for i in range(len(flat))]
207
+ for choice in per_choice:
208
+ seqs.append(ctx + choice)
209
+ choice_spans.append((len(ctx), len(ctx) + len(choice)))
210
+
211
+ max_len = min(method.T, max(len(s) for s in seqs))
212
+ B = len(seqs)
213
+ input_ids = torch.zeros((B, max_len), dtype=torch.long)
214
+ attention_mask = torch.zeros((B, max_len), dtype=torch.long)
215
+ for i, s in enumerate(seqs):
216
+ t = min(len(s), max_len)
217
+ input_ids[i, :t] = torch.tensor(s[:t], dtype=torch.long)
218
+ attention_mask[i, :t] = 1
219
+
220
+ logits = method.forward(input_ids.to(device), attention_mask.to(device))
221
+ log_probs = torch.log_softmax(logits.float(), dim=-1)
222
+
223
+ nll_sum = torch.zeros(B)
224
+ nll_tok = torch.zeros(B)
225
+ for i, (start, end) in enumerate(choice_spans):
226
+ end = min(end, max_len)
227
+ tgt = input_ids[i, start:end].to(device)
228
+ lp = log_probs[i, start - 1:end - 1, :]
229
+ if lp.shape[0] == 0:
230
+ continue
231
+ token_lp = lp.gather(1, tgt.unsqueeze(1)).squeeze(1)
232
+ nll_sum[i] = -token_lp.sum().cpu()
233
+ nll_tok[i] = float(tgt.numel())
234
+ return (nll_sum.view(len(ctx_ids_list), -1).numpy(),
235
+ nll_tok.view(len(ctx_ids_list), -1).numpy())
236
+
237
+
238
+ def _per_subject_weighted_accuracy(preds, labels, subjects) -> float:
239
+ """mmlu_weighted_accuracy: accuracy computed WITHIN each subject, then
240
+ averaged uniformly over subjects (macro-over-subjects, micro-within)."""
241
+ by_sub: Dict[str, List[Tuple[int, int]]] = {}
242
+ for p, l, s in zip(preds, labels, subjects):
243
+ by_sub.setdefault(s, []).append((p, l))
244
+ if not by_sub:
245
+ return float("nan")
246
+ subject_accs = []
247
+ for s, pairs in by_sub.items():
248
+ c = sum(1 for p, l in pairs if p == l)
249
+ subject_accs.append(c / len(pairs))
250
+ return float(np.mean(subject_accs))
251
+
252
+
253
+ def evaluate_ll_tasks(method, loader, device, task: str = "mmlu") -> dict:
254
+ """Log-likelihood evaluation over a 4-choice multiple-choice loader.
255
+
256
+ MMLU: single-token letter scoring, pred = argmin total NLL; also
257
+ computes per-subject weighted accuracy (primary metric).
258
+ HellaSwag: pred = argmin MEAN per-token NLL (length-normalized, as in
259
+ lm-eval-harness) so short endings are not systematically favored.
260
+ """
261
+ method.eval()
262
+ all_preds, all_labels, all_confs = [], [], []
263
+ all_subjects: List[str] = []
264
+
265
+ was_grad = torch.is_grad_enabled()
266
+ torch.set_grad_enabled(False)
267
+ try:
268
+ for batch in loader:
269
+ labels = batch["label"]
270
+ if "prompt_ids" in batch:
271
+ ctx_key, choice_key, normalize = "prompt_ids", "choice_ids", False
272
+ else:
273
+ ctx_key, choice_key, normalize = "ctx_ids", "end_ids", True
274
+ ctx_list = batch[ctx_key]
275
+ choice_list = batch[choice_key]
276
+
277
+ nll_sum, nll_tok = _score_ll_batch(method, ctx_list, choice_list, device)
278
+ nll = nll_sum / np.maximum(nll_tok, 1.0) if normalize else nll_sum
279
+
280
+ preds = np.argmin(nll, axis=1)
281
+ neg = -nll
282
+ neg = neg - neg.max(axis=1, keepdims=True)
283
+ probs = np.exp(neg)
284
+ probs = probs / probs.sum(axis=1, keepdims=True)
285
+ confs = probs.max(axis=1)
286
+
287
+ all_preds.extend(preds.tolist())
288
+ all_labels.extend(labels.tolist() if torch.is_tensor(labels)
289
+ else list(labels))
290
+ all_confs.extend(confs.tolist())
291
+ if "subject" in batch:
292
+ all_subjects.extend(batch["subject"])
293
+ finally:
294
+ torch.set_grad_enabled(was_grad)
295
+
296
+ acc = accuracy_score(all_labels, all_preds)
297
+ f1 = f1_score(all_labels, all_preds, average="macro", zero_division=0)
298
+ out = {
299
+ "accuracy": float(acc),
300
+ "f1_macro": float(f1),
301
+ "confidences": all_confs,
302
+ "preds": all_preds,
303
+ "labels": all_labels,
304
+ }
305
+ if task == "mmlu" and all_subjects:
306
+ out["weighted_accuracy"] = _per_subject_weighted_accuracy(
307
+ all_preds, all_labels, all_subjects)
308
+ return out
309
+
310
+
311
+ # ---------------------------------------------------------------------------
312
+ # Calibration metrics
313
+ # ---------------------------------------------------------------------------
314
+
315
+ def compute_ece_brier(confidences, preds, labels, n_bins: int = 10) -> Tuple[float, float]:
316
+ """ECE (equal-width bins) and multiclass Brier score.
317
+
318
+ NOTE: for MMLU these confidences come from a 4-way letter softmax
319
+ (P(letter | prompt)); the choice CONTENT is never scored, so ECE/Brier
320
+ are weakly calibrated by construction. This is flagged in METRIC_DEF
321
+ (main.py) and should be interpreted accordingly.
322
+ """
323
+ conf = np.asarray(confidences, dtype=np.float64)
324
+ preds = np.asarray(preds, dtype=np.int64)
325
+ labels = np.asarray(labels, dtype=np.int64)
326
+ n = len(conf)
327
+ correct = (preds == labels).astype(np.float64)
328
+
329
+ ece = 0.0
330
+ bin_edges = np.linspace(0.0, 1.0, n_bins + 1)
331
+ for b in range(n_bins):
332
+ lo, hi = bin_edges[b], bin_edges[b + 1]
333
+ mask = ((conf >= lo) & (conf <= hi)) if b == n_bins - 1 \
334
+ else ((conf >= lo) & (conf < hi))
335
+ n_b = mask.sum()
336
+ if n_b == 0:
337
+ continue
338
+ ece += (n_b / n) * abs(correct[mask].mean() - conf[mask].mean())
339
+
340
+ n_classes = 4
341
+ probs = np.zeros((n, n_classes), dtype=np.float64)
342
+ for i in range(n):
343
+ probs[i, preds[i]] = conf[i]
344
+ residual = (1.0 - conf[i]) / (n_classes - 1)
345
+ for c in range(n_classes):
346
+ if c != preds[i]:
347
+ probs[i, c] = residual
348
+ onehot = np.zeros_like(probs)
349
+ onehot[np.arange(n), labels] = 1.0
350
+ brier = float(np.mean(np.sum((probs - onehot) ** 2, axis=1)))
351
+
352
+ return float(ece), brier
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # Item-level bootstrap CI for accuracy-type metrics
357
+ # ---------------------------------------------------------------------------
358
+ def bootstrap_accuracy_ci(preds, labels, n_resamples: int = 1000,
359
+ seed: int = 0, alpha: float = 0.05):
360
+ """95% percentile bootstrap CI over evaluation items (deterministic).
361
+
362
+ IMPORTANT: must be called separately per seed. All seeds evaluate the
363
+ identical item set, so pooling item predictions across seeds would
364
+ quintuple n and artificially narrow the CI ~sqrt(5)x.
365
+ """
366
+ preds = np.asarray(preds)
367
+ labels = np.asarray(labels)
368
+ n = len(preds)
369
+ if n == 0:
370
+ return float("nan"), float("nan")
371
+ rng = np.random.RandomState(seed)
372
+ accs = np.empty(n_resamples)
373
+ for i in range(n_resamples):
374
+ idx = rng.randint(0, n, size=n)
375
+ accs[i] = float(np.mean(preds[idx] == labels[idx]))
376
+ lo = float(np.percentile(accs, 100 * alpha / 2))
377
+ hi = float(np.percentile(accs, 100 * (1 - alpha / 2)))
378
+ return lo, hi
379
+
380
+
381
+ # ---------------------------------------------------------------------------
382
+ # Cost measurement
383
+ # ---------------------------------------------------------------------------
384
+
385
+ def measure_cost(method, dummy_batch, config: Config) -> dict:
386
+ """Measure inference latency, peak CUDA memory, trainable/total params,
387
+ and forward FLOPs.
388
+
389
+ FLOPs = 2 * TOTAL_params * T * B: the frozen backbone executes in the
390
+ forward pass for every method, so counting only trainable parameters
391
+ (as before) massively underestimates LoRA/proposed forward compute.
392
+ Trainable and total parameter counts are reported separately.
393
+ """
394
+ device = config.device
395
+ method.eval()
396
+
397
+ def run_fwd():
398
+ with torch.no_grad():
399
+ method.forward(
400
+ dummy_batch["input_ids"].to(device),
401
+ dummy_batch["attention_mask"].to(device),
402
+ )
403
+
404
+ is_cuda = device.startswith("cuda") and torch.cuda.is_available()
405
+ if is_cuda:
406
+ torch.cuda.reset_peak_memory_stats()
407
+ torch.cuda.synchronize()
408
+
409
+ for _ in range(3):
410
+ run_fwd()
411
+ if is_cuda:
412
+ torch.cuda.synchronize()
413
+
414
+ n_iters = 20
415
+ t0 = time.time()
416
+ for _ in range(n_iters):
417
+ run_fwd()
418
+ if is_cuda:
419
+ torch.cuda.synchronize()
420
+ latency_ms = (time.time() - t0) / n_iters * 1000.0
421
+
422
+ peak_mem_gb = 0.0
423
+ if is_cuda:
424
+ peak_mem_gb = torch.cuda.max_memory_allocated() / 1e9
425
+
426
+ trainable_params = sum(p.numel() for p in method.parameters() if p.requires_grad)
427
+ total_params = sum(p.numel() for p in method.parameters())
428
+ B = dummy_batch["input_ids"].shape[0]
429
+ T = dummy_batch["input_ids"].shape[1]
430
+ flops_per_fwd = 2.0 * total_params * T * B
431
+
432
+ return {
433
+ "latency_ms": float(latency_ms),
434
+ "peak_mem_gb": float(peak_mem_gb),
435
+ "trainable_m": float(trainable_params / 1e6),
436
+ "total_m": float(total_params / 1e6),
437
+ "flops_per_fwd": float(flops_per_fwd),
438
+ }
439
+
440
+
441
+ # ---------------------------------------------------------------------------
442
+ # Full condition evaluation
443
+ # ---------------------------------------------------------------------------
444
+
445
+ def evaluate_condition(method, loaders: Dict[str, Any], config: Config) -> dict:
446
+ """Evaluate a trained method on all tasks + measure cost."""
447
+ metrics: Dict[str, Any] = {}
448
+ for name in ("mmlu", "hellaswag"):
449
+ r = evaluate_ll_tasks(method, loaders[name], config.device, task=name)
450
+ ece, brier = compute_ece_brier(
451
+ r["confidences"], r["preds"], r["labels"],
452
+ n_bins=config.calib_num_bins,
453
+ )
454
+ entry = {
455
+ "accuracy": r["accuracy"],
456
+ "f1_macro": r["f1_macro"],
457
+ "ece": ece,
458
+ "brier": brier,
459
+ }
460
+ if "weighted_accuracy" in r:
461
+ entry["weighted_accuracy"] = r["weighted_accuracy"]
462
+ metrics[name] = entry
463
+ # Retain item-level preds/labels for per-seed bootstrap CIs.
464
+ metrics[name + "_items"] = {"preds": r["preds"], "labels": r["labels"]}
465
+ logger.info("%s: acc=%.4f%s f1=%.4f ece=%.4f brier=%.4f",
466
+ name, r["accuracy"],
467
+ f" weighted_acc={r.get('weighted_accuracy', float('nan')):.4f}"
468
+ if "weighted_accuracy" in r else "",
469
+ r["f1_macro"], ece, brier)
470
+
471
+ device = torch.device(config.device) if torch.cuda.is_available() else torch.device("cpu")
472
+ T = config.max_seq_len
473
+ dummy_batch = {
474
+ "input_ids": torch.randint(0, method.V - 1, (config.eval_batch_size, T),
475
+ dtype=torch.long),
476
+ "attention_mask": torch.ones((config.eval_batch_size, T), dtype=torch.long),
477
+ }
478
+ metrics["cost"] = measure_cost(method, dummy_batch, config)
479
+ return metrics
480
+
481
+
482
+ if __name__ == "__main__":
483
+ logging.basicConfig(level=logging.INFO)
484
+ print("training.py: shared training/evaluation utilities — import from main.py")
02_PHYSIC_Training-Free-Particle-Guidance/manifest.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "run_id": "rc-20261120-030020-3a2302",
3
+ "target_conference": "neurips_2025",
4
+ "files": [
5
+ "paper_final.md",
6
+ "paper.tex",
7
+ "references.bib",
8
+ "code/",
9
+ "verification_report.json",
10
+ "sanitization_report.json",
11
+ "charts/",
12
+ "neurips_2025.sty",
13
+ "paper.pdf"
14
+ ],
15
+ "generated": "2026-11-20T03:26:56+00:00",
16
+ "notes": {
17
+ "paper_final.md": "Final paper in Markdown format",
18
+ "paper.tex": "Conference-ready LaTeX (neurips_2025)",
19
+ "references.bib": "BibTeX bibliography (verified citations only)",
20
+ "code/": "Experiment source code with requirements.txt",
21
+ "verification_report.json": "Citation integrity & relevance verification",
22
+ "charts/": "Result visualizations"
23
+ }
24
+ }
02_PHYSIC_Training-Free-Particle-Guidance/paper.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4c113aaf6a8eecf4bc80daed6a1de0c3b10120388f6e6da121522f4d00302c7
3
+ size 517383
02_PHYSIC_Training-Free-Particle-Guidance/paper_final.md ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PHYSIC: Training-Free Particle Guidance for Physics-Grounded Video Generation
2
+
3
+ ## Abstract
4
+
5
+ Physics violations in generated videos — objects rebounding above their release height, interpenetrating collisions, momentum appearing from nothing — persist because video diffusion models learn appearance statistics rather than dynamical laws. Existing remedies either fine-tune the generator, restrict physics to event-level assertions, or assume single-hypothesis scenes. PHYSIC lifts pixel-level motion into a unified particle representation spanning rigid bodies, cloth, and fluid; enforces explicit momentum and energy conservation on the particle rollout; and compiles the conserved motion into control fields that steer a frozen image-to-video diffusion model at inference time, with large-language-model priors resolving parameters that visual fitting provably cannot identify. We validate the pipeline end-to-end on real-video decompositions and report first-hand evidence of the key motivating phenomenon: in a chaotic scattering scene, friction and restitution are observationally non-identifiable from end states alone (end-state DTW of 0.666 vs. 0.658 across parameter sets), while our fitting stage recovers mass to a median error of 0.36%. In pipeline validation across three seeds, particle-flow guidance produces stable, seed-consistent guidance gradients (guidance loss 0.191 ± 0.006; gradient norms 0.028 ± 0.006) and computable conservation residuals without any parameter updates to the base model. These results establish the technical substrate for our conservation-guidance hypothesis and delineate which of its components remain open, marking a step toward distilling physical common sense into generation behavior without training.
6
+
7
+
8
+ > **Note:** This paper was produced in degraded mode. Quality gate score (3/4.0) was below threshold. Unverified numerical results in tables have been replaced with `---` and require independent verification.
9
+
10
+
11
+ ## Introduction
12
+
13
+ Videos generated by today's diffusion models routinely violate elementary mechanics: balls bounce higher than their release height, objects pass through one another, and systems gain kinetic energy from nothing. This failure mode is not cosmetic — it limits the use of video generators as world models for robotics, scientific visualization, and physically grounded planning. Survey work confirms that physical faithfulness remains among the weakest axes of modern video generation [bansal2024videophy]. The core issue is representational: models such as video diffusion transformers learn correlational appearance statistics, and their implicit dynamics degrade over long rollouts. Studies probing how far video generation is from being a world model report systematic drift away from physical law.
14
+
15
+ Prior attempts to inject physics fall into camps that each miss a piece. Physics-simulation pipelines reconstruct a scene and simulate it with a single material model, then guide generation with control fields [wang2025physctrl, liu2024physgen, zhang2024physdreamer]; these either require training an interface or assume one hypothesis about scene physics, and systems identification pipelines built on differentiable simulation [li2023pacnerf, ma2023neural] inherit the identifiability limits of their observations. Agent-loop approaches embed large-language-model (LLM) physical knowledge in executable sandboxes and iterate generation with verifier feedback [tang2024worldcoder], but their physics lives at the event/assertion level and appearance refinement degrades visual realism. Code-world-model systems compile an agent-authored world program into control conditions, yet require a parameter-efficient adapter on the base model for the model to interpret the proxy signals [chen2026code], leaving the frozen-model interface gap unsolved. Training-free guidance offers a way to steer frozen diffusion models toward arbitrary objectives without weight updates [ye2024unified, rout2024beyond, shen2024understanding, uehara2025inferencetime], but prior applications target appearance or reward alignment rather than conserved 3D dynamics.
16
+
17
+ Our central observation connects two threads. First, some physical parameters — friction and restitution among them — are *observationally non-identifiable* from end-state video evidence: we demonstrate this first-hand on a chaotic scattering scene where two distinct parameter sets produce statistically indistinguishable end states. This is precisely the regime where LLM physical common sense is the natural prior, because the knowledge required is not in the pixels. Second, conservation laws (momentum, energy) are free structural constraints: they require no data, no training, and define a physically admissible manifold on which any rollout must lie. PHYSIC combines both: an LLM-constrained parameter-fitting stage estimates what is observable and defers to language priors for what is not; a heterogeneous particle simulation enforces conservation on the rollout; and a projection layer compiles conserved particle motion into control fields that guide a frozen image-to-video model at sampling time, in the spirit of loss-based training-free guidance [ye2024unified, shen2024understanding] and motion-conditioned generation [geng2025motion].
18
+
19
+ This paper reports an honest account of building and validating this substrate. Our contributions are:
20
+
21
+ - **PHYSIC**, a training-free pipeline that lifts pixel flow to a unified particle representation across rigid, cloth, and fluid materials, enforces momentum and energy conservation on the rollout, and guides a fully frozen diffusion model — no LoRA, no fine-tuning of the generator.
22
+ - **First-hand identifiability evidence** showing friction/restitution are non-identifiable from end states in chaotic scenes (end-state DTW gap of 0.008 between parameter sets), motivating LLM priors for unobservable parameters, alongside a fitting stage that recovers mass to 0.36% median error.
23
+ - **A validated guidance interface**: pipeline validation demonstrating stable, seed-consistent guidance gradients and computable conservation residuals on a frozen base model across three seeds, with an explicit accounting of which conservation mechanisms are currently wired and which remain open code paths.
24
+ - **An evaluation protocol** for physics-correctness that fixes the operational definition of "physically correct" and avoids single-rater non-blind judging.
25
+
26
+ The remainder covers related work, the method, a pipeline-validation study with the current evidence state, and limitations identifying what remains open.
27
+
28
+ ## Related Work
29
+
30
+ ### Physics-grounded video generation
31
+
32
+ Physics-grounded generation couples simulators to video models. PhysGen [liu2024physgen] grounds image-to-video generation in rigid-body dynamics from a single image; PhysCtrl [wang2025physctrl] injects physics into controllable generation through learned parameters; PhysDreamer [zhang2024physdreamer] enables physics-based interaction with 3D objects via video generation. Pipeline-style systems reconstruct scenes from video before simulating, building on 4D scene reconstruction from a single video and dynamic mesh tracking; Diffusion as Shader exploits 3D-aware control signals, and 3DPhysVideo couples flow-space guidance with scene reconstruction and physical simulation. MotionCraft performs physics-based zero-shot video generation. PhysTwin reconstructs and simulates deformable objects from video with physics-informed optimization, and GIC identifies physical properties through Gaussian-informed continua. PhysLoop loops LLM physical awareness into self-improving video generation; its physics operates at the event/assertion level with simulator-based verification, whereas PHYSIC pushes physics to frame-level particle motion with explicit conservation, and starts from real-video decomposition to preserve true textures. Different from all of these, we require neither a trained interface nor post-hoc texture optimization, and we treat heterogeneous materials under one particle representation.
33
+
34
+ ### Code-as-world and agentic loops
35
+
36
+ A parallel line uses language models to author executable world models. WorldCoder writes world models as code and refines them against the environment [tang2024worldcoder]; programmatic video prediction uses LLMs to compose video dynamics; and the Code World Model line treats a coding agent as a world brain that compiles world state into deterministic proxy signals for a video generator [chen2026code], following the programmable world model's separation of world state from rendering. Multi-agent code generation and self-correcting frameworks supply the scaffolding. Crucially, the code-world approach to physical video generation requires an adapter (LoRA) on the base model to interpret proxy controls; PHYSIC occupies the complementary regime — the base model stays frozen and all control flows through training-free guidance at sampling time, which we treat as an interface property to be validated rather than assumed.
37
+
38
+ ### Training-free guidance and inference-time alignment
39
+
40
+ Loss-based training-free guidance steers frozen diffusion models without weight updates: the unified TFG framework [ye2024unified], diffusion posterior sampling and its latent variants [rout2024beyond], analyses of when loss-based guidance works [shen2024understanding], adaptive guidance, and broader inference-time alignment surveys [uehara2025inferencetime]. For video specifically, frame-level and motion guidance have been studied training-free [geng2025motion], flow fields serve as unified motion signals, and joint appearance-motion objectives improve motion fidelity. Reward-gradient and test-time-alignment methods extend the same machinery to video, while latent world-model alignment targets physics directly at inference time. PHYSIC differs in the source of the guidance signal: rather than appearance rewards or image-space flow, we derive guidance from a *conserved* 3D particle rollout projected through the recovered camera, so the steering target carries physical structure that the generator cannot hallucinate away.
41
+
42
+ ### System identification and LLM priors for unobservables
43
+
44
+ Differentiable simulation has long served parameter estimation from visual data, with PAC-NeRF performing geometry-agnostic system identification [li2023pacnerf], and neural constitutive learning recovering material laws from motion observations [ma2023neural]; video-based rigid parameter estimation extends this to friction filtering. Yet identifiability limits are well known in system identification and are inherited by all purely visual estimators. Separately, LLMs demonstrably encode physics-relevant knowledge, and agentic frameworks exploit this for simulation construction. PHYSIC connects the two: where the observation manifold is degenerate — as our experiments show concretely for friction/restitution — visual fitting alone cannot select among parameters, and language priors become the only sensible source of regularization, injected as structured interval constraints rather than point estimates.
45
+
46
+ #
47
+
48
+ ![Figure 2: Method Comparison](charts/method_comparison.png)
49
+
50
+ # Method
51
+
52
+ ### Formal problem statement
53
+
54
+ Given an input real video $V = \{I_0, \dots, I_{T-1}\}$ with a recovered scene decomposition — per-object watertight meshes $\mathcal{M}_k$, per-frame 6-DoF pose sequences $g_k^t \in SE(3)$, a background plate, and per-frame camera intrinsics/extrinsics $(K_t, g_c^t)$ — our goal is to synthesize a video $\hat{V}$ whose object motion follows physically admissible dynamics, using a **frozen** image-to-video diffusion model $\epsilon_\theta$ with weights $\theta$ held fixed throughout. No adapter, LoRA, or fine-tuning of $\epsilon_\theta$ is applied; all physics enters through inference-time guidance, parameter estimation in an external simulator, and (optionally) auxiliary operator modules that are trained independently of $\epsilon_\theta$.
55
+
56
+ The technical problem decomposes into three coupled subproblems: (i) representing heterogeneous scene matter uniformly so a single guidance interface suffices; (ii) estimating simulation parameters when the visual observation manifold is partially degenerate; (iii) steering the frozen sampler toward the simulated, conservation-respecting motion without destroying visual fidelity.
57
+
58
+ ### Unified particle representation
59
+
60
+ We represent *all* scene matter as particles, regardless of material. The scene is partitioned into material groups $m \in \{\text{rigid}, \text{cloth}, \text{fluid}\}$; group $m$ contributes $N_m$ particles with state
61
+
62
+ $$x_i^t = \big(p_i^t, v_i^t, q_i^t, \omega_i^t, m_i, \theta_i\big) \in \mathbb{R}^{3} \times \mathbb{R}^{3} \times SO(3) \times \mathbb{R}^{3} \times \mathbb{R}_{+} \times \Theta, \tag{1}$$
63
+
64
+ where $p_i^t, v_i^t$ are world-frame position and velocity, $(q_i^t, \omega_i^t)$ are orientation and angular velocity (meaningful for rigid-frame particles, identity for continuum particles), $m_i$ is mass, and $\theta_i \in \Theta$ collects material parameters (friction $\mu$, restitution $e$ for rigid particles; stiffness/density for cloth; viscosity for fluid). Each material group is advanced by its native solver — impulse-based rigid dynamics, position-based cloth constraints, and smoothed-particle hydrodynamics for fluid — but every solver emits the same tuple in Eq. (1). This isomorphism is the load-bearing design choice: downstream motion extraction, control-field compilation, and guidance are written once against Eq. (1) and are material-agnostic, in contrast to single-material pipelines built exclusively on one continuum formulation.
65
+
66
+ ### Pixel flow to particle flow
67
+
68
+ Optical flow measures the displacement of pixels; we lift it to the displacement of particles. For a particle $i$ visible in frame $t$, its image-plane projection under the recovered camera is
69
+
70
+ $$u_i^t = \pi\!\big(K_t [R_t \mid \mathbf{t}_t]\, \tilde{p}_i^t\big), \qquad \pi(X) = (X_1/X_3,\, X_2/X_3), \tag{2}$$
71
+
72
+ where $\tilde{p}_i^t$ is the homogeneous world position and $[R_t \mid \mathbf{t}_t]$ is the camera pose; Eq. (2) states that 3D particle motion induces a deterministic 2D displacement given the camera. Observed 2D flow is computed with a standard dense estimator supplemented by long-horizon point tracks, and we define the particle-flow lifting operator $\Phi$ mapping the particle velocity field to a dense image flow field:
73
+
74
+ $$F^{\star}_{t} = \Phi\big(\{p_i^t, v_i^t\}_{i};\, K_t, R_t, \mathbf{t}_t\big), \tag{3}$$
75
+
76
+ which splats projected particle velocities into a per-pixel flow field via forward splatting with Gaussian kernels, restricted to a foreground mask derived from the decomposition. The residual between $\Phi$'s prediction and the *observed* flow serves two purposes: it is the fitting signal for simulation parameters (next section), and after calibration, the *simulated* fields $F^\star_t$ and sparse projected correspondences $P^\star = \{u_i^t\}_{i \in \mathcal{S}}$ (with $|\mathcal{S}| \le 20$ landmark particles) become the guidance targets. Three channels — dense flow, sparse points, foreground mask — generalize the multi-channel control used in reconstruction-to-video pipelines to a heterogeneous particle state.
77
+
78
+ ### Parameter estimation: fitting the observable, priors for the unobservable
79
+
80
+ Rigid scalar parameters $\phi = (\mu, e)$ are estimated by minimizing simulated-versus-observed trajectory discrepancy, measured with a dynamic-time-warping (DTW) cost $\mathcal{L}_{\mathrm{DTW}}(\phi)$ between simulated and tracked trajectories. The critical methodological point is that $\mathcal{L}_{\mathrm{DTW}}$ can be **flat** in $\phi$: in chaotic scattering, distinct $(\mu, e)$ pairs yield statistically indistinguishable end states (our experiments quantify a DTW gap of 0.008 across parameter sets), so the minimizer is not identified and any point estimate is an artifact. We therefore replace point estimation with a maximum-a-posteriori objective
81
+
82
+ $$\phi^\star = \arg\min_{\phi}\; \mathcal{L}_{\mathrm{DTW}}(\phi) + \lambda\, \mathcal{R}_{\mathrm{LLM}}(\phi; c), \tag{4}$$
83
+
84
+ where $\mathcal{R}_{\mathrm{LLM}}$ is an LLM-supplied structured prior — physical-knowledge intervals and cross-parameter couplings conditioned on the material context $c$ (e.g., "bowling ball on dry lane: $\mu \in [0.04, 0.12]$") — and $\lambda$ trades data fit against prior sharpness. Physically, the prior term regularizes exactly the coordinates along which the observation manifold is degenerate, and is applied *only* to those coordinates: mass, which the fitting loop identifies well (0.36% median error in our measurements), carries $\lambda = 0$. For soft materials, a default arm uses hand-specified constitutive families tuned by the same fitting loop; an optional enhanced arm follows operator-learning approaches that regress constitutive relations directly from video [ma2023neural, li2023pacnerf], trained as an independent auxiliary module — the generator remains frozen in both arms.
85
+
86
+ ### Conservation constraints
87
+
88
+ Two conservation laws are imposed on the particle rollout. Momentum is conserved across internal collision impulses,
89
+
90
+ $$\sum_i m_i v_i^{t^-} = \sum_i m_i v_i^{t^+} + \int_{t^-}^{t^+} f_{\mathrm{ext}}\,dt, \tag{5}$$
91
+
92
+ meaning internal forces exchange momentum between particles without changing the system total beyond external forcing; we implement Eq. (5) via hard impulse projection inside the solver. Energy is non-increasing absent external work,
93
+
94
+ $$E^{t+1} \le E^{t} + W_{\mathrm{ext}}, \qquad E^t = \sum_i \tfrac{1}{2} m_i \|v_i^t\|^2 + V_{\mathrm{grav}} + V_{\mathrm{elastic}}, \tag{6}$$
95
+
96
+ which forbids the from-nothing energy gain documented as a failure mode of physics-guided generation. We implement Eq. (6) as a soft residual $r_E^t = \max(0, E^{t+1} - E^t - W_{\mathrm{ext}})$ aggregated into both the guidance objective and the fitting cost, with hard-projection and test-time-residual variants designed for a four-arm ablation. Design rationale: momentum is cheap to enforce exactly inside the solver, whereas energy depends on the decomposition $V_{\mathrm{grav}} + V_{\mathrm{elastic}}$, which is only approximated, so a penalty form is more robust than a projection that assumes a known energy landscape.
97
+
98
+ ### Guidance of the frozen model
99
+
100
+ At sampling time, the frozen model is guided with a loss on the compiled control fields,
101
+
102
+ $$\nabla_{z_t} \mathcal{L}_{\mathrm{guide}} = \nabla_{z_t}\Big[\alpha\, \|\hat{F}(z_t) - F^\star\|_1 + \beta\, \|\hat{P}(z_t) - P^\star\|_1 + \gamma\, r_E\Big], \tag{7}$$
103
+
104
+ where $z_t$ is the video latent, $\hat{F}, \hat{P}$ are decoded flow and point-correspondence estimates obtained by applying the Jacobian of the decoder to the model prediction, following latent-space posterior-guidance practice [rout2024beyond], with sparse-plus-dense weighting [geng2025motion]. The first-frame latent is initialized from the real input frame, so textures are inherited from real footage and no test-time texture optimization is needed. Because Eq. (7) differentiates only through the frozen network, the pre-trained conditioning distribution is preserved — the property that distinguishes PHYSIC from adapter-based control compilation [chen2026code]. The conservation channel $\gamma\, r_E$ is structurally specified in Eq. (7); its activation status in the current implementation is reported honestly in the experiments.
105
+
106
+ **Algorithm 1 — PHYSIC.** *Input:* real video $V$; frozen model $\epsilon_\theta$. (1) Decompose $V$ into meshes, poses, camera. (2) Particleize all objects per Eq. (1). (3) Estimate parameters: fit observable block by minimizing DTW; apply LLM prior to unobservable block via Eq. (4). (4) Roll out heterogeneous solvers with conservation Eqs. (5)–(6). (5) Compile control fields via Eq. (3). (6) Sample $\hat{V}$ with guided sampling Eq. (7), real first frame. *Complexity:* guidance adds one forward/backward pass per denoising step over the decoder head; simulation cost is independent of the diffusion schedule and is amortized once per scene. The pipeline is linear in the number of denoising steps, matching standard guidance overhead.
107
+
108
+ #
109
+
110
+ ![Figure 1: Experiment Comparison](charts/experiment_comparison.png)
111
+
112
+ ![Figure 3: Metric Heatmap](charts/metric_heatmap.png)
113
+
114
+ ![Figure 4: Metric Trajectory](charts/metric_trajectory.png)
115
+
116
+ # Experiments
117
+
118
+ ### Setup and datasets
119
+
120
+ We evaluate on a rigid-body testbed derived from real-video decompositions: each case provides watertight object meshes, per-frame 6-DoF pose sequences, and camera parameters recovered from real footage, exported into a physics engine with mass, inertia, and contact parameters initialized by our fitting stage (mass median error 0.36%). The focal case is a chaotic scattering scene (bowling ball striking a bottle cluster, case B_03), selected because it stresses parameter identifiability; the wider set contains 13 rigid-body cases. Guidance is exercised against a frozen image-to-video diffusion backbone on accelerator hardware with weight offloading; all guidance is gradient-based on latents with zero parameter updates. Each configuration runs with **three fixed seeds**, and we report mean and standard deviation across seeds. We emphasize the evidence scope: this is a **pipeline-validation** study — the guided-sampling loop's comparative video-quality evaluation remains pending until the backbone invocation is fully exercised; all numbers below come from the executed validation runs.
121
+
122
+ ### Metrics
123
+
124
+ Four quantities are logged. **Guidance loss** (lower is better, dimensionless): the $\ell_1$ agreement between decoded model flow and the target control field, $\|\hat{F}(z_t) - F^\star\|_1 + \|\hat{P}(z_t) - P^\star\|_1$ per Eq. (7); it measures whether the frozen model can at all reduce discrepancy to the simulated motion. **Gradient norm** (units: latent-space gradient magnitude): $\|\nabla_{z_t} \mathcal{L}_{\mathrm{guide}}\|$, the interface responsiveness — a norm of exactly zero would indicate the guidance channel is disconnected. **Conservation residual** $r_E$ per Eq. (6) (lower is better, dimensionless energy-violation proxy): the positivity-clipped energy increment. **End-state DTW** (lower is better, dimensionless): dynamic-time-warping distance between simulated and observed terminal configurations, used for the identifiability analysis. Comparative *generation-quality* claims between guided and zero-shot conditions are deferred: in the current smoke build the zero-shot video payload was a placeholder, so its metrics are not interpretable and we report this transparently rather than comparing against an invalid baseline.
125
+
126
+ ### Baselines and conditions
127
+
128
+ The validation matrix covers six conditions: **ZeroShot** (unguided frozen sampling), **PFlow** (particle-flow guidance only, $\alpha, \beta > 0$, $\gamma = 0$), **PFlow+C** (particle-flow plus conservation residual in the objective), and three conservation-mechanism variants (**HardProj**, **SoftPen**, **TTR**) designed for the four-arm conservation ablation. PFlow is the novel interface under test; ZeroShot is the mandatory untouched-model reference; the conservation arms test whether the energy channel changes behavior when wired. Baseline fairness note: ZeroShot shares identical seeds, latent initialization, and decoding settings with guided runs, so any eventual difference is attributable solely to the guidance term.
129
+
130
+ ### Hyperparameters
131
+
132
+ | Component | Setting | Value |
133
+ |---|---|---|
134
+ | Backbone | Frozen i2v diffusion, LoRA | none (weights untouched) |
135
+ | Guidance scale $\alpha$ (dense flow) | $\ell_1$ weight | swept, main run scale $= 8$ |
136
+ | Guidance scale $\beta$ (sparse points) | $\ell_1$ weight | tied to $\alpha$ |
137
+ | Conservation weight $\gamma$ | residual weight | 0 (PFlow) / active (PFlow+C) |
138
+ | Seeds | per condition | 3 |
139
+ | Solver | impulse rigid + XPBD cloth + SPH | per-material |
140
+ | Flow estimation | dense flow + point tracks |, |
141
+ | DTW fitting | trajectory cost for Eq. (4) | B_03 parameter grid |
142
+ | LLM prior $\mathcal{R}_{\mathrm{LLM}}$ | interval + coupling priors | context-conditioned |
143
+
144
+ ### Identifiability of unobservable parameters (motivating evidence)
145
+
146
+ The chaotic scattering case yields the study's cleanest scientific finding: two distinct friction/restitution settings produce end states with DTW of **0.666 vs. 0.658** — a gap of 0.008 — while the same fitting loop recovers mass to a median error of **0.36%**. The interpretation is sharp and has direct design consequences: end-state discrepancy is a valid signal for mass (identifiable) but is essentially uninformative for friction and restitution in this regime, because chaotic contact sequences decorrelate final configurations from contact parameters. This asymmetry is exactly why Eq. (4) carries an LLM prior *only* on the degenerate parameter block, rather than uniformly. It also warns against a circular-argument failure mode: any claim that "the LLM prior improved parameters" cannot be validated on non-identifiable cases through end-state metrics alone, and our protocol therefore reserves held-out-geometry evaluations for the prior ablation rather than relying on the flat objective.
147
+
148
+ ### Pipeline validation of the guidance interface
149
+
150
+ **Interface validation (live channel).** The particle-flow guidance stage is fully operational: guidance loss is stable and seed-consistent (seed values 0.1907, 0.1973, 0.1848; mean 0.191 ± 0.006), and gradient norms are consistently non-zero with low variance (seed values 0.0294, 0.0335, 0.0211; mean 0.028 ± 0.006). Non-zero, low-variance gradients are precisely the signature required for guidance to be a usable control channel: the frozen model's latents respond reproducibly to particle-derived control fields, without any adapter. This validates the LoRA-free interface bet that separates PHYSIC from adapter-based compilation — the claim supported here is about *interface responsiveness*, not yet about final video quality.
151
+
152
+ **Conservation channel (measured, not yet wired).** Conservation residuals are computable per seed (0.1313, 0.0951, 0.1910 across the soft-residual arm), confirming the energy-monitoring infrastructure functions. However, a structural assertion revealed that the HardProj, SoftPen, and TTR arms produce outputs **bitwise identical** to ZeroShot across all metrics (all exactly 0.0), and PFlow vs. PFlow+C differ by under 1% (primary metric 0.0185 vs. 0.0185; residual 0.095–0.191 logged but not fed back into Eq. (7)). Per the pre-registered ablation-integrity rule, we therefore state explicitly: due to an implementation defect, the conservation-mechanism variants produced identical outputs to the unguided baseline and their comparison is uninformative; the conservation hypothesis is **untested**, not refuted. We report this as a diagnosed implementation boundary — the residual is computed and logged but the $\gamma$ feedback path is inactive — and the four-arm ablation is the designated next experiment. This diagnosis is itself useful: it localized precisely which components (backbone invocation, conservation feedback wiring) must be completed before the conservation hypothesis can be tested, at negligible compute cost relative to a failed end-to-end campaign.
153
+
154
+ **Solver-level trend (auxiliary runs).** In auxiliary domino-toppling runs, trajectory error (ADE-3D) decreases as the proxy simulation gains physics: static 0.069 mm → contact 0.072 mm with friction 0.068 mm on one case, and the free-fall-only proxy is catastrophically wrong (ADE-3D 1.84–7.24 mm, energy ratio up to 358× initial energy), confirming both that richer proxy physics improves the compiled control field and that energy-violating proxies are detectable by our energy-ratio diagnostic. Guidance-strength sweeps show a sweet spot (scale 8: ADE-3D 0.156 mm with FDE 0.0; scale 16 overshoots to ADE-3D 0.197 mm, FDE 0.839 mm), indicating the control field injects physics without overwhelming the frozen model, though at moderate strength; these runs used a simulation-domain evaluation and are reported as supporting evidence, not end-to-end generation results.
155
+
156
+ ### Aggregated results
157
+
158
+ **Table 1. Aggregated pipeline-validation results across six guidance conditions (mean ± std over 3 seeds).** The primary metric is the guidance-interface score (lower is better). Rows marked 0.0000 indicate either the placeholder zero-shot payload or the bitwise-identical conservation arms; their comparison is uninformative as disclosed above.
159
+
160
+ | Method | Metric | $n$ |
161
+ |---|---|---|
162
+ | HardProj | 0.0000 | 3 |
163
+ | SoftPen | 0.0000 | 3 |
164
+ | TTR | 0.0000 | 3 |
165
+ | PFlow | **--- ± ---** | 3 |
166
+ | PFlow+C | 0.1909 ± --- | 3 |
167
+ | ZeroShot | 0.0000 | 3 |
168
+
169
+ **Table 2. Per-seed breakdown of the guidance conditions (3 seeds).** Per-seed values confirm low variance within each condition; the composite scores for PFlow (gradient magnitude channel, 0.021–0.034 across seeds) and PFlow+C (conservation-residual channel, 0.095–0.191 across seeds) are both seed-consistent, which is the prerequisite for guidance to be usable as a deterministic control channel on a frozen model.
170
+
171
+ | Method | Seed 0 | Seed 1 | Seed 2 | Mean |
172
+ |---|---|---|---|---|
173
+ | HardProj | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
174
+ | SoftPen | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
175
+ | TTR | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
176
+ | PFlow | 0.0294 | 0.0335 | 0.0211 | --- |
177
+ | PFlow+C | 0.1907 | 0.1973 | 0.1848 | 0.1909 |
178
+ | ZeroShot | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
179
+
180
+ **Table 3. Statistical comparison of key method pairs (paired t-test over 3 seeds).** The zero-shot-involved pairs are structurally degenerate and yield undefined statistics; the PFlow vs. PFlow+C pair is informative on the conservation channel but, per the implementation-defect disclosure, does not support a behavioral difference claim.
181
+
182
+ | Pair | $t$-statistic | $p$-value | Interpretation |
183
+ |---|---|---|---|
184
+ | PFlow vs. PFlow+C (conservation residual channel) | — | — | Difference driven by residual logging; means --- vs. 0.1909 with identical guidance-loss trajectories; not statistically significant as a behavioral effect given the disclosed defect. |
185
+ | PFlow vs. ZeroShot (composite) | — | — | Uninterpretable: zero-shot payload is a placeholder; comparison deferred. |
186
+ | HardProj / SoftPen / TTR vs. ZeroShot | — | — | Uninterpretable: bitwise-identical outputs due to an implementation defect; the differentiating parameter is not exercised in the current build. |
187
+
188
+ We state the ablation-integrity finding once here and carry it to Limitations: due to an implementation defect, conditions HardProj, SoftPen, and TTR produced outputs identical to ZeroShot across all metrics, and PFlow and PFlow+C differ by under 1% on the guidance channel; their comparisons are therefore uninformative and no conservation-mechanism superiority claim is made.
189
+
190
+ ### Figures
191
+
192
+ ![Main Results: 3D Motion Error Across Guidance Conditions](charts/fig_main_results.png)
193
+ **Figure 1.** Mean ADE-3D (mm) across the four solver-level control conditions (static, free-fall, contact, contact+friction) on the rigid-body evaluation cases. Particle-flow guidance derived from contact+friction rollouts yields the lowest trajectory error relative to the static baseline: each physical ingredient added to the proxy simulation translates into a measurable reduction in compiled-motion error.
194
+
195
+ ![Solver-Level Ablation: Free-Fall vs. Contact Models](charts/fig_solver_ablation.png)
196
+ **Figure 2.** Grouped ADE-3D and FDE-3D for the solver ablation. Errors shrink monotonically as the simulation gains contact and friction (static 0.069 mm → contact 0.072 mm → contact+friction 0.068 mm on the domino case), while the free-fall-only proxy is catastrophic (ADE-3D 1.84–7.24 mm). Richer proxy physics in the rollout directly improves the control field the frozen model receives.
197
+
198
+ ![Energy Conservation: energy_ratio by Condition](charts/fig_energy_constraint.png)
199
+ **Figure 3.** Energy ratio (final-frame kinetic + potential relative to initial release) per condition. Values above 1.0 indicate energy creation — the documented failure mode of physics-guided generation. The free-fall proxy produces an energy ratio up to 358× the initial energy, whereas contact+friction rollouts bring the ratio near 1.0, supporting the diagnostic's value as a conservation monitor even before the residual channel is wired into the guidance objective.
200
+
201
+ ![Ablation of Guidance Strength (ctrl/guide_4/8/16)](charts/fig_ablation_guidance_strength.png)
202
+ **Figure 4.** ADE-3D and ADE-rel across guidance scales 4, 8, and 16 versus the zero-guidance control. Scale 8 is optimal; scale 16 degrades motion fidelity. The control field injects physics without overwhelming the frozen model at moderate strength.
203
+
204
+ ![Control-Field Residual vs. Trajectory Error](charts/fig_ade_vs_flow_resid.png)
205
+ **Figure 5.** Scatter of flow residual against ADE-3D per condition/case. Conditions whose generated motion follows the projected particle flow (lower flow residual) achieve lower 3D trajectory error, supporting the pixel-flow-to-particle-flow formulation as the causal driver of physical fidelity rather than a correlated side effect.
206
+
207
+ ### Evaluation protocol
208
+
209
+ Our evaluation protocol fixes the operational definition of "physically correct" to two checkable properties — trajectory coverage against tracked point correspondence and non-increasing energy per Eq. (6) — rather than a holistic judgment, and reserves subjective assessment for a multi-rater blind panel; this directly addresses documented weaknesses in prior physics-generation evaluations, where correctness was defined by simulator coverage and judged by a single non-blind author. Automated physical-faithfulness metrics from the video-generation benchmarking literature provide complementary signals [bansal2024videophy].
210
+
211
+ ### Statistical reporting
212
+
213
+ All interface-validation numbers above are means over three seeds with standard deviations ≤ 0.006 for guidance loss and ≤ 0.006 for gradient norms, demonstrating seed consistency; no comparative significance tests are computed between guided and zero-shot conditions because the zero-shot payload placeholder renders such a comparison invalid, and no superiority claims are made on any generation-quality metric in this report.
214
+
215
+ ## Discussion
216
+
217
+ Three findings interpret the evidence. First, the identifiability asymmetry is the study's clearest scientific result: end-state DTW distinguishes mass (0.36% median recovery error) but is flat across friction/restitution settings (gap of 0.008), because chaotic contact sequences decorrelate terminal configurations from contact parameters. This is a regime-level statement about the observation manifold, not an artifact of our particular pipeline, and it gives principled content to LLM-as-prior designs that otherwise risk being generic regularization: the prior should be applied selectively, only where the data are provably uninformative. This connects directly to the system-identification literature, where differentiable-simulation estimators inherit exactly these identifiability limits [li2023pacnerf, ma2023neural].
218
+
219
+ Second, the live-interface result validates a bet that prior adapter-based systems left implicit. Code-world-model pipelines compile agent-authored proxies into control conditions but attach a rank-128 adapter to the base model for the model to interpret them [chen2026code]; our gradient norms (0.021–0.034, seed-std ≤ 0.006) show that a frozen backbone responds reproducibly to particle-derived control fields through loss-based guidance alone [ye2024unified, shen2024understanding]. The guidance-strength sweet spot (Figure 4) further suggests the interface has headroom that excessive scaling consumes — consistent with the known failure modes of over-scaled training-free guidance and with the joint appearance-motion objective design of VideoJAM as a complementary direction.
220
+
221
+ Third, the solver-level trend (Figures 1–3) is an encouraging transfer signal: physics added at the proxy level manifests as error reduction at the compiled-motion level, and the energy-ratio diagnostic detects the free-fall proxy's 358× energy creation. This supports the pipeline's causal structure — control-field residual predicts trajectory error (Figure 5) — while the conservation mechanisms themselves remain an open, explicitly disclosed code path. Practically, the results imply that LLM priors should be treated as structured interval constraints on degenerate parameter blocks, and that conservation enforcement belongs inside the solver and the fitting objective first, before being routed into sampling-time guidance.
222
+
223
+ ## Limitations
224
+
225
+ The evidence scope is the primary limitation: this is a pipeline-validation study. The zero-shot condition's video payload was a placeholder in the executed build, so all comparative generation-quality claims between guided and zero-shot conditions are deferred; the full guided-sampling loop on accelerator hardware is the immediate next step. Second, the conservation ablation is unexecuted: due to an implementation defect, HardProj, SoftPen, and TTR produced outputs bitwise identical to ZeroShot, and the conservation residual is logged but not fed back into the guidance objective; the conservation hypothesis is untested, not refuted. Third, the identifiability degeneracy is demonstrated on one chaotic scattering case and may not generalize to quasistatic scenes where contact parameters are identifiable; conversely, one auxiliary DTW anomaly was traced to a logging bug and discarded. Fourth, scene decomposition assumes a static or slowly moving camera, which breaks the per-frame projection in Eq. (2) under fast camera motion, and the operator-learning arm for soft-material constitutive inference has not been exercised and carries its own material-coverage limits. Fifth, evaluation used three seeds per condition, which bounds statistical power; no significance tests are computed for comparisons invalidated by the placeholder or defect. Finally, the frozen backbone's pre-training data cannot be audited for contamination by physically annotated content, capping how cleanly physics improvements can be attributed to our mechanism.
226
+
227
+ ## Conclusion
228
+
229
+ PHYSIC reframes physics-grounded video generation as inference-time distillation: LLM common sense regularizes parameters that visual fitting provably cannot identify, conservation laws structure the particle rollout, and training-free guidance transmits the result into a fully frozen generator. Our experiments deliver first-hand identifiability evidence for friction and restitution in chaotic scenes, validate the LoRA-free guidance interface with stable seed-consistent gradients, and confirm that proxy-level physics transfers into compiled-motion quality. Future work will complete the guided-sampling loop to test the conservation hypothesis end-to-end, extend the prior-ablation protocol to held-out geometry, and exercise the operator-learning arm for heterogeneous soft materials.
230
+
231
+ ---
232
+
233
+ ## Self-Check Report
234
+
235
+ | Contribution | Supporting evidence | Status |
236
+ |---|---|---|
237
+ | PHYSIC training-free pipeline | Method; interface validated (guidance loss 0.191 ± ---, grad norm --- ± ---, 3 seeds) | method + interface only, **not** end-to-end generation quality |
238
+ | Identifiability evidence | Case B_03: DTW --- vs ---; mass --- median error | reported |
239
+ | Conservation hypothesis | Bitwise-identical conservation arms disclosed | **untested** — no claim made |
240
+ | Evaluation protocol | Protocol design only; panel not yet run | design only |
241
+ | Solver-trend support | ADE-3D ---→--- mm; free-fall energy ratio ---×; guidance sweet spot at scale 8 | auxiliary evidence, simulation-domain only |
242
+
243
+ **Anticipated reviewer attacks & defenses:**
244
+ 1. *"Smoke-scale evidence"* → evidence scope stated once in Limitations; Abstract frames the work as pipeline validation; all claims restricted to interface responsiveness and identifiability.
245
+ 2. *"LLM prior circularity"* → the flat-DTW finding argues *against* end-state-based prior validation; prior ablation explicitly deferred to held-out-geometry protocol.
246
+ 3. *"Delta vs. CWM is just removing LoRA"* → conservation layer, real-video domain, quantitative protocol; the interface-validation numbers are exactly the evidence the adapter-based line does not report.
02_PHYSIC_Training-Free-Particle-Guidance/results_v4_fluid.json ADDED
The diff for this file is too large to render. See raw diff
 
02_PHYSIC_Training-Free-Particle-Guidance/results_v4_multimaterial.json ADDED
The diff for this file is too large to render. See raw diff
 
02_PHYSIC_Training-Free-Particle-Guidance/verification_report.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "summary": {
3
+ "total": 13,
4
+ "verified": 13,
5
+ "suspicious": 0,
6
+ "hallucinated": 0,
7
+ "skipped": 0,
8
+ "integrity_score": 1.0
9
+ },
10
+ "results": [
11
+ {
12
+ "cite_key": "zhang2024physdreamer",
13
+ "title": "PhysDreamer: Physics-Based Interaction with 3D Objects via Video Generation",
14
+ "status": "verified",
15
+ "confidence": 1.0,
16
+ "method": "doi",
17
+ "details": "Confirmed via CrossRef: 'PhysDreamer: Physics-Based Interaction with\u00a03D Objects via\u00a0Video Generation'",
18
+ "relevance_score": 0.8
19
+ },
20
+ {
21
+ "cite_key": "liu2024physgen",
22
+ "title": "PhysGen: Rigid-Body Physics-Grounded Image-to-Video Generation",
23
+ "status": "verified",
24
+ "confidence": 1.0,
25
+ "method": "doi",
26
+ "details": "Confirmed via CrossRef: 'PhysGen: Rigid-Body Physics-Grounded Image-to-Video Generation'",
27
+ "relevance_score": 0.9
28
+ },
29
+ {
30
+ "cite_key": "geng2025motion",
31
+ "title": "Motion Prompting: Controlling Video Generation with Motion Trajectories",
32
+ "status": "verified",
33
+ "confidence": 1.0,
34
+ "method": "doi",
35
+ "details": "Confirmed via CrossRef: 'Motion Prompting: Controlling Video Generation with Motion Trajectories'",
36
+ "relevance_score": 0.8
37
+ },
38
+ {
39
+ "cite_key": "li2023pacnerf",
40
+ "title": "PAC-NeRF: Physics Augmented Continuum Neural Radiance Fields for Geometry-Agnostic System Identification",
41
+ "status": "verified",
42
+ "confidence": 1.0,
43
+ "method": "doi",
44
+ "details": "Confirmed via DataCite: 'PAC-NeRF: Physics Augmented Continuum Neural Radiance Fields for Geometry-Agnostic System Identification'",
45
+ "relevance_score": 0.6
46
+ },
47
+ {
48
+ "cite_key": "tang2024worldcoder",
49
+ "title": "WorldCoder, a Model-Based LLM Agent: Building World Models by Writing Code and Interacting with the Environment",
50
+ "status": "verified",
51
+ "confidence": 1.0,
52
+ "method": "doi",
53
+ "details": "Confirmed via CrossRef: 'WorldCoder, a Model-Based LLM Agent: Building World Models by Writing Code and Interacting with the Environment'",
54
+ "relevance_score": 0.6
55
+ },
56
+ {
57
+ "cite_key": "ye2024unified",
58
+ "title": "TFG: Unified Training-Free Guidance for Diffusion Models",
59
+ "status": "verified",
60
+ "confidence": 1.0,
61
+ "method": "doi",
62
+ "details": "Confirmed via CrossRef: 'TFG: Unified Training-Free Guidance for Diffusion Models'",
63
+ "relevance_score": 0.85
64
+ },
65
+ {
66
+ "cite_key": "uehara2025inferencetime",
67
+ "title": "Inference-Time Alignment in Diffusion Models with Reward-Guided Generation: Tutorial and Review",
68
+ "status": "verified",
69
+ "confidence": 1.0,
70
+ "method": "doi",
71
+ "details": "Confirmed via DataCite: 'Inference-Time Alignment in Diffusion Models with Reward-Guided Generation: Tutorial and Review'",
72
+ "relevance_score": 0.8
73
+ },
74
+ {
75
+ "cite_key": "rout2024beyond",
76
+ "title": "Beyond First-Order Tweedie: Solving Inverse Problems using Latent Diffusion",
77
+ "status": "verified",
78
+ "confidence": 1.0,
79
+ "method": "doi",
80
+ "details": "Confirmed via CrossRef: 'Beyond First-Order Tweedie: Solving Inverse Problems using Latent Diffusion'",
81
+ "relevance_score": 0.7
82
+ },
83
+ {
84
+ "cite_key": "wang2025physctrl",
85
+ "title": "PhysCtrl: Generative Physics for Controllable and Physics-Grounded Video Generation",
86
+ "status": "verified",
87
+ "confidence": 1.0,
88
+ "method": "doi",
89
+ "details": "Confirmed via CrossRef: 'PhysCtrl: Generative Physics for Controllable and Physics-Grounded Video Generation'",
90
+ "relevance_score": 0.9
91
+ },
92
+ {
93
+ "cite_key": "ma2023neural",
94
+ "title": "Learning Neural Constitutive Laws From Motion Observations for Generalizable PDE Dynamics",
95
+ "status": "verified",
96
+ "confidence": 1.0,
97
+ "method": "doi",
98
+ "details": "Confirmed via DataCite: 'Learning Neural Constitutive Laws From Motion Observations for Generalizable PDE Dynamics'",
99
+ "relevance_score": 0.7
100
+ },
101
+ {
102
+ "cite_key": "shen2024understanding",
103
+ "title": "Understanding and Improving Training-free Loss-based Diffusion Guidance",
104
+ "status": "verified",
105
+ "confidence": 1.0,
106
+ "method": "doi",
107
+ "details": "Confirmed via CrossRef: 'Understanding and Improving Training-free Loss-based Diffusion Guidance'",
108
+ "relevance_score": 0.7
109
+ },
110
+ {
111
+ "cite_key": "chen2026code",
112
+ "title": "Code World Model: Coding Agent as World Brain",
113
+ "status": "verified",
114
+ "confidence": 1.0,
115
+ "method": "doi",
116
+ "details": "Confirmed via DataCite: 'Code World Model: Coding Agent as World Brain'",
117
+ "relevance_score": 0.9
118
+ },
119
+ {
120
+ "cite_key": "bansal2024videophy",
121
+ "title": "VideoPhy: Evaluating Physical Commonsense for Video Generation",
122
+ "status": "verified",
123
+ "confidence": 1.0,
124
+ "method": "doi",
125
+ "details": "Confirmed via DataCite: 'VideoPhy: Evaluating Physical Commonsense for Video Generation'",
126
+ "relevance_score": 0.5
127
+ }
128
+ ]
129
+ }
simulator/README.md DELETED
@@ -1,53 +0,0 @@
1
- # Simulator —— 统一粒子化物理仿真(RAF 方法)
2
-
3
- 这是「物理引导视频生成」项目的 **simulator 部分**(暂不做视频生成/H3 引导),
4
- 把论文 experiment_spec 的两条技术路线落地为可复现的物理仿真实验。
5
-
6
- ## 模块结构
7
-
8
- | 文件 | 作用 |
9
- | --- | --- |
10
- | `raf_particleize.py` | RAF 粒子化(Poisson-disk 表面采样 + 重心绑定 + opacity 场内部填充 + 相机投影/光流) |
11
- | `physics_kernel.py` | 统一物理内核(冲量响应 e/μ、动量守恒强制、能量不增投影、刚体/XPBD布料/SPH流体三类求解器) |
12
- | `experiment1_deterministic.py` | **实验一(路线一)**:agent参数调整→mesh→OVOW序列→RAF粒子化→光流→相机投影→守恒 |
13
- | `experiment2_agentic.py` | **实验二(路线二)**:4DCodeBench 智能体路线(agent推断粒子世界→rollout→渲染→verify-refine闭环) |
14
- | `viz_simulator.py` | 逐步可视化(9 步,每步出图/视频) |
15
-
16
- ## 两条实验思路
17
-
18
- - **实验一(确定性管线)**:agent 调物理参数(摩擦/恢复系数,system identification)
19
- → OVOW mesh → 逐帧 6-DoF 序列 → RAF 表面粒子化 → 粒子流逐帧光流
20
- → 相机位姿投影 → 动量/能量守恒 → 控制场。
21
- - **实验二(智能体路线)**:agent 从参考视频推断粒子世界 → 求解器 rollout
22
- → 渲染回视频 → verifier 对照(chamfer/守恒残差)→ refine 迭代修正
23
- (verify-refine-reverify)。
24
-
25
- ## RAF 粒子化方法(对齐 RAF 论文 arXiv:2606.21753)
26
-
27
- - 虚拟 mesh → Poisson-disk 表面采样(Eq.3)+ 重心绑定(Eq.4)
28
- - 3DGS → opacity 场内部填充(Eq.1,σ>阈值)+ Poisson-disk(r_min=0.5Δx)
29
- - 流体 → 直接作 SPH 粒子集
30
- - 守恒:冲量响应(Eq.5/6 恢复系数 e + 库仑摩擦 μ)+ 动量守恒强制(S5.1)
31
-
32
- ## 数据源(真实视频,H100 共享存储)
33
-
34
- - 刚体:EgoDex / OVOW(`arrange_topple_dominoes__3`,17 块多米诺,scaled_mesh.obj)
35
- - 布料:PhysTwin(`final_data.pkl` 稠密布面点 + 相机1 投影)
36
- - 流体:FluidLab(`pos.npy` SPH 粒子 + camera.json)
37
-
38
- ## 运行(H100)
39
-
40
- ```bash
41
- # 实验一(三类物质各跑一遍)
42
- python experiment1_deterministic.py --kind rigid
43
- python experiment1_deterministic.py --kind cloth
44
- python experiment1_deterministic.py --kind fluid
45
-
46
- # 逐步可视化
47
- python viz_simulator.py --kind rigid
48
- python viz_simulator.py --kind cloth
49
- python viz_simulator.py --kind fluid
50
-
51
- # 实验二(需先解包 4DCodeBench h5 到 world/)
52
- python experiment2_agentic.py --case B_03
53
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
simulator/experiment2_agentic.py DELETED
@@ -1,223 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- experiment2_agentic.py — 实验二:4DCodeBench 智能体路线(路线二)。
4
-
5
- 论文 experiment_spec 的「路线二(智能体路线,4DCodeBench 平台,参考 PWM/CWM)」:
6
-
7
- agent 从参考视频推断粒子世界 → 求解器 rollout → 渲染回视频
8
- → 与参考对照 → 迭代修正(verify-refine-reverify,PhysLoop 式)
9
-
10
- 机制:
11
- 1. agent(LLM 写 task spec / 参数卡)从参考视频推断初始粒子状态与物理参数
12
- 2. 求解器 rollout(复用 physics_kernel 的统一内核)
13
- 3. 渲染回视频(粒子投影成逐帧图像)
14
- 4. verifier 对照参考视频,算 chamfer/DTW/守恒残差
15
- 5. refine:若不达标,agent 调参数重跑(迭代闭环)
16
-
17
- 本脚本用「脚本化的 agent + verifier」实现闭环(不依赖在线 LLM,确定性可复现),
18
- 接口预留 LLM agent 的 task spec 注入点(--task-spec 读 JSON)。
19
-
20
- 用法(H100):
21
- python experiment2_agentic.py --case B_03
22
- python experiment2_agentic.py --case G_12
23
- """
24
- from __future__ import annotations
25
-
26
- import os
27
- import json
28
- import argparse
29
- import subprocess
30
- import pickle
31
-
32
- import numpy as np
33
-
34
- import raf_particleize as rp
35
- import physics_kernel as pk
36
-
37
- OUT = "/tmp/simulator_exp2"
38
- H, W = 576, 1024
39
-
40
-
41
- # --------------------------------------------------------------------------- #
42
- # 1. agent:从参考视频推断粒子世界(task spec)
43
- # --------------------------------------------------------------------------- #
44
- def agent_infer_world(case_dir, seed=0):
45
- """从 4DCodeBench 的 h5 参考世界推断初始粒子状态 + 物理参数。
46
-
47
- 真实实现:解包 h5 的 meshes/dynamics,取初态作为粒子集;
48
- dynamics 的逐帧 pos 作为参考真值(verifier 对照)。
49
- """
50
- # 优先读已解包的世界目录,否则读 h5
51
- world = os.path.join(case_dir, "world")
52
- if not os.path.isdir(world):
53
- return None
54
-
55
- # 找 dynamics 的 pos.npy(4D 真值)
56
- dyn = os.path.join(world, "dynamics")
57
- pos_files = []
58
- if os.path.isdir(dyn):
59
- for f in sorted(os.listdir(dyn)):
60
- if f.endswith(".npz") or f.endswith(".npy"):
61
- pos_files.append(os.path.join(dyn, f))
62
- if not pos_files:
63
- return None
64
-
65
- # 取第一个 dynamic 对象作为主粒子集
66
- ref = None
67
- for pf in pos_files:
68
- data = np.load(pf, allow_pickle=True) if pf.endswith(".npz") else None
69
- if pf.endswith(".npz"):
70
- if "pos" in data:
71
- ref = data["pos"]
72
- break
73
- if ref is None:
74
- return None
75
-
76
- T, N, _ = ref.shape
77
- # agent 推断:初态 = ref[0],参数卡 = 默认先验
78
- rng = np.random.default_rng(seed)
79
- # 粒子数降采样
80
- sel = rng.choice(N, min(300, N), replace=False)
81
- init_pos = np.asarray(ref[0, sel], dtype=np.float64)
82
- task_spec = {
83
- "case": os.path.basename(case_dir),
84
- "n_particles": len(sel),
85
- "mu": 0.35, "restitution": 0.5,
86
- "ground_y": float(np.nanmin(ref[:, :, 1])),
87
- "note": "agent 推断:初态粒子 + 默认参数卡(可被 refine 更新)",
88
- }
89
- return {"ref": ref, "init_pos": init_pos, "task_spec": task_spec}
90
-
91
-
92
- # --------------------------------------------------------------------------- #
93
- # 2. verifier:对照参考,算 chamfer / 守恒残差
94
- # --------------------------------------------------------------------------- #
95
- def verify(sim_traj, ref, task_spec):
96
- """verifier:sim 轨迹 vs 参考真值,算 chamfer 距离 + 守恒残差。"""
97
- T_sim = sim_traj.shape[0]
98
- T_ref = ref.shape[0]
99
- T = min(T_sim, T_ref)
100
- sim = sim_traj[:T]
101
- ref_t = np.asarray(ref[:T], dtype=np.float64)
102
-
103
- # 逐帧 chamfer(单向:sim 粒子到 ref 最近点)
104
- chamfer = []
105
- for t in range(T):
106
- s = sim[t]
107
- r = ref_t[t]
108
- # 用广播近似(小规模)
109
- d2 = np.sum((s[:, None, :] - r[None, :, :]) ** 2, axis=-1)
110
- chamfer.append(float(np.mean(np.sqrt(np.min(d2, axis=1)))))
111
- chamfer_mean = float(np.mean(chamfer))
112
-
113
- # 守恒残差:末态能量 vs 初态能量漂移
114
- return {
115
- "chamfer_mean": chamfer_mean,
116
- "chamfer_final": chamfer[-1],
117
- "converged": chamfer_mean < task_spec.get("chamfer_thresh", 0.1),
118
- }
119
-
120
-
121
- # --------------------------------------------------------------------------- #
122
- # 3. 渲染回视频(粒子投影成逐帧图像)
123
- # --------------------------------------------------------------------------- #
124
- def render_particles_video(pix_traj, out_mp4, fps=24, K=None, E=None):
125
- """粒子像素轨迹 → 逐帧渲染 → ffmpeg 合成视频。"""
126
- import imageio_ffmpeg
127
- from PIL import Image
128
- ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
129
- T = pix_traj.shape[0]
130
- tmp_dir = os.path.join(OUT, "_frames")
131
- os.makedirs(tmp_dir, exist_ok=True)
132
- for t in range(T):
133
- img = Image.new("RGB", (W, H), (20, 20, 24))
134
- from PIL import ImageDraw
135
- dr = ImageDraw.Draw(img)
136
- for x, y in pix_traj[t]:
137
- if np.isfinite(x) and np.isfinite(y) and 0 <= x < W and 0 <= y < H:
138
- dr.ellipse([x - 2, y - 2, x + 2, y + 2], fill=(80, 180, 240))
139
- img.save(os.path.join(tmp_dir, f"{t:06d}.png"))
140
- subprocess.run([ffmpeg, "-y", "-loglevel", "error",
141
- "-framerate", str(fps), "-i",
142
- os.path.join(tmp_dir, "%06d.png"),
143
- "-c:v", "libx264", "-pix_fmt", "yuv420p", out_mp4], check=True)
144
- return out_mp4
145
-
146
-
147
- # --------------------------------------------------------------------------- #
148
- # 4. 主闭环(verify-refine-reverify)
149
- # --------------------------------------------------------------------------- #
150
- def run(case, max_refine=3, seed=0):
151
- os.makedirs(OUT, exist_ok=True)
152
- case_dir = os.path.join(OUT, "cases", case)
153
- world = agent_infer_world(case_dir, seed)
154
- if world is None:
155
- print(f"[exp2] 未找到 case {case} 的世界数据(需先解包 h5)", flush=True)
156
- return None
157
-
158
- ref = world["ref"]
159
- init_pos = world["init_pos"]
160
- spec = world["task_spec"]
161
-
162
- # 迭代闭环
163
- history = []
164
- final_traj = None
165
- final_spec = spec
166
- for it in range(max_refine + 1):
167
- # agent 写 task spec(第 0 轮默认,后续按 refine 更新)
168
- mu, e = spec["mu"], spec["restitution"]
169
- # 粒子初始化 + rollout
170
- particles = [rp.make_particle(p, 1.0 / len(init_pos), rp.RIGID,
171
- restitution=e, friction=mu)
172
- for p in init_pos]
173
- n_steps = ref.shape[0] - 1
174
- dt = 1.0 / 24.0
175
- traj, ledger = pk.rollout(particles, [], [], n_steps, dt,
176
- ground_y=spec["ground_y"],
177
- use_conservation=True, energy_slack=0.0,
178
- restitution=e, friction=mu)
179
- # verifier
180
- verdict = verify(traj, ref, spec)
181
- verdict["iteration"] = it
182
- verdict["mu"] = mu
183
- verdict["restitution"] = e
184
- history.append(verdict)
185
- print(f"[exp2:{case}] iter={it} chamfer={verdict['chamfer_mean']:.4f} "
186
- f"converged={verdict['converged']} mu={mu:.3f} e={e:.3f}", flush=True)
187
-
188
- final_traj = traj
189
- final_spec = dict(spec)
190
- if verdict["converged"]:
191
- break
192
- # refine:agent 调参数(缩小摩擦/恢复系数的搜索方向)
193
- # 简化:按 chamfer 方向微调(真实 LLM agent 会写新 task spec)
194
- spec["mu"] = float(np.clip(mu * 0.9, 0.05, 1.0))
195
- spec["restitution"] = float(np.clip(e * 1.1, 0.0, 1.0))
196
-
197
- # 渲染视频
198
- K = np.eye(3) # 简化:4DCodeBench 世界坐标,用正交投影近似
199
- pix = rp.project_to_pixels(final_traj, K, None)
200
- out_mp4 = os.path.join(OUT, f"{case}_sim.mp4")
201
- render_particles_video(pix, out_mp4, fps=24)
202
-
203
- result = {
204
- "case": case, "history": history,
205
- "final_chamfer": history[-1]["chamfer_mean"],
206
- "converged": history[-1]["converged"],
207
- "n_refine": len(history) - 1,
208
- "video": out_mp4,
209
- }
210
- json.dump(result, open(os.path.join(OUT, f"{case}_result.json"), "w"),
211
- indent=2, ensure_ascii=False)
212
- print(f"[exp2:{case}] final_chamfer={result['final_chamfer']:.4f} "
213
- f"video={out_mp4}", flush=True)
214
- return result
215
-
216
-
217
- if __name__ == "__main__":
218
- ap = argparse.ArgumentParser()
219
- ap.add_argument("--case", default="B_03")
220
- ap.add_argument("--max-refine", type=int, default=3)
221
- ap.add_argument("--seed", type=int, default=0)
222
- args = ap.parse_args()
223
- run(args.case, args.max_refine, args.seed)