diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d052ad2761769970dddc76f62e0eb7ad95daf8c3 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29e2604dc20b6e36701433308e131575c79bb3de Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/cachereuse.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..339797698425c22ddb78556ed4463b5fc0f943fa Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f12113951ae5c3c5ab073924042852a1e0049ae0 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41a195c87dba05a25448b83b328acc09bb62af75 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8237c6a503d12c5af60793290cca1466ec9b2c2 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da8fb859d61315bfbecbf97acb7287d4c075fd64 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7eb75a13891b527a52372f10bba189accae9fd6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..945af88503a12a80a0bb38186abb5ca4b6563f51 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2c5a8cb460372e00d23d2ad453282c6c51d2eef Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/flowcache_metric_stats_2026-05-19_09-18-01.json b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/flowcache_metric_stats_2026-05-19_09-18-01.json new file mode 100644 index 0000000000000000000000000000000000000000..2f29778a033f4993f571b1c7cb5e4e018057f165 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/flowcache_metric_stats_2026-05-19_09-18-01.json @@ -0,0 +1,10698 @@ +{ + "description": "FlowCache original per-chunk reuse metric. flowcache_rel_l1 = mean(abs(x_embedder(X_t_current) - x_embedder(X_t_previous))) / (mean(abs(x_embedder(X_t_previous))) + 1e-8). flowcache_rel_l1_ratio = sum(abs(delta)) / sum(abs(previous_feature)); flowcache_accumulated_rel_l1 is the accumulated value compared with rel_l1_thresh.", + "records": [ + { + "infer_idx": 0, + "cur_denoise_step": 1, + "denoise_stage": 0, + "denoise_idx": 1, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 2, + "denoise_stage": 0, + "denoise_idx": 2, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 3, + "denoise_stage": 0, + "denoise_idx": 3, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 4, + "denoise_stage": 0, + "denoise_idx": 4, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 5, + "denoise_stage": 0, + "denoise_idx": 5, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.001373291015625, + "flowcache_rel_l1_ratio": 0.0013741012168141593, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.001373291015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 6, + "denoise_stage": 0, + "denoise_idx": 6, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.001373291015625, + "flowcache_rel_l1_ratio": 0.0013741012168141593, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00274658203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 7, + "denoise_stage": 0, + "denoise_idx": 7, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.001373291015625, + "flowcache_rel_l1_ratio": 0.0013741012168141593, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.004119873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 8, + "denoise_stage": 0, + "denoise_idx": 8, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.001373291015625, + "flowcache_rel_l1_ratio": 0.0013741012168141593, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0054931640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 9, + "denoise_stage": 0, + "denoise_idx": 9, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.001373291015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.006866455078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 10, + "denoise_stage": 0, + "denoise_idx": 10, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00824737548828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 11, + "denoise_stage": 0, + "denoise_idx": 11, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0096282958984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 12, + "denoise_stage": 0, + "denoise_idx": 12, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01100921630859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 13, + "denoise_stage": 0, + "denoise_idx": 13, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01239013671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 14, + "denoise_stage": 0, + "denoise_idx": 14, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013802083333333333, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01377105712890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 15, + "denoise_stage": 0, + "denoise_idx": 15, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00138092041015625, + "flowcache_rel_l1_ratio": 0.0013863699776785715, + "flowcache_delta_l1_norm": 2544.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0151519775390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 16, + "denoise_stage": 1, + "denoise_idx": 0, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.00408935546875, + "flowcache_rel_l1_ratio": 0.004080636160714286, + "flowcache_delta_l1_norm": 7488.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.00408935546875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 17, + "denoise_stage": 1, + "denoise_idx": 1, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00408935546875, + "flowcache_rel_l1_ratio": 0.004080636160714286, + "flowcache_delta_l1_norm": 7488.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0081787109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 17, + "denoise_stage": 1, + "denoise_idx": 1, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 18, + "denoise_stage": 1, + "denoise_idx": 2, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.00408935546875, + "flowcache_rel_l1_ratio": 0.004098934977578475, + "flowcache_delta_l1_norm": 7488.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.01226806640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 18, + "denoise_stage": 1, + "denoise_idx": 2, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 19, + "denoise_stage": 1, + "denoise_idx": 3, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004119873046875, + "flowcache_rel_l1_ratio": 0.004117398648648648, + "flowcache_delta_l1_norm": 7488.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.016387939453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 19, + "denoise_stage": 1, + "denoise_idx": 3, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 20, + "denoise_stage": 1, + "denoise_idx": 4, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.00537109375, + "flowcache_rel_l1_ratio": 0.005349099099099099, + "flowcache_delta_l1_norm": 9728.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.00537109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 20, + "denoise_stage": 1, + "denoise_idx": 4, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 21, + "denoise_stage": 1, + "denoise_idx": 5, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.00537109375, + "flowcache_rel_l1_ratio": 0.0053733031674208145, + "flowcache_delta_l1_norm": 9728.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.0107421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 21, + "denoise_stage": 1, + "denoise_idx": 5, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012271847345132743, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00122833251953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 22, + "denoise_stage": 1, + "denoise_idx": 6, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.005401611328125, + "flowcache_rel_l1_ratio": 0.005397727272727273, + "flowcache_delta_l1_norm": 9728.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.016143798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 22, + "denoise_stage": 1, + "denoise_idx": 6, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012271847345132743, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0024566650390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 23, + "denoise_stage": 1, + "denoise_idx": 7, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.0064697265625, + "flowcache_rel_l1_ratio": 0.006427556818181818, + "flowcache_delta_l1_norm": 11584.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.0064697265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 23, + "denoise_stage": 1, + "denoise_idx": 7, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012271847345132743, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0036773681640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 24, + "denoise_stage": 1, + "denoise_idx": 8, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.0064697265625, + "flowcache_rel_l1_ratio": 0.006456906392694064, + "flowcache_delta_l1_norm": 11584.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.012939453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 24, + "denoise_stage": 1, + "denoise_idx": 8, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012185425884955752, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0048980712890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 25, + "denoise_stage": 1, + "denoise_idx": 9, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.006500244140625, + "flowcache_rel_l1_ratio": 0.006486525229357798, + "flowcache_delta_l1_norm": 11584.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.019439697265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 25, + "denoise_stage": 1, + "denoise_idx": 9, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012271847345132743, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00612640380859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 26, + "denoise_stage": 1, + "denoise_idx": 10, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.007781982421875, + "flowcache_rel_l1_ratio": 0.007776497695852535, + "flowcache_delta_l1_norm": 13824.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.007781982421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 26, + "denoise_stage": 1, + "denoise_idx": 10, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00734710693359375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 27, + "denoise_stage": 1, + "denoise_idx": 11, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.0078125, + "flowcache_rel_l1_ratio": 0.0078125, + "flowcache_delta_l1_norm": 13824.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.015594482421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 27, + "denoise_stage": 1, + "denoise_idx": 11, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012326388888888888, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.008575439453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 28, + "denoise_stage": 1, + "denoise_idx": 12, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.0087890625, + "flowcache_rel_l1_ratio": 0.00879360465116279, + "flowcache_delta_l1_norm": 15488.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.0087890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 28, + "denoise_stage": 1, + "denoise_idx": 12, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012326388888888888, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00980377197265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 29, + "denoise_stage": 1, + "denoise_idx": 13, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008834696261682243, + "flowcache_delta_l1_norm": 15488.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.01763916015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 29, + "denoise_stage": 1, + "denoise_idx": 13, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012326388888888888, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0110321044921875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 30, + "denoise_stage": 1, + "denoise_idx": 14, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010023584905660377, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.010009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 30, + "denoise_stage": 1, + "denoise_idx": 14, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012326388888888888, + "flowcache_delta_l1_norm": 2272.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01226806640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 31, + "denoise_stage": 1, + "denoise_idx": 15, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010071090047393365, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.02001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 31, + "denoise_stage": 1, + "denoise_idx": 15, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01349639892578125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 32, + "denoise_stage": 2, + "denoise_idx": 0, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01123046875, + "flowcache_rel_l1_ratio": 0.011235119047619048, + "flowcache_delta_l1_norm": 19328.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.01123046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 32, + "denoise_stage": 2, + "denoise_idx": 0, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012294224330357143, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0147247314453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 33, + "denoise_stage": 2, + "denoise_idx": 1, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011288875598086124, + "flowcache_delta_l1_norm": 19328.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.02252197265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 33, + "denoise_stage": 2, + "denoise_idx": 1, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012294224330357143, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01595306396484375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 33, + "denoise_stage": 2, + "denoise_idx": 1, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 34, + "denoise_stage": 2, + "denoise_idx": 2, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012832125603864734, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.01287841796875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 34, + "denoise_stage": 2, + "denoise_idx": 2, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004778180803571429, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.004791259765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 34, + "denoise_stage": 2, + "denoise_idx": 2, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 35, + "denoise_stage": 2, + "denoise_idx": 3, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.012939453125, + "flowcache_rel_l1_ratio": 0.012894417475728155, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1687552.0, + "flowcache_accumulated_rel_l1": 0.02581787109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 35, + "denoise_stage": 2, + "denoise_idx": 3, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004799607623318386, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.00958251953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 35, + "denoise_stage": 2, + "denoise_idx": 3, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 36, + "denoise_stage": 2, + "denoise_idx": 4, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.0145263671875, + "flowcache_rel_l1_ratio": 0.014481707317073171, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.0145263671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 36, + "denoise_stage": 2, + "denoise_idx": 4, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004799607623318386, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.014373779296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 36, + "denoise_stage": 2, + "denoise_idx": 4, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 37, + "denoise_stage": 2, + "denoise_idx": 5, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01470947265625, + "flowcache_rel_l1_ratio": 0.014624384236453201, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1662976.0, + "flowcache_accumulated_rel_l1": 0.02923583984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 37, + "denoise_stage": 2, + "denoise_idx": 5, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.00482177734375, + "flowcache_rel_l1_ratio": 0.004821227477477478, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.019195556640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 37, + "denoise_stage": 2, + "denoise_idx": 5, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00122833251953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 38, + "denoise_stage": 2, + "denoise_idx": 6, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0166015625, + "flowcache_rel_l1_ratio": 0.016635572139303483, + "flowcache_delta_l1_norm": 27392.0, + "flowcache_prev_feat_l1_norm": 1646592.0, + "flowcache_accumulated_rel_l1": 0.0166015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 38, + "denoise_stage": 2, + "denoise_idx": 6, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.006134033203125, + "flowcache_rel_l1_ratio": 0.00611566742081448, + "flowcache_delta_l1_norm": 11072.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.006134033203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 38, + "denoise_stage": 2, + "denoise_idx": 6, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0024566650390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 39, + "denoise_stage": 2, + "denoise_idx": 7, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.0177001953125, + "flowcache_rel_l1_ratio": 0.017734375, + "flowcache_delta_l1_norm": 29056.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.0177001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 39, + "denoise_stage": 2, + "denoise_idx": 7, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.00616455078125, + "flowcache_rel_l1_ratio": 0.006178977272727273, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.012298583984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 39, + "denoise_stage": 2, + "denoise_idx": 7, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00368499755859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 40, + "denoise_stage": 2, + "denoise_idx": 8, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.01893939393939394, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1622016.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 40, + "denoise_stage": 2, + "denoise_idx": 8, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006195068359375, + "flowcache_rel_l1_ratio": 0.006143465909090909, + "flowcache_delta_l1_norm": 11072.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.01849365234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 40, + "denoise_stage": 2, + "denoise_idx": 8, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.004913330078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 41, + "denoise_stage": 2, + "denoise_idx": 9, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.0202252538071066, + "flowcache_delta_l1_norm": 32640.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 41, + "denoise_stage": 2, + "denoise_idx": 9, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.00732421875, + "flowcache_rel_l1_ratio": 0.0073487442922374425, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00732421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 41, + "denoise_stage": 2, + "denoise_idx": 9, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00614166259765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 42, + "denoise_stage": 2, + "denoise_idx": 10, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021794871794871794, + "flowcache_delta_l1_norm": 34816.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 42, + "denoise_stage": 2, + "denoise_idx": 10, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.007382454128440367, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.01470947265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 42, + "denoise_stage": 2, + "denoise_idx": 10, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0073699951171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 43, + "denoise_stage": 2, + "denoise_idx": 11, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.0234779792746114, + "flowcache_delta_l1_norm": 37120.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 43, + "denoise_stage": 2, + "denoise_idx": 11, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.007415771484375, + "flowcache_rel_l1_ratio": 0.00741647465437788, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.022125244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 43, + "denoise_stage": 2, + "denoise_idx": 11, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00860595703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 44, + "denoise_stage": 2, + "denoise_idx": 12, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.02519633507853403, + "flowcache_delta_l1_norm": 39424.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 44, + "denoise_stage": 2, + "denoise_idx": 12, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.0087890625, + "flowcache_rel_l1_ratio": 0.00882523148148148, + "flowcache_delta_l1_norm": 15616.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.0087890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 44, + "denoise_stage": 2, + "denoise_idx": 12, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0098419189453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 45, + "denoise_stage": 2, + "denoise_idx": 13, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.0272216796875, + "flowcache_rel_l1_ratio": 0.027116402116402115, + "flowcache_delta_l1_norm": 41984.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.0272216796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 45, + "denoise_stage": 2, + "denoise_idx": 13, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008866279069767441, + "flowcache_delta_l1_norm": 15616.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.01763916015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 45, + "denoise_stage": 2, + "denoise_idx": 13, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.011077880859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 46, + "denoise_stage": 2, + "denoise_idx": 14, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.0291748046875, + "flowcache_rel_l1_ratio": 0.02925531914893617, + "flowcache_delta_l1_norm": 45056.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.0291748046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 46, + "denoise_stage": 2, + "denoise_idx": 14, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00994873046875, + "flowcache_rel_l1_ratio": 0.01004988262910798, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 46, + "denoise_stage": 2, + "denoise_idx": 14, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0123138427734375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 47, + "denoise_stage": 2, + "denoise_idx": 15, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.03173828125, + "flowcache_rel_l1_ratio": 0.031586021505376344, + "flowcache_delta_l1_norm": 48128.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.03173828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 47, + "denoise_stage": 2, + "denoise_idx": 15, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010097287735849057, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.01995849609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 47, + "denoise_stage": 2, + "denoise_idx": 15, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0135498046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 48, + "denoise_stage": 3, + "denoise_idx": 0, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.0341796875, + "flowcache_rel_l1_ratio": 0.03413722826086957, + "flowcache_delta_l1_norm": 51456.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.0341796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 48, + "denoise_stage": 3, + "denoise_idx": 0, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011329976303317536, + "flowcache_delta_l1_norm": 19584.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.01129150390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 48, + "denoise_stage": 3, + "denoise_idx": 0, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0147857666015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 49, + "denoise_stage": 3, + "denoise_idx": 1, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.036865234375, + "flowcache_rel_l1_ratio": 0.03708791208791209, + "flowcache_delta_l1_norm": 55296.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.036865234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 49, + "denoise_stage": 3, + "denoise_idx": 1, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01141357421875, + "flowcache_rel_l1_ratio": 0.011383928571428571, + "flowcache_delta_l1_norm": 19584.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.022705078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 49, + "denoise_stage": 3, + "denoise_idx": 1, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01602935791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 49, + "denoise_stage": 3, + "denoise_idx": 1, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 50, + "denoise_stage": 3, + "denoise_idx": 2, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.0400390625, + "flowcache_rel_l1_ratio": 0.04027777777777778, + "flowcache_delta_l1_norm": 59392.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.0400390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 50, + "denoise_stage": 3, + "denoise_idx": 2, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01275634765625, + "flowcache_rel_l1_ratio": 0.012845552884615384, + "flowcache_delta_l1_norm": 21888.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01275634765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 50, + "denoise_stage": 3, + "denoise_idx": 2, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.0048828125, + "flowcache_rel_l1_ratio": 0.004847935267857143, + "flowcache_delta_l1_norm": 8896.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0048828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 50, + "denoise_stage": 3, + "denoise_idx": 2, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 51, + "denoise_stage": 3, + "denoise_idx": 3, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.043701171875, + "flowcache_rel_l1_ratio": 0.04371488764044944, + "flowcache_delta_l1_norm": 63744.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.043701171875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 51, + "denoise_stage": 3, + "denoise_idx": 3, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012907608695652174, + "flowcache_delta_l1_norm": 21888.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.025634765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 51, + "denoise_stage": 3, + "denoise_idx": 3, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.0048828125, + "flowcache_rel_l1_ratio": 0.004869674887892377, + "flowcache_delta_l1_norm": 8896.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 51, + "denoise_stage": 3, + "denoise_idx": 3, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 52, + "denoise_stage": 3, + "denoise_idx": 4, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.047607421875, + "flowcache_rel_l1_ratio": 0.04766949152542373, + "flowcache_delta_l1_norm": 69120.0, + "flowcache_prev_feat_l1_norm": 1449984.0, + "flowcache_accumulated_rel_l1": 0.047607421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 52, + "denoise_stage": 3, + "denoise_idx": 4, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.0145263671875, + "flowcache_rel_l1_ratio": 0.014557926829268293, + "flowcache_delta_l1_norm": 24448.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.0145263671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 52, + "denoise_stage": 3, + "denoise_idx": 4, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004913330078125, + "flowcache_rel_l1_ratio": 0.004869674887892377, + "flowcache_delta_l1_norm": 8896.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.014678955078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 52, + "denoise_stage": 3, + "denoise_idx": 4, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 53, + "denoise_stage": 3, + "denoise_idx": 5, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05224609375, + "flowcache_rel_l1_ratio": 0.05178571428571429, + "flowcache_delta_l1_norm": 74240.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05224609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 53, + "denoise_stage": 3, + "denoise_idx": 5, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01470947265625, + "flowcache_rel_l1_ratio": 0.014629289215686275, + "flowcache_delta_l1_norm": 24448.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.02923583984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 53, + "denoise_stage": 3, + "denoise_idx": 5, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.004913330078125, + "flowcache_rel_l1_ratio": 0.004891610360360361, + "flowcache_delta_l1_norm": 8896.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.01959228515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 53, + "denoise_stage": 3, + "denoise_idx": 5, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.001251220703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 54, + "denoise_stage": 3, + "denoise_idx": 6, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.056396484375, + "flowcache_rel_l1_ratio": 0.056719653179190754, + "flowcache_delta_l1_norm": 80384.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.056396484375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 54, + "denoise_stage": 3, + "denoise_idx": 6, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0164794921875, + "flowcache_rel_l1_ratio": 0.01655321782178218, + "flowcache_delta_l1_norm": 27392.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0164794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 54, + "denoise_stage": 3, + "denoise_idx": 6, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.006195068359375, + "flowcache_rel_l1_ratio": 0.006221719457013574, + "flowcache_delta_l1_norm": 11264.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.006195068359375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 54, + "denoise_stage": 3, + "denoise_idx": 6, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00250244140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 55, + "denoise_stage": 3, + "denoise_idx": 7, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.061767578125, + "flowcache_rel_l1_ratio": 0.062136627906976744, + "flowcache_delta_l1_norm": 87552.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.061767578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 55, + "denoise_stage": 3, + "denoise_idx": 7, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.0177001953125, + "flowcache_rel_l1_ratio": 0.017646144278606966, + "flowcache_delta_l1_norm": 29056.0, + "flowcache_prev_feat_l1_norm": 1646592.0, + "flowcache_accumulated_rel_l1": 0.0177001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 55, + "denoise_stage": 3, + "denoise_idx": 7, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.0062255859375, + "flowcache_rel_l1_ratio": 0.00625, + "flowcache_delta_l1_norm": 11264.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.012420654296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 55, + "denoise_stage": 3, + "denoise_idx": 7, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.003753662109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 56, + "denoise_stage": 3, + "denoise_idx": 8, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06787109375, + "flowcache_rel_l1_ratio": 0.06798245614035088, + "flowcache_delta_l1_norm": 95232.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.06787109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 56, + "denoise_stage": 3, + "denoise_idx": 8, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.019001256281407034, + "flowcache_delta_l1_norm": 30976.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 56, + "denoise_stage": 3, + "denoise_idx": 8, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006256103515625, + "flowcache_rel_l1_ratio": 0.006278538812785388, + "flowcache_delta_l1_norm": 11264.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.0186767578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 56, + "denoise_stage": 3, + "denoise_idx": 8, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0050048828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 57, + "denoise_stage": 3, + "denoise_idx": 9, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.07421875, + "flowcache_rel_l1_ratio": 0.07463235294117647, + "flowcache_delta_l1_norm": 103936.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 57, + "denoise_stage": 3, + "denoise_idx": 9, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.02030456852791878, + "flowcache_delta_l1_norm": 32768.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 57, + "denoise_stage": 3, + "denoise_idx": 9, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.007415771484375, + "flowcache_rel_l1_ratio": 0.007420091324200913, + "flowcache_delta_l1_norm": 13312.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.007415771484375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 57, + "denoise_stage": 3, + "denoise_idx": 9, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.006256103515625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 58, + "denoise_stage": 3, + "denoise_idx": 10, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.08154296875, + "flowcache_rel_l1_ratio": 0.08161764705882353, + "flowcache_delta_l1_norm": 113664.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 58, + "denoise_stage": 3, + "denoise_idx": 10, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021794871794871794, + "flowcache_delta_l1_norm": 34816.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 58, + "denoise_stage": 3, + "denoise_idx": 10, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.0074462890625, + "flowcache_rel_l1_ratio": 0.007454128440366973, + "flowcache_delta_l1_norm": 13312.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.014862060546875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 58, + "denoise_stage": 3, + "denoise_idx": 10, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00751495361328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 59, + "denoise_stage": 3, + "denoise_idx": 11, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08935546875, + "flowcache_rel_l1_ratio": 0.08970588235294118, + "flowcache_delta_l1_norm": 124928.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08935546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 59, + "denoise_stage": 3, + "denoise_idx": 11, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.023356958762886598, + "flowcache_delta_l1_norm": 37120.0, + "flowcache_prev_feat_l1_norm": 1589248.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 59, + "denoise_stage": 3, + "denoise_idx": 11, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.007476806640625, + "flowcache_rel_l1_ratio": 0.007488479262672811, + "flowcache_delta_l1_norm": 13312.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.0223388671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 59, + "denoise_stage": 3, + "denoise_idx": 11, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0087738037109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 60, + "denoise_stage": 3, + "denoise_idx": 12, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.0966796875, + "flowcache_rel_l1_ratio": 0.09665697674418605, + "flowcache_delta_l1_norm": 136192.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.0966796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 60, + "denoise_stage": 3, + "denoise_idx": 12, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.025065104166666668, + "flowcache_delta_l1_norm": 39424.0, + "flowcache_prev_feat_l1_norm": 1572864.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 60, + "denoise_stage": 3, + "denoise_idx": 12, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.0089111328125, + "flowcache_rel_l1_ratio": 0.008897569444444444, + "flowcache_delta_l1_norm": 15744.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.0089111328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 60, + "denoise_stage": 3, + "denoise_idx": 12, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01003265380859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 61, + "denoise_stage": 3, + "denoise_idx": 13, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.1044921875, + "flowcache_rel_l1_ratio": 0.10428571428571429, + "flowcache_delta_l1_norm": 149504.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.1044921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 61, + "denoise_stage": 3, + "denoise_idx": 13, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.02680921052631579, + "flowcache_delta_l1_norm": 41728.0, + "flowcache_prev_feat_l1_norm": 1556480.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 61, + "denoise_stage": 3, + "denoise_idx": 13, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00897216796875, + "flowcache_rel_l1_ratio": 0.00898072429906542, + "flowcache_delta_l1_norm": 15744.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.01788330078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 61, + "denoise_stage": 3, + "denoise_idx": 13, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01129150390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 62, + "denoise_stage": 3, + "denoise_idx": 14, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.11181640625, + "flowcache_rel_l1_ratio": 0.1111111111111111, + "flowcache_delta_l1_norm": 163840.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.11181640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 62, + "denoise_stage": 3, + "denoise_idx": 14, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.029052734375, + "flowcache_rel_l1_ratio": 0.02908909574468085, + "flowcache_delta_l1_norm": 44800.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.029052734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 62, + "denoise_stage": 3, + "denoise_idx": 14, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.01007080078125, + "flowcache_rel_l1_ratio": 0.01004988262910798, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.01007080078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 62, + "denoise_stage": 3, + "denoise_idx": 14, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01255035400390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 63, + "denoise_stage": 3, + "denoise_idx": 15, + "chunk_idx": 0, + "generated_chunk_idx": 0, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.115234375, + "flowcache_rel_l1_ratio": 0.11564171122994653, + "flowcache_delta_l1_norm": 177152.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.115234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 63, + "denoise_stage": 3, + "denoise_idx": 15, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.031494140625, + "flowcache_rel_l1_ratio": 0.03141801075268817, + "flowcache_delta_l1_norm": 47872.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.031494140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 63, + "denoise_stage": 3, + "denoise_idx": 15, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.0101318359375, + "flowcache_rel_l1_ratio": 0.010097287735849057, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.02020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 63, + "denoise_stage": 3, + "denoise_idx": 15, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012642996651785715, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0138092041015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 64, + "denoise_stage": 4, + "denoise_idx": 0, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.03369140625, + "flowcache_rel_l1_ratio": 0.03379755434782609, + "flowcache_delta_l1_norm": 50944.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.03369140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 64, + "denoise_stage": 4, + "denoise_idx": 0, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01141357421875, + "flowcache_rel_l1_ratio": 0.011329976303317536, + "flowcache_delta_l1_norm": 19584.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.01141357421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 64, + "denoise_stage": 4, + "denoise_idx": 0, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012642996651785715, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01506805419921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 65, + "denoise_stage": 4, + "denoise_idx": 1, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.03662109375, + "flowcache_rel_l1_ratio": 0.036744505494505496, + "flowcache_delta_l1_norm": 54784.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.03662109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 65, + "denoise_stage": 4, + "denoise_idx": 1, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.011474609375, + "flowcache_rel_l1_ratio": 0.011438397129186604, + "flowcache_delta_l1_norm": 19584.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.02288818359375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 65, + "denoise_stage": 4, + "denoise_idx": 1, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00445556640625, + "flowcache_rel_l1_ratio": 0.004464285714285714, + "flowcache_delta_l1_norm": 8192.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.00445556640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 65, + "denoise_stage": 4, + "denoise_idx": 1, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 66, + "denoise_stage": 4, + "denoise_idx": 2, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039794921875, + "flowcache_rel_l1_ratio": 0.03975694444444444, + "flowcache_delta_l1_norm": 58624.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 66, + "denoise_stage": 4, + "denoise_idx": 2, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012845552884615384, + "flowcache_delta_l1_norm": 21888.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01287841796875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 66, + "denoise_stage": 4, + "denoise_idx": 2, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.00445556640625, + "flowcache_rel_l1_ratio": 0.004484304932735426, + "flowcache_delta_l1_norm": 8192.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.0089111328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 66, + "denoise_stage": 4, + "denoise_idx": 2, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 67, + "denoise_stage": 4, + "denoise_idx": 3, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.04296875, + "flowcache_rel_l1_ratio": 0.04312150837988827, + "flowcache_delta_l1_norm": 63232.0, + "flowcache_prev_feat_l1_norm": 1466368.0, + "flowcache_accumulated_rel_l1": 0.04296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 67, + "denoise_stage": 4, + "denoise_idx": 3, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.012939453125, + "flowcache_rel_l1_ratio": 0.012907608695652174, + "flowcache_delta_l1_norm": 21888.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.02581787109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 67, + "denoise_stage": 4, + "denoise_idx": 3, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004486083984375, + "flowcache_rel_l1_ratio": 0.004484304932735426, + "flowcache_delta_l1_norm": 8192.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.013397216796875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 67, + "denoise_stage": 4, + "denoise_idx": 3, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 68, + "denoise_stage": 4, + "denoise_idx": 4, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046875, + "flowcache_rel_l1_ratio": 0.04696327683615819, + "flowcache_delta_l1_norm": 68096.0, + "flowcache_prev_feat_l1_norm": 1449984.0, + "flowcache_accumulated_rel_l1": 0.046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 68, + "denoise_stage": 4, + "denoise_idx": 4, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.01458740234375, + "flowcache_rel_l1_ratio": 0.014634146341463415, + "flowcache_delta_l1_norm": 24576.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.01458740234375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 68, + "denoise_stage": 4, + "denoise_idx": 4, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004486083984375, + "flowcache_rel_l1_ratio": 0.0045045045045045045, + "flowcache_delta_l1_norm": 8192.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.01788330078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 68, + "denoise_stage": 4, + "denoise_idx": 4, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 69, + "denoise_stage": 4, + "denoise_idx": 5, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05126953125, + "flowcache_rel_l1_ratio": 0.05142857142857143, + "flowcache_delta_l1_norm": 73728.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05126953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 69, + "denoise_stage": 4, + "denoise_idx": 5, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01470947265625, + "flowcache_rel_l1_ratio": 0.014705882352941176, + "flowcache_delta_l1_norm": 24576.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.029296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 69, + "denoise_stage": 4, + "denoise_idx": 5, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.005767822265625, + "flowcache_rel_l1_ratio": 0.005736204954954955, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.005767822265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 69, + "denoise_stage": 4, + "denoise_idx": 5, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012185425884955752, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.001220703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 70, + "denoise_stage": 4, + "denoise_idx": 6, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.05615234375, + "flowcache_rel_l1_ratio": 0.05635838150289017, + "flowcache_delta_l1_norm": 79872.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.05615234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 70, + "denoise_stage": 4, + "denoise_idx": 6, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0166015625, + "flowcache_rel_l1_ratio": 0.016630569306930694, + "flowcache_delta_l1_norm": 27520.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0166015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 70, + "denoise_stage": 4, + "denoise_idx": 6, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.005762160633484163, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.011566162109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 70, + "denoise_stage": 4, + "denoise_idx": 6, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012185425884955752, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00244140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 71, + "denoise_stage": 4, + "denoise_idx": 7, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.061279296875, + "flowcache_rel_l1_ratio": 0.06140988372093023, + "flowcache_delta_l1_norm": 86528.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.061279296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 71, + "denoise_stage": 4, + "denoise_idx": 7, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.0177001953125, + "flowcache_rel_l1_ratio": 0.017734375, + "flowcache_delta_l1_norm": 29056.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.0177001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 71, + "denoise_stage": 4, + "denoise_idx": 7, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.005788352272727273, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.017364501953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 71, + "denoise_stage": 4, + "denoise_idx": 7, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012185425884955752, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.003662109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 72, + "denoise_stage": 4, + "denoise_idx": 8, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06689453125, + "flowcache_rel_l1_ratio": 0.0668859649122807, + "flowcache_delta_l1_norm": 93696.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.06689453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 72, + "denoise_stage": 4, + "denoise_idx": 8, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.019001256281407034, + "flowcache_delta_l1_norm": 30976.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 72, + "denoise_stage": 4, + "denoise_idx": 8, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.00689697265625, + "flowcache_rel_l1_ratio": 0.006920662100456621, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00689697265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 72, + "denoise_stage": 4, + "denoise_idx": 8, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012185425884955752, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0048828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 73, + "denoise_stage": 4, + "denoise_idx": 9, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.07373046875, + "flowcache_rel_l1_ratio": 0.07352941176470588, + "flowcache_delta_l1_norm": 102400.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07373046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 73, + "denoise_stage": 4, + "denoise_idx": 9, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.02030456852791878, + "flowcache_delta_l1_norm": 32768.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 73, + "denoise_stage": 4, + "denoise_idx": 9, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.006927490234375, + "flowcache_rel_l1_ratio": 0.006952408256880734, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.013824462890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 73, + "denoise_stage": 4, + "denoise_idx": 9, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.006103515625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 74, + "denoise_stage": 4, + "denoise_idx": 10, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.080078125, + "flowcache_rel_l1_ratio": 0.08014705882352942, + "flowcache_delta_l1_norm": 111616.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.080078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 74, + "denoise_stage": 4, + "denoise_idx": 10, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.0218505859375, + "flowcache_rel_l1_ratio": 0.021794871794871794, + "flowcache_delta_l1_norm": 34816.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.0218505859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 74, + "denoise_stage": 4, + "denoise_idx": 10, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.0069580078125, + "flowcache_rel_l1_ratio": 0.006984447004608295, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.020782470703125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 74, + "denoise_stage": 4, + "denoise_idx": 10, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00732421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 75, + "denoise_stage": 4, + "denoise_idx": 11, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.087890625, + "flowcache_rel_l1_ratio": 0.08786764705882352, + "flowcache_delta_l1_norm": 122368.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.087890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 75, + "denoise_stage": 4, + "denoise_idx": 11, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.0234779792746114, + "flowcache_delta_l1_norm": 37120.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 75, + "denoise_stage": 4, + "denoise_idx": 11, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.00836181640625, + "flowcache_rel_l1_ratio": 0.008318865740740741, + "flowcache_delta_l1_norm": 14720.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.00836181640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 75, + "denoise_stage": 4, + "denoise_idx": 11, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.008544921875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 76, + "denoise_stage": 4, + "denoise_idx": 12, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.095703125, + "flowcache_rel_l1_ratio": 0.09576023391812866, + "flowcache_delta_l1_norm": 134144.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.095703125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 76, + "denoise_stage": 4, + "denoise_idx": 12, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0252685546875, + "flowcache_rel_l1_ratio": 0.025065104166666668, + "flowcache_delta_l1_norm": 39424.0, + "flowcache_prev_feat_l1_norm": 1572864.0, + "flowcache_accumulated_rel_l1": 0.0252685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 76, + "denoise_stage": 4, + "denoise_idx": 12, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.00836181640625, + "flowcache_rel_l1_ratio": 0.008357558139534883, + "flowcache_delta_l1_norm": 14720.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.0167236328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 76, + "denoise_stage": 4, + "denoise_idx": 12, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012152777777777778, + "flowcache_delta_l1_norm": 2240.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 77, + "denoise_stage": 4, + "denoise_idx": 13, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.1025390625, + "flowcache_rel_l1_ratio": 0.10344827586206896, + "flowcache_delta_l1_norm": 147456.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.1025390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 77, + "denoise_stage": 4, + "denoise_idx": 13, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.0269775390625, + "flowcache_rel_l1_ratio": 0.026973684210526316, + "flowcache_delta_l1_norm": 41984.0, + "flowcache_prev_feat_l1_norm": 1556480.0, + "flowcache_accumulated_rel_l1": 0.0269775390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 77, + "denoise_stage": 4, + "denoise_idx": 13, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.0093994140625, + "flowcache_rel_l1_ratio": 0.009418808411214953, + "flowcache_delta_l1_norm": 16512.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.0093994140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 77, + "denoise_stage": 4, + "denoise_idx": 13, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.010986328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 78, + "denoise_stage": 4, + "denoise_idx": 14, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.109375, + "flowcache_rel_l1_ratio": 0.10893854748603352, + "flowcache_delta_l1_norm": 159744.0, + "flowcache_prev_feat_l1_norm": 1466368.0, + "flowcache_accumulated_rel_l1": 0.109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 78, + "denoise_stage": 4, + "denoise_idx": 14, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.029052734375, + "flowcache_rel_l1_ratio": 0.02908909574468085, + "flowcache_delta_l1_norm": 44800.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.029052734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 78, + "denoise_stage": 4, + "denoise_idx": 14, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00946044921875, + "flowcache_rel_l1_ratio": 0.009463028169014084, + "flowcache_delta_l1_norm": 16512.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.01885986328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 78, + "denoise_stage": 4, + "denoise_idx": 14, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012239583333333334, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01220703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 79, + "denoise_stage": 4, + "denoise_idx": 15, + "chunk_idx": 1, + "generated_chunk_idx": 1, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.11328125, + "flowcache_rel_l1_ratio": 0.11296791443850267, + "flowcache_delta_l1_norm": 173056.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.11328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 79, + "denoise_stage": 4, + "denoise_idx": 15, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.031494140625, + "flowcache_rel_l1_ratio": 0.03141801075268817, + "flowcache_delta_l1_norm": 47872.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.031494140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 79, + "denoise_stage": 4, + "denoise_idx": 15, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.0106201171875, + "flowcache_rel_l1_ratio": 0.01061320754716981, + "flowcache_delta_l1_norm": 18432.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.0106201171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 79, + "denoise_stage": 4, + "denoise_idx": 15, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.001220703125, + "flowcache_delta_l1_norm": 2240.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.013427734375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 80, + "denoise_stage": 5, + "denoise_idx": 0, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.033935546875, + "flowcache_rel_l1_ratio": 0.03379755434782609, + "flowcache_delta_l1_norm": 50944.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.033935546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 80, + "denoise_stage": 5, + "denoise_idx": 0, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01068115234375, + "flowcache_rel_l1_ratio": 0.010714285714285714, + "flowcache_delta_l1_norm": 18432.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.02130126953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 80, + "denoise_stage": 5, + "denoise_idx": 0, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.001220703125, + "flowcache_rel_l1_ratio": 0.0012294224330357143, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0146484375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 81, + "denoise_stage": 5, + "denoise_idx": 1, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.03662109375, + "flowcache_rel_l1_ratio": 0.036744505494505496, + "flowcache_delta_l1_norm": 54784.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.03662109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 81, + "denoise_stage": 5, + "denoise_idx": 1, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.011962890625, + "flowcache_rel_l1_ratio": 0.012036483253588517, + "flowcache_delta_l1_norm": 20608.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.011962890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 81, + "denoise_stage": 5, + "denoise_idx": 1, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012294224330357143, + "flowcache_delta_l1_norm": 2256.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01587677001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 81, + "denoise_stage": 5, + "denoise_idx": 1, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 82, + "denoise_stage": 5, + "denoise_idx": 2, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039794921875, + "flowcache_rel_l1_ratio": 0.03975694444444444, + "flowcache_delta_l1_norm": 58624.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 82, + "denoise_stage": 5, + "denoise_idx": 2, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01202392578125, + "flowcache_rel_l1_ratio": 0.012094350961538462, + "flowcache_delta_l1_norm": 20608.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.02398681640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 82, + "denoise_stage": 5, + "denoise_idx": 2, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004778180803571429, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.004791259765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 82, + "denoise_stage": 5, + "denoise_idx": 2, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 83, + "denoise_stage": 5, + "denoise_idx": 3, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.04345703125, + "flowcache_rel_l1_ratio": 0.04318820224719101, + "flowcache_delta_l1_norm": 62976.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.04345703125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 83, + "denoise_stage": 5, + "denoise_idx": 3, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.013671875, + "flowcache_rel_l1_ratio": 0.013652912621359222, + "flowcache_delta_l1_norm": 23040.0, + "flowcache_prev_feat_l1_norm": 1687552.0, + "flowcache_accumulated_rel_l1": 0.013671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 83, + "denoise_stage": 5, + "denoise_idx": 3, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004799607623318386, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.00958251953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 83, + "denoise_stage": 5, + "denoise_idx": 3, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 84, + "denoise_stage": 5, + "denoise_idx": 4, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046875, + "flowcache_rel_l1_ratio": 0.04696327683615819, + "flowcache_delta_l1_norm": 68096.0, + "flowcache_prev_feat_l1_norm": 1449984.0, + "flowcache_accumulated_rel_l1": 0.046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 84, + "denoise_stage": 5, + "denoise_idx": 4, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.01373291015625, + "flowcache_rel_l1_ratio": 0.013719512195121951, + "flowcache_delta_l1_norm": 23040.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.02740478515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 84, + "denoise_stage": 5, + "denoise_idx": 4, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.00482177734375, + "flowcache_rel_l1_ratio": 0.004821227477477478, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.014404296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 84, + "denoise_stage": 5, + "denoise_idx": 4, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 85, + "denoise_stage": 5, + "denoise_idx": 5, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05126953125, + "flowcache_rel_l1_ratio": 0.05107142857142857, + "flowcache_delta_l1_norm": 73216.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05126953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 85, + "denoise_stage": 5, + "denoise_idx": 5, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01544189453125, + "flowcache_rel_l1_ratio": 0.015548029556650246, + "flowcache_delta_l1_norm": 25856.0, + "flowcache_prev_feat_l1_norm": 1662976.0, + "flowcache_accumulated_rel_l1": 0.01544189453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 85, + "denoise_stage": 5, + "denoise_idx": 5, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.004852294921875, + "flowcache_rel_l1_ratio": 0.004821227477477478, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.019256591796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 85, + "denoise_stage": 5, + "denoise_idx": 5, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00124359130859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 86, + "denoise_stage": 5, + "denoise_idx": 6, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.0556640625, + "flowcache_rel_l1_ratio": 0.0559971098265896, + "flowcache_delta_l1_norm": 79360.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.0556640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 86, + "denoise_stage": 5, + "denoise_idx": 6, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0166015625, + "flowcache_rel_l1_ratio": 0.016475866336633664, + "flowcache_delta_l1_norm": 27264.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0166015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 86, + "denoise_stage": 5, + "denoise_idx": 6, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.006134033203125, + "flowcache_rel_l1_ratio": 0.006151018099547511, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.006134033203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 86, + "denoise_stage": 5, + "denoise_idx": 6, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0024871826171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 87, + "denoise_stage": 5, + "denoise_idx": 7, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.061279296875, + "flowcache_rel_l1_ratio": 0.061046511627906974, + "flowcache_delta_l1_norm": 86016.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.061279296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 87, + "denoise_stage": 5, + "denoise_idx": 7, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.01765625, + "flowcache_delta_l1_norm": 28928.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 87, + "denoise_stage": 5, + "denoise_idx": 7, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.00616455078125, + "flowcache_rel_l1_ratio": 0.006178977272727273, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.012298583984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 87, + "denoise_stage": 5, + "denoise_idx": 7, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00373077392578125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 88, + "denoise_stage": 5, + "denoise_idx": 8, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06689453125, + "flowcache_rel_l1_ratio": 0.06652046783625731, + "flowcache_delta_l1_norm": 93184.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.06689453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 88, + "denoise_stage": 5, + "denoise_idx": 8, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.01893939393939394, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1622016.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 88, + "denoise_stage": 5, + "denoise_idx": 8, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006195068359375, + "flowcache_rel_l1_ratio": 0.0062071917808219175, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.01849365234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 88, + "denoise_stage": 5, + "denoise_idx": 8, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.004974365234375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 89, + "denoise_stage": 5, + "denoise_idx": 9, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.0732421875, + "flowcache_rel_l1_ratio": 0.07316176470588236, + "flowcache_delta_l1_norm": 101888.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0732421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 89, + "denoise_stage": 5, + "denoise_idx": 9, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.020145939086294418, + "flowcache_delta_l1_norm": 32512.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 89, + "denoise_stage": 5, + "denoise_idx": 9, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.0073487442922374425, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00738525390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 89, + "denoise_stage": 5, + "denoise_idx": 9, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00621795654296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 90, + "denoise_stage": 5, + "denoise_idx": 10, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.07958984375, + "flowcache_rel_l1_ratio": 0.07977941176470588, + "flowcache_delta_l1_norm": 111104.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07958984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 90, + "denoise_stage": 5, + "denoise_idx": 10, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 90, + "denoise_stage": 5, + "denoise_idx": 10, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.007382454128440367, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.0147705078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 90, + "denoise_stage": 5, + "denoise_idx": 10, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0074615478515625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 91, + "denoise_stage": 5, + "denoise_idx": 11, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08740234375, + "flowcache_rel_l1_ratio": 0.0875, + "flowcache_delta_l1_norm": 121856.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08740234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 91, + "denoise_stage": 5, + "denoise_idx": 11, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 91, + "denoise_stage": 5, + "denoise_idx": 11, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.007415771484375, + "flowcache_rel_l1_ratio": 0.007450810185185185, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.022186279296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 91, + "denoise_stage": 5, + "denoise_idx": 11, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00870513916015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 92, + "denoise_stage": 5, + "denoise_idx": 12, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.0947265625, + "flowcache_rel_l1_ratio": 0.09447674418604651, + "flowcache_delta_l1_norm": 133120.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.0947265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 92, + "denoise_stage": 5, + "denoise_idx": 12, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.025032722513089006, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 92, + "denoise_stage": 5, + "denoise_idx": 12, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.0087890625, + "flowcache_rel_l1_ratio": 0.008829941860465117, + "flowcache_delta_l1_norm": 15552.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.0087890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 92, + "denoise_stage": 5, + "denoise_idx": 12, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 93, + "denoise_stage": 5, + "denoise_idx": 13, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.10205078125, + "flowcache_rel_l1_ratio": 0.10201149425287356, + "flowcache_delta_l1_norm": 145408.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.10205078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 93, + "denoise_stage": 5, + "denoise_idx": 13, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.0269510582010582, + "flowcache_delta_l1_norm": 41728.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 93, + "denoise_stage": 5, + "denoise_idx": 13, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008871203271028038, + "flowcache_delta_l1_norm": 15552.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.01763916015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 93, + "denoise_stage": 5, + "denoise_idx": 13, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01119232177734375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 94, + "denoise_stage": 5, + "denoise_idx": 14, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.10791015625, + "flowcache_rel_l1_ratio": 0.10824022346368715, + "flowcache_delta_l1_norm": 158720.0, + "flowcache_prev_feat_l1_norm": 1466368.0, + "flowcache_accumulated_rel_l1": 0.10791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 94, + "denoise_stage": 5, + "denoise_idx": 14, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.029052734375, + "flowcache_rel_l1_ratio": 0.029077540106951873, + "flowcache_delta_l1_norm": 44544.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.029052734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 94, + "denoise_stage": 5, + "denoise_idx": 14, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00994873046875, + "flowcache_rel_l1_ratio": 0.009976525821596244, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 94, + "denoise_stage": 5, + "denoise_idx": 14, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0124359130859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 95, + "denoise_stage": 5, + "denoise_idx": 15, + "chunk_idx": 2, + "generated_chunk_idx": 2, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.11181640625, + "flowcache_rel_l1_ratio": 0.11163101604278075, + "flowcache_delta_l1_norm": 171008.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.11181640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 95, + "denoise_stage": 5, + "denoise_idx": 15, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.03125, + "flowcache_rel_l1_ratio": 0.03125, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1515520.0, + "flowcache_accumulated_rel_l1": 0.03125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 95, + "denoise_stage": 5, + "denoise_idx": 15, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010023584905660377, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.01995849609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 95, + "denoise_stage": 5, + "denoise_idx": 15, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01367950439453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 96, + "denoise_stage": 6, + "denoise_idx": 0, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.03369140625, + "flowcache_rel_l1_ratio": 0.033627717391304345, + "flowcache_delta_l1_norm": 50688.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.03369140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 96, + "denoise_stage": 6, + "denoise_idx": 0, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01123046875, + "flowcache_rel_l1_ratio": 0.011255924170616114, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.01123046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 96, + "denoise_stage": 6, + "denoise_idx": 0, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012555803571428572, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.014923095703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 97, + "denoise_stage": 6, + "denoise_idx": 1, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.03662109375, + "flowcache_rel_l1_ratio": 0.036401098901098904, + "flowcache_delta_l1_norm": 54272.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.03662109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 97, + "denoise_stage": 6, + "denoise_idx": 1, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011363636363636364, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.02252197265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 97, + "denoise_stage": 6, + "denoise_idx": 1, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012555803571428572, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01616668701171875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 97, + "denoise_stage": 6, + "denoise_idx": 1, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 98, + "denoise_stage": 6, + "denoise_idx": 2, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.03955078125, + "flowcache_rel_l1_ratio": 0.03958333333333333, + "flowcache_delta_l1_norm": 58368.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.03955078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 98, + "denoise_stage": 6, + "denoise_idx": 2, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01275634765625, + "flowcache_rel_l1_ratio": 0.012770432692307692, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01275634765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 98, + "denoise_stage": 6, + "denoise_idx": 2, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.0048828125, + "flowcache_rel_l1_ratio": 0.0048828125, + "flowcache_delta_l1_norm": 8960.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0048828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 98, + "denoise_stage": 6, + "denoise_idx": 2, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 99, + "denoise_stage": 6, + "denoise_idx": 3, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.04296875, + "flowcache_rel_l1_ratio": 0.0430126404494382, + "flowcache_delta_l1_norm": 62720.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.04296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 99, + "denoise_stage": 6, + "denoise_idx": 3, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012832125603864734, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.025634765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 99, + "denoise_stage": 6, + "denoise_idx": 3, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.0048828125, + "flowcache_rel_l1_ratio": 0.0049047085201793725, + "flowcache_delta_l1_norm": 8960.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 99, + "denoise_stage": 6, + "denoise_idx": 3, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 100, + "denoise_stage": 6, + "denoise_idx": 4, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046875, + "flowcache_rel_l1_ratio": 0.046875, + "flowcache_delta_l1_norm": 67584.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 100, + "denoise_stage": 6, + "denoise_idx": 4, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.0145263671875, + "flowcache_rel_l1_ratio": 0.014481707317073171, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.0145263671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 100, + "denoise_stage": 6, + "denoise_idx": 4, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004913330078125, + "flowcache_rel_l1_ratio": 0.0049047085201793725, + "flowcache_delta_l1_norm": 8960.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.014678955078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 100, + "denoise_stage": 6, + "denoise_idx": 4, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 101, + "denoise_stage": 6, + "denoise_idx": 5, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.051025390625, + "flowcache_rel_l1_ratio": 0.05100574712643678, + "flowcache_delta_l1_norm": 72704.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.051025390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 101, + "denoise_stage": 6, + "denoise_idx": 5, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01458740234375, + "flowcache_rel_l1_ratio": 0.014552696078431373, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.02911376953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 101, + "denoise_stage": 6, + "denoise_idx": 5, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.004913330078125, + "flowcache_rel_l1_ratio": 0.004926801801801802, + "flowcache_delta_l1_norm": 8960.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.01959228515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 101, + "denoise_stage": 6, + "denoise_idx": 5, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.001251220703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 102, + "denoise_stage": 6, + "denoise_idx": 6, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.05615234375, + "flowcache_rel_l1_ratio": 0.05563583815028902, + "flowcache_delta_l1_norm": 78848.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.05615234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 102, + "denoise_stage": 6, + "denoise_idx": 6, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.016357421875, + "flowcache_rel_l1_ratio": 0.016475866336633664, + "flowcache_delta_l1_norm": 27264.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.016357421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 102, + "denoise_stage": 6, + "denoise_idx": 6, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.00616455078125, + "flowcache_rel_l1_ratio": 0.006186368778280543, + "flowcache_delta_l1_norm": 11200.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.00616455078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 102, + "denoise_stage": 6, + "denoise_idx": 6, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00251007080078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 103, + "denoise_stage": 6, + "denoise_idx": 7, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.060791015625, + "flowcache_rel_l1_ratio": 0.06103801169590643, + "flowcache_delta_l1_norm": 85504.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.060791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 103, + "denoise_stage": 6, + "denoise_idx": 7, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.01765625, + "flowcache_delta_l1_norm": 28928.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 103, + "denoise_stage": 6, + "denoise_idx": 7, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.006195068359375, + "flowcache_rel_l1_ratio": 0.006214488636363636, + "flowcache_delta_l1_norm": 11200.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.012359619140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 103, + "denoise_stage": 6, + "denoise_idx": 7, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0037689208984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 104, + "denoise_stage": 6, + "denoise_idx": 8, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06640625, + "flowcache_rel_l1_ratio": 0.06654411764705882, + "flowcache_delta_l1_norm": 92672.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.06640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 104, + "denoise_stage": 6, + "denoise_idx": 8, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.018798828125, + "flowcache_rel_l1_ratio": 0.018844221105527637, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.018798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 104, + "denoise_stage": 6, + "denoise_idx": 8, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.0062255859375, + "flowcache_rel_l1_ratio": 0.006214488636363636, + "flowcache_delta_l1_norm": 11200.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.018585205078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 104, + "denoise_stage": 6, + "denoise_idx": 8, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00502777099609375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 105, + "denoise_stage": 6, + "denoise_idx": 9, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.0732421875, + "flowcache_rel_l1_ratio": 0.0724264705882353, + "flowcache_delta_l1_norm": 100864.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0732421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 105, + "denoise_stage": 6, + "denoise_idx": 9, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.0201416015625, + "flowcache_rel_l1_ratio": 0.020145939086294418, + "flowcache_delta_l1_norm": 32512.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.0201416015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 105, + "denoise_stage": 6, + "denoise_idx": 9, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.007384417808219178, + "flowcache_delta_l1_norm": 13248.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00738525390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 105, + "denoise_stage": 6, + "denoise_idx": 9, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00628662109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 106, + "denoise_stage": 6, + "denoise_idx": 10, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.07958984375, + "flowcache_rel_l1_ratio": 0.07988165680473373, + "flowcache_delta_l1_norm": 110592.0, + "flowcache_prev_feat_l1_norm": 1384448.0, + "flowcache_accumulated_rel_l1": 0.07958984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 106, + "denoise_stage": 6, + "denoise_idx": 10, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 106, + "denoise_stage": 6, + "denoise_idx": 10, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.0074462890625, + "flowcache_rel_l1_ratio": 0.007454128440366973, + "flowcache_delta_l1_norm": 13312.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.01483154296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 106, + "denoise_stage": 6, + "denoise_idx": 10, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012531111725663717, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00754547119140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 107, + "denoise_stage": 6, + "denoise_idx": 11, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08642578125, + "flowcache_rel_l1_ratio": 0.08676470588235294, + "flowcache_delta_l1_norm": 120832.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08642578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 107, + "denoise_stage": 6, + "denoise_idx": 11, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.023193359375, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.023193359375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 107, + "denoise_stage": 6, + "denoise_idx": 11, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.0074462890625, + "flowcache_rel_l1_ratio": 0.0074524769585253454, + "flowcache_delta_l1_norm": 13248.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.02227783203125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 107, + "denoise_stage": 6, + "denoise_idx": 11, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0088043212890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 108, + "denoise_stage": 6, + "denoise_idx": 12, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.09423828125, + "flowcache_rel_l1_ratio": 0.09429824561403509, + "flowcache_delta_l1_norm": 132096.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.09423828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 108, + "denoise_stage": 6, + "denoise_idx": 12, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.02490234375, + "flowcache_rel_l1_ratio": 0.025032722513089006, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.02490234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 108, + "denoise_stage": 6, + "denoise_idx": 12, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008861400462962963, + "flowcache_delta_l1_norm": 15680.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.00885009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 108, + "denoise_stage": 6, + "denoise_idx": 12, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01006317138671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 109, + "denoise_stage": 6, + "denoise_idx": 13, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.1015625, + "flowcache_rel_l1_ratio": 0.10129310344827586, + "flowcache_delta_l1_norm": 144384.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.1015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 109, + "denoise_stage": 6, + "denoise_idx": 13, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.026644736842105263, + "flowcache_delta_l1_norm": 41472.0, + "flowcache_prev_feat_l1_norm": 1556480.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 109, + "denoise_stage": 6, + "denoise_idx": 13, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.0089111328125, + "flowcache_rel_l1_ratio": 0.008902616279069768, + "flowcache_delta_l1_norm": 15680.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.01776123046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 109, + "denoise_stage": 6, + "denoise_idx": 13, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.0012664794921875, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01132965087890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 110, + "denoise_stage": 6, + "denoise_idx": 14, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.10693359375, + "flowcache_rel_l1_ratio": 0.10754189944134078, + "flowcache_delta_l1_norm": 157696.0, + "flowcache_prev_feat_l1_norm": 1466368.0, + "flowcache_accumulated_rel_l1": 0.10693359375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 110, + "denoise_stage": 6, + "denoise_idx": 14, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.02880859375, + "flowcache_rel_l1_ratio": 0.02892287234042553, + "flowcache_delta_l1_norm": 44544.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.02880859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 110, + "denoise_stage": 6, + "denoise_idx": 14, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.01004988262910798, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.010009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 110, + "denoise_stage": 6, + "denoise_idx": 14, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.0012664794921875, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01259613037109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 111, + "denoise_stage": 6, + "denoise_idx": 15, + "chunk_idx": 3, + "generated_chunk_idx": 3, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.11083984375, + "flowcache_rel_l1_ratio": 0.11096256684491979, + "flowcache_delta_l1_norm": 169984.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.11083984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 111, + "denoise_stage": 6, + "denoise_idx": 15, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.031005859375, + "flowcache_rel_l1_ratio": 0.031081989247311828, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.031005859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 111, + "denoise_stage": 6, + "denoise_idx": 15, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010097287735849057, + "flowcache_delta_l1_norm": 17536.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.02001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 111, + "denoise_stage": 6, + "denoise_idx": 15, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.0012664794921875, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01386260986328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 112, + "denoise_stage": 7, + "denoise_idx": 0, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.03369140625, + "flowcache_rel_l1_ratio": 0.03345788043478261, + "flowcache_delta_l1_norm": 50432.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.03369140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 112, + "denoise_stage": 7, + "denoise_idx": 0, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011255924170616114, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.01129150390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 112, + "denoise_stage": 7, + "denoise_idx": 0, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.0012664794921875, + "flowcache_rel_l1_ratio": 0.0012586805555555556, + "flowcache_delta_l1_norm": 2320.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01512908935546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 113, + "denoise_stage": 7, + "denoise_idx": 1, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.0361328125, + "flowcache_rel_l1_ratio": 0.03622939560439561, + "flowcache_delta_l1_norm": 54016.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.0361328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 113, + "denoise_stage": 7, + "denoise_idx": 1, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01141357421875, + "flowcache_rel_l1_ratio": 0.011363636363636364, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.022705078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 113, + "denoise_stage": 7, + "denoise_idx": 1, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.0045166015625, + "flowcache_rel_l1_ratio": 0.004534040178571429, + "flowcache_delta_l1_norm": 8320.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0045166015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 113, + "denoise_stage": 7, + "denoise_idx": 1, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 114, + "denoise_stage": 7, + "denoise_idx": 2, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.03940972222222222, + "flowcache_delta_l1_norm": 58112.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 114, + "denoise_stage": 7, + "denoise_idx": 2, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01275634765625, + "flowcache_rel_l1_ratio": 0.012770432692307692, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01275634765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 114, + "denoise_stage": 7, + "denoise_idx": 2, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.004547119140625, + "flowcache_rel_l1_ratio": 0.004534040178571429, + "flowcache_delta_l1_norm": 8320.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.009063720703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 114, + "denoise_stage": 7, + "denoise_idx": 2, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 115, + "denoise_stage": 7, + "denoise_idx": 3, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.042724609375, + "flowcache_rel_l1_ratio": 0.042837078651685394, + "flowcache_delta_l1_norm": 62464.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.042724609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 115, + "denoise_stage": 7, + "denoise_idx": 3, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012832125603864734, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.025634765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 115, + "denoise_stage": 7, + "denoise_idx": 3, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004547119140625, + "flowcache_rel_l1_ratio": 0.004554372197309417, + "flowcache_delta_l1_norm": 8320.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.01361083984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 115, + "denoise_stage": 7, + "denoise_idx": 3, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 116, + "denoise_stage": 7, + "denoise_idx": 4, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.04638671875, + "flowcache_rel_l1_ratio": 0.04651988636363636, + "flowcache_delta_l1_norm": 67072.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.04638671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 116, + "denoise_stage": 7, + "denoise_idx": 4, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.01458740234375, + "flowcache_rel_l1_ratio": 0.014557926829268293, + "flowcache_delta_l1_norm": 24448.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.01458740234375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 116, + "denoise_stage": 7, + "denoise_idx": 4, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.00457763671875, + "flowcache_rel_l1_ratio": 0.004554372197309417, + "flowcache_delta_l1_norm": 8320.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.0181884765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 116, + "denoise_stage": 7, + "denoise_idx": 4, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 117, + "denoise_stage": 7, + "denoise_idx": 5, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05078125, + "flowcache_rel_l1_ratio": 0.05071428571428571, + "flowcache_delta_l1_norm": 72704.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 117, + "denoise_stage": 7, + "denoise_idx": 5, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01470947265625, + "flowcache_rel_l1_ratio": 0.014629289215686275, + "flowcache_delta_l1_norm": 24448.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.029296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 117, + "denoise_stage": 7, + "denoise_idx": 5, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.0058065878378378375, + "flowcache_delta_l1_norm": 10560.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.00579833984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 117, + "denoise_stage": 7, + "denoise_idx": 5, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.001251220703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 118, + "denoise_stage": 7, + "denoise_idx": 6, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.05517578125, + "flowcache_rel_l1_ratio": 0.055274566473988436, + "flowcache_delta_l1_norm": 78336.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.05517578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 118, + "denoise_stage": 7, + "denoise_idx": 6, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0164794921875, + "flowcache_rel_l1_ratio": 0.01655321782178218, + "flowcache_delta_l1_norm": 27392.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0164794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 118, + "denoise_stage": 7, + "denoise_idx": 6, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.005832861990950226, + "flowcache_delta_l1_norm": 10560.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.0115966796875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 118, + "denoise_stage": 7, + "denoise_idx": 6, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00250244140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 119, + "denoise_stage": 7, + "denoise_idx": 7, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.060546875, + "flowcache_rel_l1_ratio": 0.06031976744186047, + "flowcache_delta_l1_norm": 84992.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.060546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 119, + "denoise_stage": 7, + "denoise_idx": 7, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.01765625, + "flowcache_delta_l1_norm": 28928.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 119, + "denoise_stage": 7, + "denoise_idx": 7, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.005828857421875, + "flowcache_rel_l1_ratio": 0.005859375, + "flowcache_delta_l1_norm": 10560.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.017425537109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 119, + "denoise_stage": 7, + "denoise_idx": 7, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012444690265486725, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.003753662109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 120, + "denoise_stage": 7, + "denoise_idx": 8, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06640625, + "flowcache_rel_l1_ratio": 0.0661764705882353, + "flowcache_delta_l1_norm": 92160.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.06640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 120, + "denoise_stage": 7, + "denoise_idx": 8, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.018798828125, + "flowcache_rel_l1_ratio": 0.018844221105527637, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.018798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 120, + "denoise_stage": 7, + "denoise_idx": 8, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006927490234375, + "flowcache_rel_l1_ratio": 0.006956335616438356, + "flowcache_delta_l1_norm": 12480.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.006927490234375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 120, + "denoise_stage": 7, + "denoise_idx": 8, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0050048828125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 121, + "denoise_stage": 7, + "denoise_idx": 9, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.072265625, + "flowcache_rel_l1_ratio": 0.07205882352941176, + "flowcache_delta_l1_norm": 100352.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.072265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 121, + "denoise_stage": 7, + "denoise_idx": 9, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.0202252538071066, + "flowcache_delta_l1_norm": 32640.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 121, + "denoise_stage": 7, + "denoise_idx": 9, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.006988525390625, + "flowcache_rel_l1_ratio": 0.0069882454128440364, + "flowcache_delta_l1_norm": 12480.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.013916015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 121, + "denoise_stage": 7, + "denoise_idx": 9, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.006256103515625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 122, + "denoise_stage": 7, + "denoise_idx": 10, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.0791015625, + "flowcache_rel_l1_ratio": 0.07914201183431953, + "flowcache_delta_l1_norm": 109568.0, + "flowcache_prev_feat_l1_norm": 1384448.0, + "flowcache_accumulated_rel_l1": 0.0791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 122, + "denoise_stage": 7, + "denoise_idx": 10, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 122, + "denoise_stage": 7, + "denoise_idx": 10, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.006988525390625, + "flowcache_rel_l1_ratio": 0.00702044930875576, + "flowcache_delta_l1_norm": 12480.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.020904541015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 122, + "denoise_stage": 7, + "denoise_idx": 10, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00751495361328125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 123, + "denoise_stage": 7, + "denoise_idx": 11, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08642578125, + "flowcache_rel_l1_ratio": 0.08602941176470588, + "flowcache_delta_l1_norm": 119808.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08642578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 123, + "denoise_stage": 7, + "denoise_idx": 11, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 123, + "denoise_stage": 7, + "denoise_idx": 11, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.00830078125, + "flowcache_rel_l1_ratio": 0.008316532258064516, + "flowcache_delta_l1_norm": 14784.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.00830078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 123, + "denoise_stage": 7, + "denoise_idx": 11, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0087738037109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 124, + "denoise_stage": 7, + "denoise_idx": 12, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.09326171875, + "flowcache_rel_l1_ratio": 0.0935672514619883, + "flowcache_delta_l1_norm": 131072.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.09326171875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 124, + "denoise_stage": 7, + "denoise_idx": 12, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.025032722513089006, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 124, + "denoise_stage": 7, + "denoise_idx": 12, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.00836181640625, + "flowcache_rel_l1_ratio": 0.00839389534883721, + "flowcache_delta_l1_norm": 14784.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.01666259765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 124, + "denoise_stage": 7, + "denoise_idx": 12, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01001739501953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 125, + "denoise_stage": 7, + "denoise_idx": 13, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.1005859375, + "flowcache_rel_l1_ratio": 0.10057471264367816, + "flowcache_delta_l1_norm": 143360.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.1005859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 125, + "denoise_stage": 7, + "denoise_idx": 13, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.02680921052631579, + "flowcache_delta_l1_norm": 41728.0, + "flowcache_prev_feat_l1_norm": 1556480.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 125, + "denoise_stage": 7, + "denoise_idx": 13, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00933837890625, + "flowcache_rel_l1_ratio": 0.009345794392523364, + "flowcache_delta_l1_norm": 16384.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.00933837890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 125, + "denoise_stage": 7, + "denoise_idx": 13, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.00125, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0112762451171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 126, + "denoise_stage": 7, + "denoise_idx": 14, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.1064453125, + "flowcache_rel_l1_ratio": 0.10614525139664804, + "flowcache_delta_l1_norm": 155648.0, + "flowcache_prev_feat_l1_norm": 1466368.0, + "flowcache_accumulated_rel_l1": 0.1064453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 126, + "denoise_stage": 7, + "denoise_idx": 14, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.02880859375, + "flowcache_rel_l1_ratio": 0.02892287234042553, + "flowcache_delta_l1_norm": 44544.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.02880859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 126, + "denoise_stage": 7, + "denoise_idx": 14, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.0093994140625, + "flowcache_rel_l1_ratio": 0.009389671361502348, + "flowcache_delta_l1_norm": 16384.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.01873779296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 126, + "denoise_stage": 7, + "denoise_idx": 14, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012555803571428572, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01253509521484375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 127, + "denoise_stage": 7, + "denoise_idx": 15, + "chunk_idx": 4, + "generated_chunk_idx": 4, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.1103515625, + "flowcache_rel_l1_ratio": 0.11088709677419355, + "flowcache_delta_l1_norm": 168960.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.1103515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 127, + "denoise_stage": 7, + "denoise_idx": 15, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.03125, + "flowcache_rel_l1_ratio": 0.031081989247311828, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.03125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 127, + "denoise_stage": 7, + "denoise_idx": 15, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.0106201171875, + "flowcache_rel_l1_ratio": 0.010539504716981132, + "flowcache_delta_l1_norm": 18304.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.0106201171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 127, + "denoise_stage": 7, + "denoise_idx": 15, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00125885009765625, + "flowcache_rel_l1_ratio": 0.0012555803571428572, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0137939453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 128, + "denoise_stage": 8, + "denoise_idx": 0, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.03369140625, + "flowcache_rel_l1_ratio": 0.033627717391304345, + "flowcache_delta_l1_norm": 50688.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.03369140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 128, + "denoise_stage": 8, + "denoise_idx": 0, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01068115234375, + "flowcache_rel_l1_ratio": 0.010589454976303318, + "flowcache_delta_l1_norm": 18304.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.02130126953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 128, + "denoise_stage": 8, + "denoise_idx": 0, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.0012664794921875, + "flowcache_rel_l1_ratio": 0.0012555803571428572, + "flowcache_delta_l1_norm": 2304.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0150604248046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 129, + "denoise_stage": 8, + "denoise_idx": 1, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.036376953125, + "flowcache_rel_l1_ratio": 0.036401098901098904, + "flowcache_delta_l1_norm": 54272.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.036376953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 129, + "denoise_stage": 8, + "denoise_idx": 1, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.011962890625, + "flowcache_rel_l1_ratio": 0.011961722488038277, + "flowcache_delta_l1_norm": 20480.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.011962890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 129, + "denoise_stage": 8, + "denoise_idx": 1, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.0045166015625, + "flowcache_rel_l1_ratio": 0.004499162946428571, + "flowcache_delta_l1_norm": 8256.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0045166015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 129, + "denoise_stage": 8, + "denoise_idx": 1, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 130, + "denoise_stage": 8, + "denoise_idx": 2, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.03940972222222222, + "flowcache_delta_l1_norm": 58112.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 130, + "denoise_stage": 8, + "denoise_idx": 2, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01202392578125, + "flowcache_rel_l1_ratio": 0.01201923076923077, + "flowcache_delta_l1_norm": 20480.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.02398681640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 130, + "denoise_stage": 8, + "denoise_idx": 2, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.0045166015625, + "flowcache_rel_l1_ratio": 0.0045193385650224216, + "flowcache_delta_l1_norm": 8256.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.009033203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 130, + "denoise_stage": 8, + "denoise_idx": 2, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 131, + "denoise_stage": 8, + "denoise_idx": 3, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.04296875, + "flowcache_rel_l1_ratio": 0.042837078651685394, + "flowcache_delta_l1_norm": 62464.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.04296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 131, + "denoise_stage": 8, + "denoise_idx": 3, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.0135498046875, + "flowcache_rel_l1_ratio": 0.013577063106796116, + "flowcache_delta_l1_norm": 22912.0, + "flowcache_prev_feat_l1_norm": 1687552.0, + "flowcache_accumulated_rel_l1": 0.0135498046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 131, + "denoise_stage": 8, + "denoise_idx": 3, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.0045166015625, + "flowcache_rel_l1_ratio": 0.0045193385650224216, + "flowcache_delta_l1_norm": 8256.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.0135498046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 131, + "denoise_stage": 8, + "denoise_idx": 3, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 132, + "denoise_stage": 8, + "denoise_idx": 4, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046630859375, + "flowcache_rel_l1_ratio": 0.046875, + "flowcache_delta_l1_norm": 67584.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.046630859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 132, + "denoise_stage": 8, + "denoise_idx": 4, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.013671875, + "flowcache_rel_l1_ratio": 0.01364329268292683, + "flowcache_delta_l1_norm": 22912.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.0272216796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 132, + "denoise_stage": 8, + "denoise_idx": 4, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.0045166015625, + "flowcache_rel_l1_ratio": 0.0045396959459459455, + "flowcache_delta_l1_norm": 8256.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.01806640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 132, + "denoise_stage": 8, + "denoise_idx": 4, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 133, + "denoise_stage": 8, + "denoise_idx": 5, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05078125, + "flowcache_rel_l1_ratio": 0.05071428571428571, + "flowcache_delta_l1_norm": 72704.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 133, + "denoise_stage": 8, + "denoise_idx": 5, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01544189453125, + "flowcache_rel_l1_ratio": 0.015471059113300493, + "flowcache_delta_l1_norm": 25728.0, + "flowcache_prev_feat_l1_norm": 1662976.0, + "flowcache_accumulated_rel_l1": 0.01544189453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 133, + "denoise_stage": 8, + "denoise_idx": 5, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.005767822265625, + "flowcache_rel_l1_ratio": 0.005762160633484163, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.005767822265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 133, + "denoise_stage": 8, + "denoise_idx": 5, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00124359130859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 134, + "denoise_stage": 8, + "denoise_idx": 6, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.05517578125, + "flowcache_rel_l1_ratio": 0.055274566473988436, + "flowcache_delta_l1_norm": 78336.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.05517578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 134, + "denoise_stage": 8, + "denoise_idx": 6, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0164794921875, + "flowcache_rel_l1_ratio": 0.016475866336633664, + "flowcache_delta_l1_norm": 27264.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0164794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 134, + "denoise_stage": 8, + "denoise_idx": 6, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.005762160633484163, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.011566162109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 134, + "denoise_stage": 8, + "denoise_idx": 6, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0024871826171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 135, + "denoise_stage": 8, + "denoise_idx": 7, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.060546875, + "flowcache_rel_l1_ratio": 0.06031976744186047, + "flowcache_delta_l1_norm": 84992.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.060546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 135, + "denoise_stage": 8, + "denoise_idx": 7, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.017578125, + "flowcache_delta_l1_norm": 28800.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 135, + "denoise_stage": 8, + "denoise_idx": 7, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.00579833984375, + "flowcache_rel_l1_ratio": 0.005788352272727273, + "flowcache_delta_l1_norm": 10432.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.017364501953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 135, + "denoise_stage": 8, + "denoise_idx": 7, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.00122833251953125, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00371551513671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 136, + "denoise_stage": 8, + "denoise_idx": 8, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06640625, + "flowcache_rel_l1_ratio": 0.06578947368421052, + "flowcache_delta_l1_norm": 92160.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.06640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 136, + "denoise_stage": 8, + "denoise_idx": 8, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.018844221105527637, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 136, + "denoise_stage": 8, + "denoise_idx": 8, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.00689697265625, + "flowcache_rel_l1_ratio": 0.006920662100456621, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00689697265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 136, + "denoise_stage": 8, + "denoise_idx": 8, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0049591064453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 137, + "denoise_stage": 8, + "denoise_idx": 9, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.07177734375, + "flowcache_rel_l1_ratio": 0.07205882352941176, + "flowcache_delta_l1_norm": 100352.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07177734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 137, + "denoise_stage": 8, + "denoise_idx": 9, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.020145939086294418, + "flowcache_delta_l1_norm": 32512.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 137, + "denoise_stage": 8, + "denoise_idx": 9, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.006927490234375, + "flowcache_rel_l1_ratio": 0.006952408256880734, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.013824462890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 137, + "denoise_stage": 8, + "denoise_idx": 9, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.006195068359375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 138, + "denoise_stage": 8, + "denoise_idx": 10, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.0791015625, + "flowcache_rel_l1_ratio": 0.07867647058823529, + "flowcache_delta_l1_norm": 109568.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 138, + "denoise_stage": 8, + "denoise_idx": 10, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 138, + "denoise_stage": 8, + "denoise_idx": 10, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.0069580078125, + "flowcache_rel_l1_ratio": 0.006984447004608295, + "flowcache_delta_l1_norm": 12416.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.020782470703125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 138, + "denoise_stage": 8, + "denoise_idx": 10, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00743865966796875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 139, + "denoise_stage": 8, + "denoise_idx": 11, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.0859375, + "flowcache_rel_l1_ratio": 0.08602941176470588, + "flowcache_delta_l1_norm": 119808.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 139, + "denoise_stage": 8, + "denoise_idx": 11, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.023193359375, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.023193359375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 139, + "denoise_stage": 8, + "denoise_idx": 11, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.00836181640625, + "flowcache_rel_l1_ratio": 0.008318865740740741, + "flowcache_delta_l1_norm": 14720.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.00836181640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 139, + "denoise_stage": 8, + "denoise_idx": 11, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0086822509765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 140, + "denoise_stage": 8, + "denoise_idx": 12, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.09326171875, + "flowcache_rel_l1_ratio": 0.09265988372093023, + "flowcache_delta_l1_norm": 130560.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.09326171875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 140, + "denoise_stage": 8, + "denoise_idx": 12, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.025032722513089006, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 140, + "denoise_stage": 8, + "denoise_idx": 12, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.00836181640625, + "flowcache_rel_l1_ratio": 0.008357558139534883, + "flowcache_delta_l1_norm": 14720.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.0167236328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 140, + "denoise_stage": 8, + "denoise_idx": 12, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.0012359619140625, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.009918212890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 141, + "denoise_stage": 8, + "denoise_idx": 13, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.10009765625, + "flowcache_rel_l1_ratio": 0.1, + "flowcache_delta_l1_norm": 143360.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.10009765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 141, + "denoise_stage": 8, + "denoise_idx": 13, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.0269510582010582, + "flowcache_delta_l1_norm": 41728.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 141, + "denoise_stage": 8, + "denoise_idx": 13, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.0093994140625, + "flowcache_rel_l1_ratio": 0.009345794392523364, + "flowcache_delta_l1_norm": 16384.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.0093994140625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 141, + "denoise_stage": 8, + "denoise_idx": 13, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01116180419921875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 142, + "denoise_stage": 8, + "denoise_idx": 14, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.10546875, + "flowcache_rel_l1_ratio": 0.10555555555555556, + "flowcache_delta_l1_norm": 155648.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.10546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 142, + "denoise_stage": 8, + "denoise_idx": 14, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.02880859375, + "flowcache_rel_l1_ratio": 0.02892287234042553, + "flowcache_delta_l1_norm": 44544.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.02880859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 142, + "denoise_stage": 8, + "denoise_idx": 14, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00946044921875, + "flowcache_rel_l1_ratio": 0.009389671361502348, + "flowcache_delta_l1_norm": 16384.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.01885986328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 142, + "denoise_stage": 8, + "denoise_idx": 14, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.0124053955078125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 143, + "denoise_stage": 8, + "denoise_idx": 15, + "chunk_idx": 5, + "generated_chunk_idx": 5, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.109375, + "flowcache_rel_l1_ratio": 0.10970744680851063, + "flowcache_delta_l1_norm": 168960.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 143, + "denoise_stage": 8, + "denoise_idx": 15, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.03125, + "flowcache_rel_l1_ratio": 0.031081989247311828, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.03125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 143, + "denoise_stage": 8, + "denoise_idx": 15, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.0106201171875, + "flowcache_rel_l1_ratio": 0.010589454976303318, + "flowcache_delta_l1_norm": 18304.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.0106201171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 143, + "denoise_stage": 8, + "denoise_idx": 15, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01364898681640625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 144, + "denoise_stage": 9, + "denoise_idx": 0, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.03369140625, + "flowcache_rel_l1_ratio": 0.033627717391304345, + "flowcache_delta_l1_norm": 50688.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.03369140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 144, + "denoise_stage": 9, + "denoise_idx": 0, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01068115234375, + "flowcache_rel_l1_ratio": 0.010639880952380953, + "flowcache_delta_l1_norm": 18304.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.02130126953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 144, + "denoise_stage": 9, + "denoise_idx": 0, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.001251220703125, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01490020751953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 145, + "denoise_stage": 9, + "denoise_idx": 1, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.036376953125, + "flowcache_rel_l1_ratio": 0.036401098901098904, + "flowcache_delta_l1_norm": 54272.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.036376953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 145, + "denoise_stage": 9, + "denoise_idx": 1, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.011962890625, + "flowcache_rel_l1_ratio": 0.011961722488038277, + "flowcache_delta_l1_norm": 20480.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.011962890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 145, + "denoise_stage": 9, + "denoise_idx": 1, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.016143798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 145, + "denoise_stage": 9, + "denoise_idx": 1, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 1, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 146, + "denoise_stage": 9, + "denoise_idx": 2, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.03940972222222222, + "flowcache_delta_l1_norm": 58112.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 146, + "denoise_stage": 9, + "denoise_idx": 2, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.0120849609375, + "flowcache_rel_l1_ratio": 0.012077294685990338, + "flowcache_delta_l1_norm": 20480.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.0240478515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 146, + "denoise_stage": 9, + "denoise_idx": 2, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004778180803571429, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.004791259765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 146, + "denoise_stage": 9, + "denoise_idx": 2, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 2, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 147, + "denoise_stage": 9, + "denoise_idx": 3, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.042724609375, + "flowcache_rel_l1_ratio": 0.042837078651685394, + "flowcache_delta_l1_norm": 62464.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.042724609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 147, + "denoise_stage": 9, + "denoise_idx": 3, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01361083984375, + "flowcache_rel_l1_ratio": 0.013652912621359222, + "flowcache_delta_l1_norm": 23040.0, + "flowcache_prev_feat_l1_norm": 1687552.0, + "flowcache_accumulated_rel_l1": 0.01361083984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 147, + "denoise_stage": 9, + "denoise_idx": 3, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004799607623318386, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.00958251953125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 147, + "denoise_stage": 9, + "denoise_idx": 3, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 3, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 148, + "denoise_stage": 9, + "denoise_idx": 4, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046630859375, + "flowcache_rel_l1_ratio": 0.04651988636363636, + "flowcache_delta_l1_norm": 67072.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.046630859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 148, + "denoise_stage": 9, + "denoise_idx": 4, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.013671875, + "flowcache_rel_l1_ratio": 0.013786764705882353, + "flowcache_delta_l1_norm": 23040.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.02728271484375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 148, + "denoise_stage": 9, + "denoise_idx": 4, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004821227477477478, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.014373779296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 148, + "denoise_stage": 9, + "denoise_idx": 4, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 4, + "flowcache_rel_l1": null, + "flowcache_rel_l1_ratio": null, + "flowcache_delta_l1_norm": null, + "flowcache_prev_feat_l1_norm": null, + "flowcache_accumulated_rel_l1": 0.0, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "warmup" + }, + { + "infer_idx": 0, + "cur_denoise_step": 149, + "denoise_stage": 9, + "denoise_idx": 5, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.05078125, + "flowcache_rel_l1_ratio": 0.05071428571428571, + "flowcache_delta_l1_norm": 72704.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.05078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 149, + "denoise_stage": 9, + "denoise_idx": 5, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01544189453125, + "flowcache_rel_l1_ratio": 0.015471059113300493, + "flowcache_delta_l1_norm": 25728.0, + "flowcache_prev_feat_l1_norm": 1662976.0, + "flowcache_accumulated_rel_l1": 0.01544189453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 149, + "denoise_stage": 9, + "denoise_idx": 5, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.00482177734375, + "flowcache_rel_l1_ratio": 0.004821227477477478, + "flowcache_delta_l1_norm": 8768.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.019195556640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 149, + "denoise_stage": 9, + "denoise_idx": 5, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 5, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00124359130859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 150, + "denoise_stage": 9, + "denoise_idx": 6, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.0556640625, + "flowcache_rel_l1_ratio": 0.055274566473988436, + "flowcache_delta_l1_norm": 78336.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.0556640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 150, + "denoise_stage": 9, + "denoise_idx": 6, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0164794921875, + "flowcache_rel_l1_ratio": 0.01655783582089552, + "flowcache_delta_l1_norm": 27264.0, + "flowcache_prev_feat_l1_norm": 1646592.0, + "flowcache_accumulated_rel_l1": 0.0164794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 150, + "denoise_stage": 9, + "denoise_idx": 6, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.006072998046875, + "flowcache_rel_l1_ratio": 0.00611566742081448, + "flowcache_delta_l1_norm": 11072.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.006072998046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 150, + "denoise_stage": 9, + "denoise_idx": 6, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 6, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.0024871826171875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 151, + "denoise_stage": 9, + "denoise_idx": 7, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.060546875, + "flowcache_rel_l1_ratio": 0.06031976744186047, + "flowcache_delta_l1_norm": 84992.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.060546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 151, + "denoise_stage": 9, + "denoise_idx": 7, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.017578125, + "flowcache_delta_l1_norm": 28800.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 151, + "denoise_stage": 9, + "denoise_idx": 7, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.006103515625, + "flowcache_rel_l1_ratio": 0.006143465909090909, + "flowcache_delta_l1_norm": 11072.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.012176513671875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 151, + "denoise_stage": 9, + "denoise_idx": 7, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 7, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00373077392578125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 152, + "denoise_stage": 9, + "denoise_idx": 8, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06591796875, + "flowcache_rel_l1_ratio": 0.0661764705882353, + "flowcache_delta_l1_norm": 92160.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.06591796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 152, + "denoise_stage": 9, + "denoise_idx": 8, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.0189208984375, + "flowcache_rel_l1_ratio": 0.01893939393939394, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1622016.0, + "flowcache_accumulated_rel_l1": 0.0189208984375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 152, + "denoise_stage": 9, + "denoise_idx": 8, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006134033203125, + "flowcache_rel_l1_ratio": 0.006171518264840183, + "flowcache_delta_l1_norm": 11072.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.018310546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 152, + "denoise_stage": 9, + "denoise_idx": 8, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 8, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.004974365234375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 153, + "denoise_stage": 9, + "denoise_idx": 9, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.072265625, + "flowcache_rel_l1_ratio": 0.07205882352941176, + "flowcache_delta_l1_norm": 100352.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.072265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 153, + "denoise_stage": 9, + "denoise_idx": 9, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.0201416015625, + "flowcache_rel_l1_ratio": 0.02024872448979592, + "flowcache_delta_l1_norm": 32512.0, + "flowcache_prev_feat_l1_norm": 1605632.0, + "flowcache_accumulated_rel_l1": 0.0201416015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 153, + "denoise_stage": 9, + "denoise_idx": 9, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.00732421875, + "flowcache_rel_l1_ratio": 0.007346616972477064, + "flowcache_delta_l1_norm": 13120.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.00732421875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 153, + "denoise_stage": 9, + "denoise_idx": 9, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 9, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012358268805309734, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1851392.0, + "flowcache_accumulated_rel_l1": 0.00621795654296875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 154, + "denoise_stage": 9, + "denoise_idx": 10, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.0791015625, + "flowcache_rel_l1_ratio": 0.07877218934911243, + "flowcache_delta_l1_norm": 109056.0, + "flowcache_prev_feat_l1_norm": 1384448.0, + "flowcache_accumulated_rel_l1": 0.0791015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 154, + "denoise_stage": 9, + "denoise_idx": 10, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 154, + "denoise_stage": 9, + "denoise_idx": 10, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.007380472350230415, + "flowcache_delta_l1_norm": 13120.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.01470947265625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 154, + "denoise_stage": 9, + "denoise_idx": 10, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 10, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0074615478515625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 155, + "denoise_stage": 9, + "denoise_idx": 11, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.0859375, + "flowcache_rel_l1_ratio": 0.08566176470588235, + "flowcache_delta_l1_norm": 119296.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 155, + "denoise_stage": 9, + "denoise_idx": 11, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0233154296875, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0233154296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 155, + "denoise_stage": 9, + "denoise_idx": 11, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.007415771484375, + "flowcache_rel_l1_ratio": 0.007414641203703704, + "flowcache_delta_l1_norm": 13120.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.022125244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 155, + "denoise_stage": 9, + "denoise_idx": 11, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 11, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00870513916015625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 156, + "denoise_stage": 9, + "denoise_idx": 12, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.0927734375, + "flowcache_rel_l1_ratio": 0.09320175438596491, + "flowcache_delta_l1_norm": 130560.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.0927734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 156, + "denoise_stage": 9, + "denoise_idx": 12, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.02490234375, + "flowcache_rel_l1_ratio": 0.025032722513089006, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.02490234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 156, + "denoise_stage": 9, + "denoise_idx": 12, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.00879360465116279, + "flowcache_delta_l1_norm": 15488.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.00885009765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 156, + "denoise_stage": 9, + "denoise_idx": 12, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 12, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 157, + "denoise_stage": 9, + "denoise_idx": 13, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.099609375, + "flowcache_rel_l1_ratio": 0.09985632183908046, + "flowcache_delta_l1_norm": 142336.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.099609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 157, + "denoise_stage": 9, + "denoise_idx": 13, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.026785714285714284, + "flowcache_delta_l1_norm": 41472.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 157, + "denoise_stage": 9, + "denoise_idx": 13, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008834696261682243, + "flowcache_delta_l1_norm": 15488.0, + "flowcache_prev_feat_l1_norm": 1753088.0, + "flowcache_accumulated_rel_l1": 0.0177001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 157, + "denoise_stage": 9, + "denoise_idx": 13, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 13, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01119232177734375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 158, + "denoise_stage": 9, + "denoise_idx": 14, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.1064453125, + "flowcache_rel_l1_ratio": 0.10555555555555556, + "flowcache_delta_l1_norm": 155648.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.1064453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 158, + "denoise_stage": 9, + "denoise_idx": 14, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.029052734375, + "flowcache_rel_l1_ratio": 0.028910427807486632, + "flowcache_delta_l1_norm": 44288.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.029052734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 158, + "denoise_stage": 9, + "denoise_idx": 14, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00994873046875, + "flowcache_rel_l1_ratio": 0.009903169014084508, + "flowcache_delta_l1_norm": 17280.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 158, + "denoise_stage": 9, + "denoise_idx": 14, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 14, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.0124359130859375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 159, + "denoise_stage": 9, + "denoise_idx": 15, + "chunk_idx": 6, + "generated_chunk_idx": 6, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.1103515625, + "flowcache_rel_l1_ratio": 0.11029411764705882, + "flowcache_delta_l1_norm": 168960.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.1103515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 159, + "denoise_stage": 9, + "denoise_idx": 15, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.031005859375, + "flowcache_rel_l1_ratio": 0.03125, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1515520.0, + "flowcache_accumulated_rel_l1": 0.031005859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 159, + "denoise_stage": 9, + "denoise_idx": 15, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.009949882075471699, + "flowcache_delta_l1_norm": 17280.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.01995849609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 159, + "denoise_stage": 9, + "denoise_idx": 15, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 15, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.01367950439453125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 160, + "denoise_stage": 10, + "denoise_idx": 0, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.033447265625, + "flowcache_rel_l1_ratio": 0.033640710382513664, + "flowcache_delta_l1_norm": 50432.0, + "flowcache_prev_feat_l1_norm": 1499136.0, + "flowcache_accumulated_rel_l1": 0.033447265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 160, + "denoise_stage": 10, + "denoise_idx": 0, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01123046875, + "flowcache_rel_l1_ratio": 0.011235119047619048, + "flowcache_delta_l1_norm": 19328.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.01123046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 160, + "denoise_stage": 10, + "denoise_idx": 0, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 16, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012413194444444444, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1843200.0, + "flowcache_accumulated_rel_l1": 0.014923095703125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 161, + "denoise_stage": 10, + "denoise_idx": 1, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.036376953125, + "flowcache_rel_l1_ratio": 0.03622939560439561, + "flowcache_delta_l1_norm": 54016.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.036376953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 161, + "denoise_stage": 10, + "denoise_idx": 1, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011288875598086124, + "flowcache_delta_l1_norm": 19328.0, + "flowcache_prev_feat_l1_norm": 1712128.0, + "flowcache_accumulated_rel_l1": 0.02252197265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 161, + "denoise_stage": 10, + "denoise_idx": 1, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 17, + "flowcache_rel_l1": 0.00124359130859375, + "flowcache_rel_l1_ratio": 0.0012468610491071428, + "flowcache_delta_l1_norm": 2288.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.01616668701171875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 162, + "denoise_stage": 10, + "denoise_idx": 2, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.03940972222222222, + "flowcache_delta_l1_norm": 58112.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 162, + "denoise_stage": 10, + "denoise_idx": 2, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01263427734375, + "flowcache_rel_l1_ratio": 0.012620192307692308, + "flowcache_delta_l1_norm": 21504.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01263427734375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 162, + "denoise_stage": 10, + "denoise_idx": 2, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 18, + "flowcache_rel_l1": 0.004791259765625, + "flowcache_rel_l1_ratio": 0.004813058035714286, + "flowcache_delta_l1_norm": 8832.0, + "flowcache_prev_feat_l1_norm": 1835008.0, + "flowcache_accumulated_rel_l1": 0.004791259765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 163, + "denoise_stage": 10, + "denoise_idx": 3, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.042724609375, + "flowcache_rel_l1_ratio": 0.04266151685393258, + "flowcache_delta_l1_norm": 62208.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.042724609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 163, + "denoise_stage": 10, + "denoise_idx": 3, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01275634765625, + "flowcache_rel_l1_ratio": 0.012742718446601941, + "flowcache_delta_l1_norm": 21504.0, + "flowcache_prev_feat_l1_norm": 1687552.0, + "flowcache_accumulated_rel_l1": 0.025390625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 163, + "denoise_stage": 10, + "denoise_idx": 3, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 19, + "flowcache_rel_l1": 0.00482177734375, + "flowcache_rel_l1_ratio": 0.004834641255605381, + "flowcache_delta_l1_norm": 8832.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.009613037109375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 164, + "denoise_stage": 10, + "denoise_idx": 4, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.046630859375, + "flowcache_rel_l1_ratio": 0.04651988636363636, + "flowcache_delta_l1_norm": 67072.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.046630859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 164, + "denoise_stage": 10, + "denoise_idx": 4, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.01446533203125, + "flowcache_rel_l1_ratio": 0.01440548780487805, + "flowcache_delta_l1_norm": 24192.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.01446533203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 164, + "denoise_stage": 10, + "denoise_idx": 4, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 20, + "flowcache_rel_l1": 0.004852294921875, + "flowcache_rel_l1_ratio": 0.004834641255605381, + "flowcache_delta_l1_norm": 8832.0, + "flowcache_prev_feat_l1_norm": 1826816.0, + "flowcache_accumulated_rel_l1": 0.01446533203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 165, + "denoise_stage": 10, + "denoise_idx": 5, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.050537109375, + "flowcache_rel_l1_ratio": 0.05064655172413793, + "flowcache_delta_l1_norm": 72192.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.050537109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 165, + "denoise_stage": 10, + "denoise_idx": 5, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.0145263671875, + "flowcache_rel_l1_ratio": 0.014547413793103448, + "flowcache_delta_l1_norm": 24192.0, + "flowcache_prev_feat_l1_norm": 1662976.0, + "flowcache_accumulated_rel_l1": 0.02899169921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 165, + "denoise_stage": 10, + "denoise_idx": 5, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 21, + "flowcache_rel_l1": 0.004852294921875, + "flowcache_rel_l1_ratio": 0.004856418918918919, + "flowcache_delta_l1_norm": 8832.0, + "flowcache_prev_feat_l1_norm": 1818624.0, + "flowcache_accumulated_rel_l1": 0.019317626953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 166, + "denoise_stage": 10, + "denoise_idx": 6, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.05517578125, + "flowcache_rel_l1_ratio": 0.055274566473988436, + "flowcache_delta_l1_norm": 78336.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.05517578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 166, + "denoise_stage": 10, + "denoise_idx": 6, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.016357421875, + "flowcache_rel_l1_ratio": 0.01639851485148515, + "flowcache_delta_l1_norm": 27136.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.016357421875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 166, + "denoise_stage": 10, + "denoise_idx": 6, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 22, + "flowcache_rel_l1": 0.006134033203125, + "flowcache_rel_l1_ratio": 0.006151018099547511, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.006134033203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 167, + "denoise_stage": 10, + "denoise_idx": 7, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.060546875, + "flowcache_rel_l1_ratio": 0.06030701754385965, + "flowcache_delta_l1_norm": 84480.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.060546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 167, + "denoise_stage": 10, + "denoise_idx": 7, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.0174560546875, + "flowcache_rel_l1_ratio": 0.0175, + "flowcache_delta_l1_norm": 28672.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.0174560546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 167, + "denoise_stage": 10, + "denoise_idx": 7, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 23, + "flowcache_rel_l1": 0.00616455078125, + "flowcache_rel_l1_ratio": 0.006151018099547511, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1810432.0, + "flowcache_accumulated_rel_l1": 0.012298583984375, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 168, + "denoise_stage": 10, + "denoise_idx": 8, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.06591796875, + "flowcache_rel_l1_ratio": 0.06580882352941177, + "flowcache_delta_l1_norm": 91648.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.06591796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 168, + "denoise_stage": 10, + "denoise_idx": 8, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.018798828125, + "flowcache_rel_l1_ratio": 0.018781565656565656, + "flowcache_delta_l1_norm": 30464.0, + "flowcache_prev_feat_l1_norm": 1622016.0, + "flowcache_accumulated_rel_l1": 0.018798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 168, + "denoise_stage": 10, + "denoise_idx": 8, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 24, + "flowcache_rel_l1": 0.006195068359375, + "flowcache_rel_l1_ratio": 0.006178977272727273, + "flowcache_delta_l1_norm": 11136.0, + "flowcache_prev_feat_l1_norm": 1802240.0, + "flowcache_accumulated_rel_l1": 0.01849365234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 169, + "denoise_stage": 10, + "denoise_idx": 9, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.0712890625, + "flowcache_rel_l1_ratio": 0.07169117647058823, + "flowcache_delta_l1_norm": 99840.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0712890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 169, + "denoise_stage": 10, + "denoise_idx": 9, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.02001953125, + "flowcache_rel_l1_ratio": 0.020089285714285716, + "flowcache_delta_l1_norm": 32256.0, + "flowcache_prev_feat_l1_norm": 1605632.0, + "flowcache_accumulated_rel_l1": 0.02001953125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 169, + "denoise_stage": 10, + "denoise_idx": 9, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 25, + "flowcache_rel_l1": 0.00738525390625, + "flowcache_rel_l1_ratio": 0.0073487442922374425, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1794048.0, + "flowcache_accumulated_rel_l1": 0.00738525390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 170, + "denoise_stage": 10, + "denoise_idx": 10, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.07861328125, + "flowcache_rel_l1_ratio": 0.07830882352941176, + "flowcache_delta_l1_norm": 109056.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07861328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 170, + "denoise_stage": 10, + "denoise_idx": 10, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021484375, + "flowcache_rel_l1_ratio": 0.021474358974358974, + "flowcache_delta_l1_norm": 34304.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021484375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 170, + "denoise_stage": 10, + "denoise_idx": 10, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 26, + "flowcache_rel_l1": 0.007415771484375, + "flowcache_rel_l1_ratio": 0.007382454128440367, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1785856.0, + "flowcache_accumulated_rel_l1": 0.014801025390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 171, + "denoise_stage": 10, + "denoise_idx": 11, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08544921875, + "flowcache_rel_l1_ratio": 0.08529411764705883, + "flowcache_delta_l1_norm": 118784.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08544921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 171, + "denoise_stage": 10, + "denoise_idx": 11, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.0230712890625, + "flowcache_rel_l1_ratio": 0.023154145077720206, + "flowcache_delta_l1_norm": 36608.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.0230712890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 171, + "denoise_stage": 10, + "denoise_idx": 11, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 27, + "flowcache_rel_l1": 0.0074462890625, + "flowcache_rel_l1_ratio": 0.00741647465437788, + "flowcache_delta_l1_norm": 13184.0, + "flowcache_prev_feat_l1_norm": 1777664.0, + "flowcache_accumulated_rel_l1": 0.022247314453125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 172, + "denoise_stage": 10, + "denoise_idx": 12, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.0927734375, + "flowcache_rel_l1_ratio": 0.09229651162790697, + "flowcache_delta_l1_norm": 130048.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.0927734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 172, + "denoise_stage": 10, + "denoise_idx": 12, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.02490234375, + "flowcache_rel_l1_ratio": 0.024869109947643978, + "flowcache_delta_l1_norm": 38912.0, + "flowcache_prev_feat_l1_norm": 1564672.0, + "flowcache_accumulated_rel_l1": 0.02490234375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 172, + "denoise_stage": 10, + "denoise_idx": 12, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 28, + "flowcache_rel_l1": 0.0087890625, + "flowcache_rel_l1_ratio": 0.00882523148148148, + "flowcache_delta_l1_norm": 15616.0, + "flowcache_prev_feat_l1_norm": 1769472.0, + "flowcache_accumulated_rel_l1": 0.0087890625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 173, + "denoise_stage": 10, + "denoise_idx": 13, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.10009765625, + "flowcache_rel_l1_ratio": 0.09928571428571428, + "flowcache_delta_l1_norm": 142336.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.10009765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 173, + "denoise_stage": 10, + "denoise_idx": 13, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.026611328125, + "flowcache_rel_l1_ratio": 0.02662037037037037, + "flowcache_delta_l1_norm": 41216.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.026611328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 173, + "denoise_stage": 10, + "denoise_idx": 13, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 29, + "flowcache_rel_l1": 0.00885009765625, + "flowcache_rel_l1_ratio": 0.008866279069767441, + "flowcache_delta_l1_norm": 15616.0, + "flowcache_prev_feat_l1_norm": 1761280.0, + "flowcache_accumulated_rel_l1": 0.01763916015625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 174, + "denoise_stage": 10, + "denoise_idx": 14, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.10546875, + "flowcache_rel_l1_ratio": 0.10555555555555556, + "flowcache_delta_l1_norm": 155648.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.10546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 174, + "denoise_stage": 10, + "denoise_idx": 14, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.02880859375, + "flowcache_rel_l1_ratio": 0.02874331550802139, + "flowcache_delta_l1_norm": 44032.0, + "flowcache_prev_feat_l1_norm": 1531904.0, + "flowcache_accumulated_rel_l1": 0.02880859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 174, + "denoise_stage": 10, + "denoise_idx": 14, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 30, + "flowcache_rel_l1": 0.00994873046875, + "flowcache_rel_l1_ratio": 0.009976525821596244, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1744896.0, + "flowcache_accumulated_rel_l1": 0.00994873046875, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 175, + "denoise_stage": 10, + "denoise_idx": 15, + "chunk_idx": 7, + "generated_chunk_idx": 7, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.1103515625, + "flowcache_rel_l1_ratio": 0.11037234042553191, + "flowcache_delta_l1_norm": 169984.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.1103515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 175, + "denoise_stage": 10, + "denoise_idx": 15, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.0308837890625, + "flowcache_rel_l1_ratio": 0.031081081081081083, + "flowcache_delta_l1_norm": 47104.0, + "flowcache_prev_feat_l1_norm": 1515520.0, + "flowcache_accumulated_rel_l1": 0.0308837890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 175, + "denoise_stage": 10, + "denoise_idx": 15, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 31, + "flowcache_rel_l1": 0.010009765625, + "flowcache_rel_l1_ratio": 0.010023584905660377, + "flowcache_delta_l1_norm": 17408.0, + "flowcache_prev_feat_l1_norm": 1736704.0, + "flowcache_accumulated_rel_l1": 0.01995849609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 176, + "denoise_stage": 11, + "denoise_idx": 0, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.033447265625, + "flowcache_rel_l1_ratio": 0.03346994535519126, + "flowcache_delta_l1_norm": 50176.0, + "flowcache_prev_feat_l1_norm": 1499136.0, + "flowcache_accumulated_rel_l1": 0.033447265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 176, + "denoise_stage": 11, + "denoise_idx": 0, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 32, + "flowcache_rel_l1": 0.01129150390625, + "flowcache_rel_l1_ratio": 0.011255924170616114, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1728512.0, + "flowcache_accumulated_rel_l1": 0.01129150390625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 177, + "denoise_stage": 11, + "denoise_idx": 1, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.0361328125, + "flowcache_rel_l1_ratio": 0.036256906077348064, + "flowcache_delta_l1_norm": 53760.0, + "flowcache_prev_feat_l1_norm": 1482752.0, + "flowcache_accumulated_rel_l1": 0.0361328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 177, + "denoise_stage": 11, + "denoise_idx": 1, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 33, + "flowcache_rel_l1": 0.01141357421875, + "flowcache_rel_l1_ratio": 0.01130952380952381, + "flowcache_delta_l1_norm": 19456.0, + "flowcache_prev_feat_l1_norm": 1720320.0, + "flowcache_accumulated_rel_l1": 0.022705078125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 178, + "denoise_stage": 11, + "denoise_idx": 2, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.0390625, + "flowcache_delta_l1_norm": 57600.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 178, + "denoise_stage": 11, + "denoise_idx": 2, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 34, + "flowcache_rel_l1": 0.01275634765625, + "flowcache_rel_l1_ratio": 0.012770432692307692, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1703936.0, + "flowcache_accumulated_rel_l1": 0.01275634765625, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 179, + "denoise_stage": 11, + "denoise_idx": 3, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.04248046875, + "flowcache_rel_l1_ratio": 0.042485955056179775, + "flowcache_delta_l1_norm": 61952.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.04248046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 179, + "denoise_stage": 11, + "denoise_idx": 3, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 35, + "flowcache_rel_l1": 0.01287841796875, + "flowcache_rel_l1_ratio": 0.012832125603864734, + "flowcache_delta_l1_norm": 21760.0, + "flowcache_prev_feat_l1_norm": 1695744.0, + "flowcache_accumulated_rel_l1": 0.025634765625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 180, + "denoise_stage": 11, + "denoise_idx": 4, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.04638671875, + "flowcache_rel_l1_ratio": 0.04616477272727273, + "flowcache_delta_l1_norm": 66560.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.04638671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 180, + "denoise_stage": 11, + "denoise_idx": 4, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 36, + "flowcache_rel_l1": 0.01446533203125, + "flowcache_rel_l1_ratio": 0.014481707317073171, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1679360.0, + "flowcache_accumulated_rel_l1": 0.01446533203125, + "rel_l1_thresh": 0.015, + "reused": true, + "decision_reason": "below_threshold" + }, + { + "infer_idx": 0, + "cur_denoise_step": 181, + "denoise_stage": 11, + "denoise_idx": 5, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.050048828125, + "flowcache_rel_l1_ratio": 0.05028735632183908, + "flowcache_delta_l1_norm": 71680.0, + "flowcache_prev_feat_l1_norm": 1425408.0, + "flowcache_accumulated_rel_l1": 0.050048828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 181, + "denoise_stage": 11, + "denoise_idx": 5, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 37, + "flowcache_rel_l1": 0.01458740234375, + "flowcache_rel_l1_ratio": 0.014552696078431373, + "flowcache_delta_l1_norm": 24320.0, + "flowcache_prev_feat_l1_norm": 1671168.0, + "flowcache_accumulated_rel_l1": 0.029052734375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 182, + "denoise_stage": 11, + "denoise_idx": 6, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.054931640625, + "flowcache_rel_l1_ratio": 0.05491329479768786, + "flowcache_delta_l1_norm": 77824.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.054931640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 182, + "denoise_stage": 11, + "denoise_idx": 6, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 38, + "flowcache_rel_l1": 0.0164794921875, + "flowcache_rel_l1_ratio": 0.016475866336633664, + "flowcache_delta_l1_norm": 27264.0, + "flowcache_prev_feat_l1_norm": 1654784.0, + "flowcache_accumulated_rel_l1": 0.0164794921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 183, + "denoise_stage": 11, + "denoise_idx": 7, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.06005859375, + "flowcache_rel_l1_ratio": 0.059941520467836254, + "flowcache_delta_l1_norm": 83968.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.06005859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 183, + "denoise_stage": 11, + "denoise_idx": 7, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 39, + "flowcache_rel_l1": 0.017578125, + "flowcache_rel_l1_ratio": 0.01765625, + "flowcache_delta_l1_norm": 28928.0, + "flowcache_prev_feat_l1_norm": 1638400.0, + "flowcache_accumulated_rel_l1": 0.017578125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 184, + "denoise_stage": 11, + "denoise_idx": 8, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.0654296875, + "flowcache_rel_l1_ratio": 0.06544117647058824, + "flowcache_delta_l1_norm": 91136.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0654296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 184, + "denoise_stage": 11, + "denoise_idx": 8, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 40, + "flowcache_rel_l1": 0.018798828125, + "flowcache_rel_l1_ratio": 0.018844221105527637, + "flowcache_delta_l1_norm": 30720.0, + "flowcache_prev_feat_l1_norm": 1630208.0, + "flowcache_accumulated_rel_l1": 0.018798828125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 185, + "denoise_stage": 11, + "denoise_idx": 9, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.0712890625, + "flowcache_rel_l1_ratio": 0.07095588235294117, + "flowcache_delta_l1_norm": 98816.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0712890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 185, + "denoise_stage": 11, + "denoise_idx": 9, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 41, + "flowcache_rel_l1": 0.020263671875, + "flowcache_rel_l1_ratio": 0.020145939086294418, + "flowcache_delta_l1_norm": 32512.0, + "flowcache_prev_feat_l1_norm": 1613824.0, + "flowcache_accumulated_rel_l1": 0.020263671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 186, + "denoise_stage": 11, + "denoise_idx": 10, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.07763671875, + "flowcache_rel_l1_ratio": 0.07757352941176471, + "flowcache_delta_l1_norm": 108032.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07763671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 186, + "denoise_stage": 11, + "denoise_idx": 10, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 42, + "flowcache_rel_l1": 0.021728515625, + "flowcache_rel_l1_ratio": 0.021634615384615384, + "flowcache_delta_l1_norm": 34560.0, + "flowcache_prev_feat_l1_norm": 1597440.0, + "flowcache_accumulated_rel_l1": 0.021728515625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 187, + "denoise_stage": 11, + "denoise_idx": 11, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08447265625, + "flowcache_rel_l1_ratio": 0.08455882352941177, + "flowcache_delta_l1_norm": 117760.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.08447265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 187, + "denoise_stage": 11, + "denoise_idx": 11, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 43, + "flowcache_rel_l1": 0.023193359375, + "flowcache_rel_l1_ratio": 0.023316062176165803, + "flowcache_delta_l1_norm": 36864.0, + "flowcache_prev_feat_l1_norm": 1581056.0, + "flowcache_accumulated_rel_l1": 0.023193359375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 188, + "denoise_stage": 11, + "denoise_idx": 12, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.09130859375, + "flowcache_rel_l1_ratio": 0.09156976744186046, + "flowcache_delta_l1_norm": 129024.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.09130859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 188, + "denoise_stage": 11, + "denoise_idx": 12, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 44, + "flowcache_rel_l1": 0.0250244140625, + "flowcache_rel_l1_ratio": 0.02490234375, + "flowcache_delta_l1_norm": 39168.0, + "flowcache_prev_feat_l1_norm": 1572864.0, + "flowcache_accumulated_rel_l1": 0.0250244140625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 189, + "denoise_stage": 11, + "denoise_idx": 13, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.09912109375, + "flowcache_rel_l1_ratio": 0.09928571428571428, + "flowcache_delta_l1_norm": 142336.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.09912109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 189, + "denoise_stage": 11, + "denoise_idx": 13, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 45, + "flowcache_rel_l1": 0.02685546875, + "flowcache_rel_l1_ratio": 0.026644736842105263, + "flowcache_delta_l1_norm": 41472.0, + "flowcache_prev_feat_l1_norm": 1556480.0, + "flowcache_accumulated_rel_l1": 0.02685546875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 190, + "denoise_stage": 11, + "denoise_idx": 14, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.1044921875, + "flowcache_rel_l1_ratio": 0.10497237569060773, + "flowcache_delta_l1_norm": 155648.0, + "flowcache_prev_feat_l1_norm": 1482752.0, + "flowcache_accumulated_rel_l1": 0.1044921875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 190, + "denoise_stage": 11, + "denoise_idx": 14, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 46, + "flowcache_rel_l1": 0.02880859375, + "flowcache_rel_l1_ratio": 0.02892287234042553, + "flowcache_delta_l1_norm": 44544.0, + "flowcache_prev_feat_l1_norm": 1540096.0, + "flowcache_accumulated_rel_l1": 0.02880859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 191, + "denoise_stage": 11, + "denoise_idx": 15, + "chunk_idx": 8, + "generated_chunk_idx": 8, + "chunk_denoise_count": 63, + "flowcache_rel_l1": 0.109375, + "flowcache_rel_l1_ratio": 0.10978835978835978, + "flowcache_delta_l1_norm": 169984.0, + "flowcache_prev_feat_l1_norm": 1548288.0, + "flowcache_accumulated_rel_l1": 0.109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 191, + "denoise_stage": 11, + "denoise_idx": 15, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 47, + "flowcache_rel_l1": 0.031005859375, + "flowcache_rel_l1_ratio": 0.031081989247311828, + "flowcache_delta_l1_norm": 47360.0, + "flowcache_prev_feat_l1_norm": 1523712.0, + "flowcache_accumulated_rel_l1": 0.031005859375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 192, + "denoise_stage": 12, + "denoise_idx": 0, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 48, + "flowcache_rel_l1": 0.033447265625, + "flowcache_rel_l1_ratio": 0.03345788043478261, + "flowcache_delta_l1_norm": 50432.0, + "flowcache_prev_feat_l1_norm": 1507328.0, + "flowcache_accumulated_rel_l1": 0.033447265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 193, + "denoise_stage": 12, + "denoise_idx": 1, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 49, + "flowcache_rel_l1": 0.0361328125, + "flowcache_rel_l1_ratio": 0.036401098901098904, + "flowcache_delta_l1_norm": 54272.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.0361328125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 194, + "denoise_stage": 12, + "denoise_idx": 2, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 50, + "flowcache_rel_l1": 0.039306640625, + "flowcache_rel_l1_ratio": 0.03940972222222222, + "flowcache_delta_l1_norm": 58112.0, + "flowcache_prev_feat_l1_norm": 1474560.0, + "flowcache_accumulated_rel_l1": 0.039306640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 195, + "denoise_stage": 12, + "denoise_idx": 3, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 51, + "flowcache_rel_l1": 0.042724609375, + "flowcache_rel_l1_ratio": 0.04266151685393258, + "flowcache_delta_l1_norm": 62208.0, + "flowcache_prev_feat_l1_norm": 1458176.0, + "flowcache_accumulated_rel_l1": 0.042724609375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 196, + "denoise_stage": 12, + "denoise_idx": 4, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 52, + "flowcache_rel_l1": 0.04638671875, + "flowcache_rel_l1_ratio": 0.04651988636363636, + "flowcache_delta_l1_norm": 67072.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.04638671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 197, + "denoise_stage": 12, + "denoise_idx": 5, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 53, + "flowcache_rel_l1": 0.050537109375, + "flowcache_rel_l1_ratio": 0.05035714285714286, + "flowcache_delta_l1_norm": 72192.0, + "flowcache_prev_feat_l1_norm": 1433600.0, + "flowcache_accumulated_rel_l1": 0.050537109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 198, + "denoise_stage": 12, + "denoise_idx": 6, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 54, + "flowcache_rel_l1": 0.054931640625, + "flowcache_rel_l1_ratio": 0.055274566473988436, + "flowcache_delta_l1_norm": 78336.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.054931640625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 199, + "denoise_stage": 12, + "denoise_idx": 7, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 55, + "flowcache_rel_l1": 0.0595703125, + "flowcache_rel_l1_ratio": 0.05995639534883721, + "flowcache_delta_l1_norm": 84480.0, + "flowcache_prev_feat_l1_norm": 1409024.0, + "flowcache_accumulated_rel_l1": 0.0595703125, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 200, + "denoise_stage": 12, + "denoise_idx": 8, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 56, + "flowcache_rel_l1": 0.0654296875, + "flowcache_rel_l1_ratio": 0.06542397660818713, + "flowcache_delta_l1_norm": 91648.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.0654296875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 201, + "denoise_stage": 12, + "denoise_idx": 9, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 57, + "flowcache_rel_l1": 0.0712890625, + "flowcache_rel_l1_ratio": 0.07169117647058823, + "flowcache_delta_l1_norm": 99840.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.0712890625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 202, + "denoise_stage": 12, + "denoise_idx": 10, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 58, + "flowcache_rel_l1": 0.07763671875, + "flowcache_rel_l1_ratio": 0.07794117647058824, + "flowcache_delta_l1_norm": 108544.0, + "flowcache_prev_feat_l1_norm": 1392640.0, + "flowcache_accumulated_rel_l1": 0.07763671875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 203, + "denoise_stage": 12, + "denoise_idx": 11, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 59, + "flowcache_rel_l1": 0.08447265625, + "flowcache_rel_l1_ratio": 0.0847953216374269, + "flowcache_delta_l1_norm": 118784.0, + "flowcache_prev_feat_l1_norm": 1400832.0, + "flowcache_accumulated_rel_l1": 0.08447265625, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 204, + "denoise_stage": 12, + "denoise_idx": 12, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 60, + "flowcache_rel_l1": 0.091796875, + "flowcache_rel_l1_ratio": 0.09176300578034682, + "flowcache_delta_l1_norm": 130048.0, + "flowcache_prev_feat_l1_norm": 1417216.0, + "flowcache_accumulated_rel_l1": 0.091796875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 205, + "denoise_stage": 12, + "denoise_idx": 13, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 61, + "flowcache_rel_l1": 0.09912109375, + "flowcache_rel_l1_ratio": 0.09943181818181818, + "flowcache_delta_l1_norm": 143360.0, + "flowcache_prev_feat_l1_norm": 1441792.0, + "flowcache_accumulated_rel_l1": 0.09912109375, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + }, + { + "infer_idx": 0, + "cur_denoise_step": 206, + "denoise_stage": 12, + "denoise_idx": 14, + "chunk_idx": 9, + "generated_chunk_idx": 9, + "chunk_denoise_count": 62, + "flowcache_rel_l1": 0.10498046875, + "flowcache_rel_l1_ratio": 0.10508241758241758, + "flowcache_delta_l1_norm": 156672.0, + "flowcache_prev_feat_l1_norm": 1490944.0, + "flowcache_accumulated_rel_l1": 0.10498046875, + "rel_l1_thresh": 0.015, + "reused": false, + "decision_reason": "threshold_exceeded" + } + ] +} \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/infer_2026-05-19_09-18-01.log b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/infer_2026-05-19_09-18-01.log new file mode 100644 index 0000000000000000000000000000000000000000..ddb800627d565cd51be2bc47e2c77f1dac980815 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing/infer_2026-05-19_09-18-01.log @@ -0,0 +1,223 @@ +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W519 09:18:09.994595319 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-05-19 09:18:09,596 - INFO] Initialize torch distribution and model parallel successfully +[2026-05-19 09:18:09,597 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-05-19 09:18:09,597 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'rel_l1_thresh': 0.015, 'warmup_steps': 5, 'discard_nearly_clean_chunk': True, 'compress_kv_cache': True, 'total_cache_chunk_nums': 5, 'compress_strategy': 'token', 'mix_lambda': 0.07, 'query_granularity': 'frame', 'score_weighting_method': 'no_weight', 'power': 3, 'log': True, 'print_peak_memory': True, 'debug': False} +Added to args: rel_l1_thresh = 0.015 +Added to args: warmup_steps = 5 +Added to args: discard_nearly_clean_chunk = True +Added to args: compress_kv_cache = True +Added to args: total_cache_chunk_nums = 5 +Added to args: compress_strategy = token +Added to args: mix_lambda = 0.07 +Added to args: query_granularity = frame +Added to args: score_weighting_method = no_weight +Added to args: power = 3 +Added to args: log = True +Added to args: print_peak_memory = True +Added to args: debug = False +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'rel_l1_thresh': 0.015, 'warmup_steps': 5, 'discard_nearly_clean_chunk': True, 'compress_kv_cache': True, 'total_cache_chunk_nums': 5, 'compress_strategy': 'token', 'mix_lambda': 0.07, 'query_granularity': 'frame', 'score_weighting_method': 'no_weight', 'power': 3, 'log': True, 'print_peak_memory': True, 'debug': False} +Added to args: rel_l1_thresh = 0.015 +Added to args: warmup_steps = 5 +Added to args: discard_nearly_clean_chunk = True +Added to args: compress_kv_cache = True +Added to args: total_cache_chunk_nums = 5 +Added to args: compress_strategy = token +Added to args: mix_lambda = 0.07 +Added to args: query_granularity = frame +Added to args: score_weighting_method = no_weight +Added to args: power = 3 +Added to args: log = True +Added to args: print_peak_memory = True +Added to args: debug = False +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB allocated + Loading checkpoint shards: 0%| | 0/2 [00:00 +[rank0]: main() +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py", line 81, in main +[rank0]: pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 47, in run_text_to_video +[rank0]: self._run(prompt, None, output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in _run +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1357, in generate_per_chunk +[rank0]: for _, _, chunk in sample_transport.walk(): +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1327, in walk +[rank0]: velocity = self.forward_velocity(work_status.infer_idx, work_status.cur_denoise_step + 1) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1171, in forward_velocity +[rank0]: velocity = forward_fn( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 573, in forward_dispatcher +[rank0]: cat_out = self.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 399, in forward +[rank0]: x = self.videodit_blocks.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1585, in forward +[rank0]: hidden_states = layer( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1473, in forward +[rank0]: hidden_states = self.attn_post_process(core_attn_out, cross_attn_out, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1486, in attn_post_process +[rank0]: hidden_states = self.gating_and_mlp(hidden_states, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1520, in gating_and_mlp +[rank0]: hidden_states = self.mlp(hidden_states) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 554, in forward +[rank0]: hidden_states = torch.nn.functional.gelu(hidden_states) +[rank0]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.67 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.66 GiB is free. Including non-PyTorch memory, this process has 30.81 GiB memory in use. Process 565617 has 46.62 GiB memory in use. Of the allocated memory 29.34 GiB is allocated by PyTorch, and 427.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) + InferBatch 0: 10%|█ | 1/10 [06:46<1:00:59, 406.58s/it] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-11-32/infer_2026-06-12_16-11-32.log b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-11-32/infer_2026-06-12_16-11-32.log new file mode 100644 index 0000000000000000000000000000000000000000..ce16dae4ffa75a4700197a3908f10d8808ec12f8 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-11-32/infer_2026-06-12_16-11-32.log @@ -0,0 +1,68 @@ +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W612 16:11:38.402380501 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-06-12 16:11:38,097 - INFO] Initialize torch distribution and model parallel successfully +[2026-06-12 16:11:38,097 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-06-12 16:11:38,097 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB allocated + Loading checkpoint shards: 0%| | 0/2 [00:00 +[rank0]: main() +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py", line 81, in main +[rank0]: pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 47, in run_text_to_video +[rank0]: self._run(prompt, None, output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in _run +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1357, in generate_per_chunk +[rank0]: for _, _, chunk in sample_transport.walk(): +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1327, in walk +[rank0]: velocity = self.forward_velocity(work_status.infer_idx, work_status.cur_denoise_step + 1) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1171, in forward_velocity +[rank0]: velocity = forward_fn( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 573, in forward_dispatcher +[rank0]: cat_out = self.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 399, in forward +[rank0]: x = self.videodit_blocks.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1585, in forward +[rank0]: hidden_states = layer( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1473, in forward +[rank0]: hidden_states = self.attn_post_process(core_attn_out, cross_attn_out, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1486, in attn_post_process +[rank0]: hidden_states = self.gating_and_mlp(hidden_states, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1520, in gating_and_mlp +[rank0]: hidden_states = self.mlp(hidden_states) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 554, in forward +[rank0]: hidden_states = torch.nn.functional.gelu(hidden_states) +[rank0]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.67 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.66 GiB is free. Including non-PyTorch memory, this process has 30.81 GiB memory in use. Process 576875 has 46.62 GiB memory in use. Of the allocated memory 29.34 GiB is allocated by PyTorch, and 427.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) + InferBatch 0: 10%|█ | 1/10 [05:46<51:54, 346.10s/it] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-18-14/infer_2026-06-12_16-18-14.log b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-18-14/infer_2026-06-12_16-18-14.log new file mode 100644 index 0000000000000000000000000000000000000000..3fdf11e5252178408e09dac0d1504c05d95e663b --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-18-14/infer_2026-06-12_16-18-14.log @@ -0,0 +1,68 @@ +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W612 16:18:20.531242725 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-06-12 16:18:20,226 - INFO] Initialize torch distribution and model parallel successfully +[2026-06-12 16:18:20,226 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-06-12 16:18:20,226 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB allocated + Loading checkpoint shards: 0%| | 0/2 [00:00 +[rank0]: main() +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/entry.py", line 81, in main +[rank0]: pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 47, in run_text_to_video +[rank0]: self._run(prompt, None, output_path) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in _run +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/pipeline.py", line 61, in +[rank0]: [ +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1357, in generate_per_chunk +[rank0]: for _, _, chunk in sample_transport.walk(): +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1327, in walk +[rank0]: velocity = self.forward_velocity(work_status.infer_idx, work_status.cur_denoise_step + 1) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/pipeline/video_generate.py", line 1171, in forward_velocity +[rank0]: velocity = forward_fn( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 573, in forward_dispatcher +[rank0]: cat_out = self.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_model.py", line 399, in forward +[rank0]: x = self.videodit_blocks.forward( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context +[rank0]: return func(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1585, in forward +[rank0]: hidden_states = layer( +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1473, in forward +[rank0]: hidden_states = self.attn_post_process(core_attn_out, cross_attn_out, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1486, in attn_post_process +[rank0]: hidden_states = self.gating_and_mlp(hidden_states, residual, condition, condition_map) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 1520, in gating_and_mlp +[rank0]: hidden_states = self.mlp(hidden_states) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl +[rank0]: return self._call_impl(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl +[rank0]: return forward_call(*args, **kwargs) +[rank0]: File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev-V2/inference/model/dit/dit_module.py", line 554, in forward +[rank0]: hidden_states = torch.nn.functional.gelu(hidden_states) +[rank0]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.67 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.66 GiB is free. Including non-PyTorch memory, this process has 30.81 GiB memory in use. Process 582212 has 46.62 GiB memory in use. Of the allocated memory 29.34 GiB is allocated by PyTorch, and 427.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) + InferBatch 0: 10%|█ | 1/10 [05:41<51:11, 341.29s/it] diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-25-27/infer_2026-06-12_16-25-27.log b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-25-27/infer_2026-06-12_16-25-27.log new file mode 100644 index 0000000000000000000000000000000000000000..3b77174021edecead17ed6297e66138a30a9cec6 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/outputs/a_woman_dancing_token_heterogeneity_2026-06-12_16-25-27/infer_2026-06-12_16-25-27.log @@ -0,0 +1,37 @@ +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W612 16:25:34.392444672 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-06-12 16:25:34,098 - INFO] Initialize torch distribution and model parallel successfully +[2026-06-12 16:25:34,098 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-06-12 16:25:34,098 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB allocated + Loading checkpoint shards: 0%| | 0/2 [00:00 >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Run sampling +python sample_video.py "$YAML_CONFIG" + +if [ $? -eq 0 ]; then + echo "✅ Sampling completed successfully." +else + echo "❌ Sampling failed. Check log: $LOG_FILE" + exit 1 +fi + +echo "---" +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/flowcache_vbench.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/flowcache_vbench.sh new file mode 100644 index 0000000000000000000000000000000000000000..85dc6ea8c4f96940985d61c6418f51546af9e825 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/flowcache_vbench.sh @@ -0,0 +1,80 @@ +#!/bin/bash + +# FlowCache VBench sampling script +# Usage: bash flowcache_vbench.sh [yaml_config_path] +# Default config: yaml_config/sample/flowcache_vbench.yaml + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/flowcache_vbench.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/flowcache_vbench_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" + +# Define list of dimensions to process +DIMENSIONS=("overall_consistency" "subject_consistency" "scene") + +echo "🔢 Total dimensions to process: ${#DIMENSIONS[@]}" +echo "📋 Dimensions: ${DIMENSIONS[*]}" + +# Loop through each dimension +for DIMENSION in "${DIMENSIONS[@]}"; do + echo "🔍 Processing dimension: $DIMENSION" + + # Use Python to temporarily modify the dimension in YAML, then run sampling + python3 -c " +import yaml +import sys + +# Read YAML config +with open('$YAML_CONFIG', 'r') as f: + config = yaml.safe_load(f) + +# Modify dimension +config['dimension'] = '$DIMENSION' + +# Save to temporary file +temp_config = '$YAML_CONFIG.tmp' +with open(temp_config, 'w') as f: + yaml.dump(config, f, default_flow_style=False) +print(temp_config) +" > /tmp/temp_config_path.txt + + TEMP_CONFIG=$(cat /tmp/temp_config_path.txt) + python sample_video.py "$TEMP_CONFIG" + rm "$TEMP_CONFIG" + + if [ $? -eq 0 ]; then + echo "✅ Completed: $DIMENSION" + else + echo "❌ Failed: $DIMENSION" + echo "🛑 Script paused due to error. Fix the issue and rerun." + exit 1 + fi + + echo "---" +done + +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_physicsiq.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_physicsiq.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4d0ffc2ce5fe7c329ff0cb766d56a28d6b289b4 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_physicsiq.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +# TeaCache PhysicsIQ sampling script +# Usage: bash teacache_physicsiq.sh [yaml_config_path] +# Default config: yaml_config/sample/teacache_physicsiq.yaml + +export DEVICES="0,1,2,3,4,5,6,7" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +export XDG_CACHE_HOME="/path/to/tmp" +mkdir -p "$XDG_CACHE_HOME" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/teacache_physicsiq.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/teacache_physicsiq_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Run sampling +python sample_video.py "$YAML_CONFIG" + +if [ $? -eq 0 ]; then + echo "✅ Sampling completed successfully." +else + echo "❌ Sampling failed. Check log: $LOG_FILE" + exit 1 +fi + +echo "---" +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_vbench.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_vbench.sh new file mode 100644 index 0000000000000000000000000000000000000000..196d31a912ad4f83040091376e2032e9c78f0dab --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/sample/teacache_vbench.sh @@ -0,0 +1,82 @@ +#!/bin/bash + +# TeaCache VBench sampling script +# Usage: bash teacache_vbench.sh [yaml_config_path] +# Default config: yaml_config/sample/teacache_vbench.yaml + +export DEVICES="4,5,7" + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +export MAGI_ROOT="$MAGI_ROOT" + +# YAML config file path (can be overridden via command line argument) +YAML_CONFIG="${1:-yaml_config/sample/teacache_vbench.yaml}" + +if [ ! -f "$YAML_CONFIG" ]; then + echo "❌ YAML config file not found: $YAML_CONFIG" + exit 1 +fi + +echo "📋 Using YAML config: $YAML_CONFIG" + +# Create log directory +LOG_DIR="./logs" +mkdir -p "$LOG_DIR" +LOG_FILE="$LOG_DIR/teacache_vbench_$(date +%Y%m%d_%H%M%S).log" +exec > >(tee -a "$LOG_FILE") 2>&1 + +echo "🚀 Starting multi-GPU benchmark sampling" +echo "🎮 GPUs: $DEVICES" + +# Define list of dimensions to process +DIMENSIONS=("overall_consistency" "subject_consistency" "scene") + +echo "🔢 Total dimensions to process: ${#DIMENSIONS[@]}" + +# Loop through each dimension +for DIMENSION in "${DIMENSIONS[@]}"; do + echo "📌 Processing dimension: $DIMENSION" + + # Use Python to temporarily modify the dimension in YAML, then run sampling + python3 -c " +import yaml +import sys + +# Read YAML config +with open('$YAML_CONFIG', 'r') as f: + config = yaml.safe_load(f) + +# Modify dimension +config['dimension'] = '$DIMENSION' + +# Save to temporary file +temp_config = '$YAML_CONFIG.tmp' +with open(temp_config, 'w') as f: + yaml.dump(config, f, default_flow_style=False) +print(temp_config) +" > /tmp/temp_config_path.txt + + TEMP_CONFIG=$(cat /tmp/temp_config_path.txt) + python sample_video.py "$TEMP_CONFIG" + rm "$TEMP_CONFIG" + + if [ $? -eq 0 ]; then + echo "✅ Successfully completed: $DIMENSION" + else + echo "❌ Failed: $DIMENSION" + echo "🛑 Script paused due to error. Fix the issue and rerun." + exit 1 + fi + + echo "---" +done + +echo "🎉 All sampling tasks completed." diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_t2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7bf9910fcc4c4bcf401f9ef16c444808d495936 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_t2v.sh @@ -0,0 +1,119 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6005 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=0 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +cd "$MAGI_ROOT" + +PROMPT="${PROMPT:-a woman dancing.}" +TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}" +PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY' +import re +import sys +import unicodedata + +prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip() +prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt) +prompt = re.sub(r"\s+", "_", prompt) +prompt = prompt.strip("._") +print((prompt or "prompt")[:120]) +PY +)}" +OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}" +EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_$TIMESTAMP}" +mkdir -p "$EXP_DIR" + +OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}" +RESIDUAL_JSON="${RESIDUAL_JSON:-$EXP_DIR/residual_stats_$TIMESTAMP.json}" +RESIDUAL_PNG="${RESIDUAL_PNG:-$EXP_DIR/residual_norms_$TIMESTAMP.png}" +L1_REL_JSON="${L1_REL_JSON:-$EXP_DIR/l1_rel_stats_$TIMESTAMP.json}" +L1_REL_PNG="${L1_REL_PNG:-$EXP_DIR/l1_rel_$TIMESTAMP.png}" +L1_REL_RATIO_PNG="${L1_REL_RATIO_PNG:-$EXP_DIR/l1_rel_ratio_$TIMESTAMP.png}" +X_EMBEDDER_L1_REL_PNG="${X_EMBEDDER_L1_REL_PNG:-$EXP_DIR/x_embedder_l1_rel_$TIMESTAMP.png}" +X_EMBEDDER_L1_REL_RATIO_PNG="${X_EMBEDDER_L1_REL_RATIO_PNG:-$EXP_DIR/x_embedder_l1_rel_ratio_$TIMESTAMP.png}" +FLOWCACHE_METRIC_JSON="${FLOWCACHE_METRIC_JSON:-$EXP_DIR/flowcache_metric_stats_$TIMESTAMP.json}" +FLOWCACHE_REL_L1_PNG="${FLOWCACHE_REL_L1_PNG:-$EXP_DIR/flowcache_rel_l1_$TIMESTAMP.png}" +FLOWCACHE_REL_L1_RATIO_PNG="${FLOWCACHE_REL_L1_RATIO_PNG:-$EXP_DIR/flowcache_rel_l1_ratio_$TIMESTAMP.png}" +FLOWCACHE_ACCUMULATED_REL_L1_PNG="${FLOWCACHE_ACCUMULATED_REL_L1_PNG:-$EXP_DIR/flowcache_accumulated_rel_l1_$TIMESTAMP.png}" +LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}" + +export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}" +python3 inference/pipeline/flowcache.py \ + --config_file config/single_run/flowcache_t2v.json \ + --mode t2v \ + --prompt "$PROMPT" \ + --output_path "$OUTPUT_PATH" \ + --additional_config yaml_config/single_run/config.yaml \ + --residual_stats_path "$RESIDUAL_JSON" \ + --l1_rel_stats_path "$L1_REL_JSON" \ + --flowcache_metric_stats_path "$FLOWCACHE_METRIC_JSON" \ + 2>&1 | tee "$LOG_FILE" + +python3 tools/plot_residual_norms.py "$RESIDUAL_JSON" -o "$RESIDUAL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" -o "$L1_REL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field l1_rel_ratio -o "$L1_REL_RATIO_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel -o "$X_EMBEDDER_L1_REL_PNG" +python3 tools/plot_l1_rel.py "$L1_REL_JSON" --y-field x_embedder_l1_rel_ratio -o "$X_EMBEDDER_L1_REL_RATIO_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_rel_l1 -o "$FLOWCACHE_REL_L1_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_rel_l1_ratio -o "$FLOWCACHE_REL_L1_RATIO_PNG" +python3 tools/plot_l1_rel.py "$FLOWCACHE_METRIC_JSON" --x-field cur_denoise_step --y-field flowcache_accumulated_rel_l1 -o "$FLOWCACHE_ACCUMULATED_REL_L1_PNG" + +python3 - "$FLOWCACHE_METRIC_JSON" <<'PY' +import json +import sys + +with open(sys.argv[1], "r") as f: + payload = json.load(f) + +summary = payload.get("chunk_execution_summary", {}) +print("FlowCache actual execution summary:") +for chunk_id in sorted(summary, key=lambda value: int(value)): + item = summary[chunk_id] + print( + " chunk {chunk_idx}: reuse={reuse_steps}, compute={compute_steps}, " + "total={total_steps}, reuse_rate={reuse_rate:.2%}".format(**item) + ) +PY + +echo "Done." +echo " log: $LOG_FILE" +echo " video: $OUTPUT_PATH" +echo " residual json: $RESIDUAL_JSON" +echo " residual plot: $RESIDUAL_PNG" +echo " L1 rel json: $L1_REL_JSON" +echo " L1 rel plot: $L1_REL_PNG" +echo " L1 rel ratio plot: $L1_REL_RATIO_PNG" +echo " x_embedder L1 rel plot: $X_EMBEDDER_L1_REL_PNG" +echo " x_embedder L1 rel ratio plot: $X_EMBEDDER_L1_REL_RATIO_PNG" +echo " FlowCache metric json: $FLOWCACHE_METRIC_JSON" +echo " FlowCache rel L1 plot: $FLOWCACHE_REL_L1_PNG" +echo " FlowCache rel L1 ratio plot: $FLOWCACHE_REL_L1_RATIO_PNG" +echo " FlowCache accumulated rel L1 plot: $FLOWCACHE_ACCUMULATED_REL_L1_PNG" diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_v2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6867ddc351383f193685fdea417c6f57058e0f9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/flowcache_v2v.sh @@ -0,0 +1,51 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6001 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=7 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=flowcache +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/flowcache.py \ + --config_file config/single_run/flowcache_v2v.json \ + --mode v2v \ + --prompt "Two pillows on a table and two grabber tools hanging above them from which a brown tennis ball and an orange block are suspended. The grabber tools let go of the ball and block. Static shot with no camera movement." \ + --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \ + --output_path $OUTPUT_PATH \ + --additional_config addconfig/config.yaml \ + 2>&1 | tee $LOG_FILE + +# a cat sitting on the grass diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_t2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..e01f11f55fdbcb27fdebb14fffd4940517668db0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_t2v.sh @@ -0,0 +1,50 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6002 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=2 + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=allreuse +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +exec > >(tee -a "$LOG_FILE") 2>&1 +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/teacache_all.py \ + --rel_l1_thresh 0.01 \ + --warmup_steps 5 \ + --config_file config/single_run/flowcache_t2v.json \ + --mode t2v \ + --prompt "A fantasy landscape" \ + --log \ + --output_path $OUTPUT_PATH \ \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_v2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..d99fb479b9811b6ca93d23a73cdf9f3654ecf4eb --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/teacache_v2v.sh @@ -0,0 +1,52 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +export MASTER_ADDR=localhost +export MASTER_PORT=6012 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=1 +export CUDA_HOME="/usr/local/cuda-12.1" + +export PAD_HQ=1 +export PAD_DURATION=1 + +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +MAGI_ROOT=$(git rev-parse --show-toplevel) + + +OUTPUT_NAME=allreuse +TIMESTAMP=$(date "+%Y-%m-%d_%H-%M-%S") +EXP_DIR="/path/to/output/magi/${TIMESTAMP}_${OUTPUT_NAME}" +mkdir -p "$EXP_DIR" + +LOG_FILE="$EXP_DIR/log_${TIMESTAMP}.log" +exec > >(tee -a "$LOG_FILE") 2>&1 +OUTPUT_PATH="$EXP_DIR/output.mp4" + +export PYTHONPATH="$MAGI_ROOT:$PYTHONPATH" +python3 inference/pipeline/teacache_all.py \ + --rel_l1_thresh 0.01 \ + --warmup_steps 5 \ + --config_file config/single_run/all_reuse.json \ + --mode v2v \ + --prompt "Two pillows on a table and two grabber tools hanging above them from which a brown tennis ball and an orange block are suspended. The grabber tools let go of the ball and block. Static shot with no camera movement." \ + --prefix_video_path "/path/to/physicsiq/conditioning_video.mp4" \ + --output_path $OUTPUT_PATH \ + --log \ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/token_heterogeneity_t2v.sh b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/token_heterogeneity_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..fd6302d07320aefb65138e9b15fb04a86fc7b199 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/scripts/single_run/token_heterogeneity_t2v.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Collect per-token L2 norm change-rate stats for chunk 0 and plot the density curve. +# Usage: bash scripts/single_run/token_heterogeneity_t2v.sh + +export MASTER_ADDR=localhost +export MASTER_PORT=6006 +export GPUS_PER_NODE=1 +export NNODES=1 +export WORLD_SIZE=1 +export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES:-0} + +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true +export TORCH_CUDA_ARCH_LIST="8.9;9.0" + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MAGI_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +cd "$MAGI_ROOT" + +PROMPT="${PROMPT:-a woman dancing.}" +TIMESTAMP="${RUN_ID:-$(date "+%Y-%m-%d_%H-%M-%S")}" +PROMPT_DIR_NAME="${PROMPT_DIR_NAME:-$(python3 - "$PROMPT" <<'PY' +import re +import sys +import unicodedata + +prompt = unicodedata.normalize("NFKC", sys.argv[1]).strip() +prompt = re.sub(r"[\\/:\*\?\"<>\|\x00-\x1f]+", "_", prompt) +prompt = re.sub(r"\s+", "_", prompt) +prompt = prompt.strip("._") +print((prompt or "prompt")[:120]) +PY +)}" +OUTPUT_ROOT="${OUTPUT_ROOT:-outputs}" +EXP_DIR="${RUN_DIR:-$OUTPUT_ROOT/${PROMPT_DIR_NAME}_token_heterogeneity_$TIMESTAMP}" +mkdir -p "$EXP_DIR" + +OUTPUT_PATH="${OUTPUT_PATH:-$EXP_DIR/output_$TIMESTAMP.mp4}" +TOKEN_STATS_JSON="${TOKEN_STATS_JSON:-$EXP_DIR/token_l2_change_rate_chunk0_$TIMESTAMP.json}" +TOKEN_DENSITY_PNG="${TOKEN_DENSITY_PNG:-$EXP_DIR/token_l2_change_rate_density_chunk0_$TIMESTAMP.png}" +LOG_FILE="${LOG_FILE:-$EXP_DIR/infer_$TIMESTAMP.log}" +CHUNK_IDX="${CHUNK_IDX:-0}" + +export PYTHONPATH="$MAGI_ROOT:${PYTHONPATH:-}" +python3 inference/pipeline/entry.py \ + --config_file config/single_run/flowcache_t2v.json \ + --mode t2v \ + --prompt "$PROMPT" \ + --output_path "$OUTPUT_PATH" \ + --token_l2_change_rate_stats_path "$TOKEN_STATS_JSON" \ + --token_l2_change_rate_chunk_idx "$CHUNK_IDX" \ + --print_peak_memory \ + 2>&1 | tee "$LOG_FILE" + +python3 tools/plot_token_l2_change_rate_density.py \ + "$TOKEN_STATS_JSON" \ + -o "$TOKEN_DENSITY_PNG" \ + --chunk-idx "$CHUNK_IDX" + +echo "Done." +echo " log: $LOG_FILE" +echo " video: $OUTPUT_PATH" +echo " token stats json: $TOKEN_STATS_JSON" +echo " density plot: $TOKEN_DENSITY_PNG" diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_l1_rel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_l1_rel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e85d201a85bc30be7690f33a0276cc3134397c8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_l1_rel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_residual_norms.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_residual_norms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8453b79cd8122069b9c3886294fe9399dd435f7c Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_residual_norms.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_token_l2_change_rate_density.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_token_l2_change_rate_density.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42b10395c7eb59c3cd7cc977c1863846ab40fbe4 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev-V2/tools/__pycache__/plot_token_l2_change_rate_density.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_physicsiq.yaml b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_physicsiq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..81433ce4c0d4aaedf738e6502e90ca9c5c93fb20 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_physicsiq.yaml @@ -0,0 +1,36 @@ +# FlowCache PhysicsIQ configuration file +# Usage: bash scripts/sample/flowcache_physicsiq.sh + +# Basic configuration +benchmark: physicsiq +config_file: config/sample/5s_physicsiq.json + +# GPU configuration +gpus: all + +# PhysicsIQ dataset configuration +physicsiq_data_dir: /path/to/physicsiq + +# Output path configuration +base_save_path: /path/to/output/physicsiq + +# Reuse strategy configuration +reuse_strategy: chunkwise +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# KV cache compression configuration +compress_kv_cache: true +total_cache_chunk_nums: 6 +compress_strategy: token +query_granularity: token +mix_lambda: 0.07 +score_weighting_method: no_weight +power: 3 + +# Sampling range control +start: 150 +end: 200 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_vbench.yaml b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_vbench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..85cd1d240495f6b169bedfcde8a407166f6b3f32 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/flowcache_vbench.yaml @@ -0,0 +1,36 @@ +# FlowCache VBench configuration file +# Usage: bash scripts/sample/flowcache_vbench.sh + +# Basic configuration +benchmark: vbench +config_file: config/sample/vbench.json + +# GPU configuration +gpus: all + +# VBench dataset configuration +vbench_prompt_dir: downloads/vbench/prompts_per_dimension + +# Dimension configuration (specify the current dimension to process) +dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style + +# Output path configuration +base_save_path: outputs/vbench + +# Reuse strategy configuration +reuse_strategy: chunkwise +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# KV cache compression configuration +compress_kv_cache: true +total_cache_chunk_nums: 6 +budget_cache_chunk_nums: 1 +compress_strategy: token +query_granularity: chunk +mix_lambda: 0.07 +score_weighting_method: no_weight +discard_nearly_clean_chunk: true + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_physicsiq.yaml b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_physicsiq.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0dbfcb540039e515a0196bf90b360317b814ca9 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_physicsiq.yaml @@ -0,0 +1,23 @@ +# TeaCache PhysicsIQ configuration file +# Usage: bash scripts/sample/teacache_physicsiq.sh + +# Basic configuration +benchmark: physicsiq +config_file: config/sample/5s_physicsiq.json + +# GPU configuration +gpus: all + +# PhysicsIQ dataset configuration +physicsiq_data_dir: /path/to/physicsiq + +# Output path configuration +base_save_path: /path/to/output/physicsiq + +# Reuse strategy configuration +reuse_strategy: all +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_vbench.yaml b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_vbench.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f6783e30de2788738b58a1c85124931a3f7d8a2b --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/sample/teacache_vbench.yaml @@ -0,0 +1,26 @@ +# TeaCache VBench configuration file +# Usage: bash scripts/sample/teacache_vbench.sh + +# Basic configuration +benchmark: vbench +config_file: config/sample/vbench.json + +# GPU configuration +gpus: all + +# VBench dataset configuration +vbench_prompt_dir: downloads/vbench/prompts_per_dimension + +# Dimension configuration (specify the current dimension to process) +dimension: overall_consistency # Options: subject_consistency, scene, object_class, multiple_objects, color, spatial_relationship, temporal_style, human_action, temporal_flickering, appearance_style + +# Output path configuration +base_save_path: /path/to/output/vbench + +# Reuse strategy configuration +reuse_strategy: all +rel_l1_thresh: 0.01 +warmup_steps: 5 + +# Log configuration +log: false diff --git a/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/single_run/config.yaml b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/single_run/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78463d84ae51ccc251f9272651f299a997feba54 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev-V2/yaml_config/single_run/config.yaml @@ -0,0 +1,15 @@ +rel_l1_thresh: 0.015 +warmup_steps: 5 +discard_nearly_clean_chunk: true + +compress_kv_cache: true +total_cache_chunk_nums: 5 +compress_strategy: token +mix_lambda: 0.07 +query_granularity: frame +score_weighting_method: no_weight +power: 3 + +log: true +print_peak_memory: true +debug: false \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/physicsiq.json b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/physicsiq.json new file mode 100644 index 0000000000000000000000000000000000000000..17df1b44b67824c0a3d5db952fa8a1de7c3c9ba1 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/physicsiq.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 120, + "video_size_h": 720, + "video_size_w": 1280, + "num_steps": 64, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": true, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/vbench.json b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/vbench.json new file mode 100644 index 0000000000000000000000000000000000000000..e549246b9b7757b12bb8822bac18da3345e41e3e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/sample/vbench.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 240, + "video_size_h": 720, + "video_size_w": 720, + "num_steps": 16, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": true, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json new file mode 100644 index 0000000000000000000000000000000000000000..6b0762dad4dc5ec0263248699721f97cd6feef9d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json @@ -0,0 +1,81 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 240, + "video_size_h": 720, + "video_size_w": 720, + "num_steps": 64, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": false, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_v2v.json b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_v2v.json new file mode 100644 index 0000000000000000000000000000000000000000..cdc9001264bce5c7ad72c2430b47540c9b8c85da --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_v2v.json @@ -0,0 +1,86 @@ +{ + "model_config": { + "model_name": "videodit_ardf", + "num_layers": 34, + "hidden_size": 3072, + "ffn_hidden_size": 12288, + "num_attention_heads": 24, + "num_query_groups": 8, + "kv_channels": 128, + "layernorm_epsilon": 1e-06, + "apply_layernorm_1p": true, + "x_rescale_factor": 1, + "half_channel_vae": false, + "params_dtype": "torch.bfloat16", + "patch_size": 2, + "t_patch_size": 1, + "in_channels": 16, + "out_channels": 16, + "cond_hidden_ratio": 0.25, + "caption_channels": 4096, + "caption_max_length": 800, + "xattn_cond_hidden_ratio": 1.0, + "cond_gating_ratio": 1.0, + "gated_linear_unit": false + }, + "runtime_config": { + "cfg_number": 1, + "cfg_t_range": [ + 0.0, + 0.0217, + 0.1, + 0.3, + 0.999 + ], + "prev_chunk_scales": [ + 1.5, + 1.5, + 1.5, + 1.0, + 1.0 + ], + "text_scales": [ + 7.5, + 7.5, + 7.5, + 0.0, + 0.0 + ], + "noise2clean_kvrange": [ + 5, + 4, + 3, + 2 + ], + "clean_chunk_kvrange": 1, + "clean_t": 0.9999, + "seed": 1234, + "num_frames": 120, + "video_size_h": 720, + "video_size_w": 1280, + "num_steps": 8, + "window_size": 4, + "fps": 24, + "chunk_width": 6, + "load": "./downloads/4.5B_distill", + "t5_pretrained": "./downloads/t5_pretrained", + "t5_device": "cuda", + "vae_pretrained": "./downloads/vae", + "scale_factor": 0.18215, + "temporal_downsample_factor": 4 + }, + "engine_config": { + "distributed_backend": "nccl", + "distributed_timeout_minutes": 15, + "pp_size": 1, + "cp_size": 1, + "cp_strategy": "none", + "ulysses_overlap_degree": 1, + "fp8_quant": false, + "distill_nearly_clean_chunk_threshold": 0.3, + "shortcut_mode": "8,16,16", + "distill": true, + "kv_offload": false, + "enable_cuda_graph": false + } +} diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..771cd9f029178bb256d7c6cf3d227398ec5343f8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5190c57dcd4c060701be30119eecf14958780ccc Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..882ab751a039e9bc8fedd086c9b81e0e38110ed8 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .common_utils import divide, env_is_true, set_random_seed +from .config import EngineConfig, MagiConfig, ModelConfig, RuntimeConfig +from .dataclass import InferenceParams, ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams +from .logger import magi_logger, print_per_rank, print_rank_0 +from .timer import event_path_timer + +__all__ = [ + "MagiConfig", + "ModelConfig", + "EngineConfig", + "RuntimeConfig", + "magi_logger", + "print_per_rank", + "print_rank_0", + "event_path_timer", + "divide", + "env_is_true", + "set_random_seed", + "PackedCoreAttnParams", + "PackedCrossAttnParams", + "ModelMetaArgs", + "InferenceParams", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03a563bc073381865021a121a7040d2b04b36069 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..817f7f6d42c72b3b5b6ca16ddad0c8cb5ab0c134 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b3b9dff246a55294fc24418d078d09917d9890 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c323c31b2ea8bc0e158c26e7a796ad7fd46f885d Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/common_utils.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24656370941e92345750ef87690751c1674ca525 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a533078861a05bbd7c59ac3120d4055037cdd425 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/config.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62f0c2be51975477d8086b8ccf6c556baefb72db Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb8b8505df5e4060d8a33597781627926d6f77fe Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/dataclass.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78d5167bebef8cda35cdffa537f04f05d63f5c0f Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f6527b3655b06df43bfc838fa0784c823fb655 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/logger.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69ec0f2afb324a54bdb7af04f0e98b20499b304f Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f76e61d98e7ff344f84a1fa6cb9da549b78d4a8 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/__pycache__/timer.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/common_utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/common_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d3960150c93d595881e6d0be281ec5ffb0c22f73 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/common_utils.py @@ -0,0 +1,42 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import random + +import numpy as np +import torch + + +def env_is_true(env_name: str) -> bool: + return str(os.environ.get(env_name, "0")).lower() in {"1", "true", "yes", "y", "on", "enabled"} + + +def divide(numerator, denominator): + assert numerator % denominator == 0, "{} is not divisible by {}".format(numerator, denominator) + return numerator // denominator + + +def set_random_seed(seed): + """Set random seed. + + Args: + seed (int): Seed to be used. + """ + assert seed is not None, "Please provide a seed in config.json" + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + return seed diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/config.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a71ab92f693ad4c64f684e0ee45581db2a2a60df --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/config.py @@ -0,0 +1,180 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import json +import os + +import torch + + +@dataclasses.dataclass +class ModelConfig: + model_name: str + + # Transformer + num_layers: int = None # Number of transformer layers. + hidden_size: int = None # Transformer hidden size. + ffn_hidden_size: int = None # Transformer Feed-Forward Network hidden size + num_attention_heads: int = None # Number of transformer attention heads. + num_query_groups: int = 1 # Number of query groups, which used for GQA + kv_channels: int = None # Projection weights dimension in multi-head attention + layernorm_epsilon: float = 1e-6 # Epsilon for layer norm and RMS norm. + apply_layernorm_1p: bool = False # Adjust LayerNorm weights which improves numerical stability. + x_rescale_factor: float = 1.0 + half_channel_vae: bool = False + params_dtype: torch.dtype = None + + # Embedding + patch_size: int = 2 # (latent) patch size for DiT patch embedding layer + t_patch_size: int = 1 # (latent) patch size for t dim patch embedding layer + in_channels: int = 4 # latent input channel for DiT + out_channels: int = 4 # latent output channel for DiT + cond_hidden_ratio: float = 0.25 + caption_channels: int = 4096 + caption_max_length: int = 800 + xattn_cond_hidden_ratio: float = 1.0 + cond_gating_ratio: float = 1.0 + gated_linear_unit: bool = False + + +@dataclasses.dataclass +class RuntimeConfig: + # Inference settings such as cfg, kv range, clean t, etc. + cfg_number: int = None # Number of CFG + cfg_t_range: list = dataclasses.field( + default_factory=lambda: [0, 0.0217, 0.1000, 0.3, 0.999] + ) # CFG t-range of each scales + prev_chunk_scales: list = dataclasses.field( + default_factory=lambda: [1.5, 1.5, 1.5, 1.5, 1.5] + ) # CFG scales of previous chunks + text_scales: list = dataclasses.field(default_factory=lambda: [7.5, 7.5, 7.5, 7.5, 7.5]) # CFG scales of text + + noise2clean_kvrange: list = dataclasses.field(default_factory=list) # Range of kv for noise2clean chunks + clean_chunk_kvrange: int = -1 # Range of kv for clean chunks + clean_t: float = 1.0 # timestep for clean chunks + + # Video settings + seed: int = 1234 # Random seed used for python, numpy, pytorch, and cuda. + num_frames: int = 128 + video_size_h: int = None + video_size_w: int = None + num_steps: int = 64 # Number of steps for the diffusion model + window_size: int = 4 # Window size for the diffusion model + fps: int = 24 # Frames per second + chunk_width: int = 6 # Clip width for the diffusion model + + # Checkpoint, includes t5, vae, dit, etc. + t5_pretrained: str = None # Path to load pretrained T5 model. + t5_device: str = "cuda" # Device for T5 model to run on. + vae_pretrained: str = None # Path to load pretrained VAE model. + scale_factor: float = 0.18215 # Scale factor for the vae + temporal_downsample_factor: int = 4 # Temporal downsample factor for the vae + load: str = None # Directory containing a model checkpoint. + + +@dataclasses.dataclass +class EngineConfig: + # Parallism strategy + distributed_backend: str = "nccl" # Choices: ["nccl", "gloo"] + distributed_timeout_minutes: int = 10 # Timeout minutes for torch.distributed. + pp_size: int = 1 # Degree of pipeline model parallelism. + cp_size: int = 1 # Degree of context parallelism. + cp_strategy: str = "none" # Choices: ["none", "cp_ulysses", "cp_shuffle_overlap"] + ulysses_overlap_degree: int = 1 # Overlap degree for Ulysses + + # Quantization + fp8_quant: bool = False # Enable 8-bit floating point quantization for model weights. + + # Distillation + distill_nearly_clean_chunk_threshold: float = 0.3 # Threshold for distilling nearly clean chunks + shortcut_mode: str = "8,16,16" # Parameters for shortcut mode + distill: bool = False # Use distill mode + + # Optimization + kv_offload: bool = False # Use kv-offload algorithm + enable_cuda_graph: bool = False # Enable CUDA graph for video generation + + +@dataclasses.dataclass +class MagiConfig: + model_config: ModelConfig + runtime_config: RuntimeConfig + engine_config: EngineConfig + + @classmethod + def _check_missing_fields(cls, config_dict: dict, required_fields: list): + actual_fields = set(config_dict.keys()) + missing_fields = set(required_fields) - actual_fields + if missing_fields: + raise ValueError(f"Missing fields in the configuration file: {', '.join(missing_fields)}") + + @classmethod + def _create_nested_config(cls, config_dict: dict, config_name: str, config_cls): + nested_config_dict = config_dict.get(config_name, {}) + cls._check_missing_fields(nested_config_dict, config_cls.__dataclass_fields__.keys()) + return config_cls(**nested_config_dict) + + @classmethod + def _create_config_from_dict(cls, config_dict: dict): + cls._check_missing_fields(config_dict, cls.__dataclass_fields__.keys()) + + # Create nested configs + model_config = cls._create_nested_config(config_dict, "model_config", ModelConfig) + runtime_config = cls._create_nested_config(config_dict, "runtime_config", RuntimeConfig) + engine_config = cls._create_nested_config(config_dict, "engine_config", EngineConfig) + + return cls(model_config=model_config, runtime_config=runtime_config, engine_config=engine_config) + + @classmethod + def from_json(cls, json_path: str): + def simple_json_decoder(dct): + dtype_map = {"torch.bfloat16": torch.bfloat16, "torch.float16": torch.float16, "torch.float32": torch.float32} + if 'params_dtype' in dct: + dct['params_dtype'] = dtype_map[dct['params_dtype']] + return dct + + with open(json_path, "r") as f: + config_dict = json.load(f, object_hook=simple_json_decoder) + magi_config = cls._create_config_from_dict(config_dict) + + def post_validation(magi_config): + if magi_config.engine_config.fp8_quant or magi_config.engine_config.distill: + assert ( + magi_config.runtime_config.cfg_number == 1 + ), "Please set `cfg_number: 1` in config.json for distill or quant model" + else: + assert magi_config.runtime_config.cfg_number == 3, "Please set `cfg_number: 3` in config.json for base model" + + post_validation(magi_config) + + return magi_config + + def to_json(self, json_path: str): + class SimpleJSONEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, torch.dtype): + return str(obj) + return super().default(obj) + + # Ensure the directory exists + os.makedirs(os.path.dirname(json_path), exist_ok=True) + + config_dict = { + "model_config": dataclasses.asdict(self.model_config), + "runtime_config": dataclasses.asdict(self.runtime_config), + "engine_config": dataclasses.asdict(self.engine_config), + } + with open(json_path, "w") as f: + json.dump(config_dict, f, indent=4, cls=SimpleJSONEncoder) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/dataclass.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/dataclass.py new file mode 100644 index 0000000000000000000000000000000000000000..5eaab774faf3cb2ca8e1bfc17fd6f65861f4e1fc --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/dataclass.py @@ -0,0 +1,100 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass +from typing import List, Optional + +import numpy as np +import torch + + +@dataclass(frozen=True) +class PackedCoreAttnParams: + # Packed sequence parameters for core_attn + q_range: torch.Tensor + k_range: torch.Tensor + np_q_range: np.ndarray + np_k_range: np.ndarray + max_seqlen_q: int + max_seqlen_k: int + + +@dataclass(frozen=True) +class PackedCrossAttnParams: + # Packed sequence parameters for cross_attn + q_ranges: torch.Tensor = None + kv_ranges: torch.Tensor = None + cu_seqlens_q: torch.Tensor = None + cu_seqlens_kv: torch.Tensor = None + max_seqlen_q: int = None + max_seqlen_kv: int = None + + +@dataclass(frozen=True) +class ModelMetaArgs: + H: int + W: int + cp_pad_size: int + cp_split_sizes: List[int] + slice_point: int + denoising_range_num: int + range_num: int + extract_prefix_video_feature: bool + fwd_extra_1st_chunk: bool + distill_nearly_clean_chunk: bool + clip_token_nums: int + enable_cuda_graph: bool + core_attn_params: PackedCoreAttnParams + cross_attn_params: PackedCrossAttnParams + timestep: torch.Tensor + get_attn_weights_layer_num: int + save_kvcache_every_forward: bool + cur_denoise_step: int + # Includes all chunks of the current sequence + start_chunk_id: int + end_chunk_id: int + compress_kv: bool # use kv cache compression or not + total_cache_len: int + budget_cache_len: int + chunk_num: int + debug: bool + near_clean_chunk_idx: int + # MotionCache sparse forward (Phase 2): gather active tokens only + sparse_active_indices: Optional[torch.Tensor] = None + sparse_total_tokens: int = 0 + +class InferenceParams: + """Inference parameters that are passed to the main model in order + to efficienly calculate and store the context during inference.""" + + def __init__(self, max_batch_size, max_sequence_length): + self.max_sequence_length = max_sequence_length + self.max_batch_size = max_batch_size + self.sequence_len_offset = 0 + self.key_value_memory_dict = {} + self.update_kv_cache = False + + self.kv_compressed = False + + def swap_key_value_dict(self, batch_idx): + "swap between batches" + if len(self.key_value_memory_dict) == 0: + raise ValueError("should not swap when dict in empty") + + for layer_number in self.key_value_memory_dict.keys(): + inference_key_memory, inference_value_memory = self.key_value_memory_dict[layer_number] + assert len(batch_idx) == inference_key_memory.shape[1] # make sure batch size is the same + new_inference_key_memory = inference_key_memory[:, batch_idx] + new_inference_value_memory = inference_value_memory[:, batch_idx] + self.key_value_memory_dict[layer_number] = (new_inference_key_memory, new_inference_value_memory) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/logger.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1072df87334090dbe286f55d7a1056fd4cae2e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/logger.py @@ -0,0 +1,51 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +import torch + + +class GlobalLogger: + _logger = None + + @classmethod + def get_logger(cls, name=__name__, level=logging.INFO): + if cls._logger is None: + cls._logger = logging.getLogger("magi_logger") + cls._logger.setLevel(logging.INFO) + + cls._logger.propagate = False + cls._logger.handlers.clear() + formatter = logging.Formatter("[%(asctime)s - %(levelname)s] %(message)s") + handler = logging.StreamHandler() + handler.setFormatter(formatter) + cls._logger.addHandler(handler) + + return cls._logger + + +magi_logger = GlobalLogger.get_logger() + + +def print_per_rank(message): + magi_logger.info(message) + + +def print_rank_0(message): + if torch.distributed.is_initialized(): + if torch.distributed.get_rank() == 0: + magi_logger.info(message) + else: + magi_logger.info(message) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/timer.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..d0c9f58fdeefb791f548276bea42f5e1288d495e --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/common/timer.py @@ -0,0 +1,85 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime + +import torch + +from .logger import print_rank_0 + + +class EventPathTimer: + """ + A lightweight class for recording time without any distributed barrier. + + This class allows for recording elapsed time between events without requiring + synchronization across distributed processes. It maintains the previous message + and time to calculate the duration between consecutive records. + """ + + def __init__(self): + """ + Initialize the EventPathTimer. + + This constructor sets the previous message and time to None, preparing + the instance for recording events. + """ + self.prev_message: str = None + self.prev_time: datetime = None + + def reset(self): + """ + Reset the recorded message and time. + + This method clears the previous message and time, allowing for a fresh + start in recording new events. + """ + self.prev_message = None + self.prev_time = None + + def synced_record(self, message): + """ + Record the current time with a message. + + Args: + message (str): A message to log along with the current time. + + This method synchronizes the CUDA operations, records the current time, + and calculates the elapsed time since the last recorded message, if any. + It then logs the elapsed time along with the previous and current messages. + """ + torch.cuda.synchronize() + current_time = datetime.now() + if self.prev_message is not None: + print_rank_0( + f"\nTime Elapsed: [{current_time - self.prev_time}] From [{self.prev_message} ({self.prev_time})] To [{message} ({current_time})]" + ) + self.prev_message = message + self.prev_time = current_time + + +_GLOBAL_LIGHT_TIMER = EventPathTimer() + + +def event_path_timer() -> EventPathTimer: + """Get the current EventPathTimer instance. + + Returns: + EventPathTimer: The current EventPathTimer instance. + + Raises: + AssertionError: If the EventPathTimer has not been initialized. + """ + assert _GLOBAL_LIGHT_TIMER is not None, "light time recorder is not initialized" + return _GLOBAL_LIGHT_TIMER diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1419f26c98ef95bed6651827747da6dca50b07 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .checkpointing import load_checkpoint + +__all__ = ["load_checkpoint"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58ee7fc95a48eb8020ee0fed28069121d28b5877 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35b5abbf0db2b5eb431c550d3b65986185316309 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c1585e7186c7301c07137a7238bb779ddee145a Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..513a48d3b81a1025ada3bb52f3b661ef7897e7ac Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/checkpointing.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..983a0100d704e8e9403f785fe0cd4b060ff8eca3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/checkpoint/checkpointing.py @@ -0,0 +1,180 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import io +import json +import os +import re +import subprocess +from collections import OrderedDict +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime + +import numpy as np +import torch +import torch.distributed +from safetensors.torch import load as load_from_bytes +from safetensors.torch import load_file +from tqdm.auto import tqdm + +import inference.infra.distributed.parallel_state as mpu +from inference.common import EngineConfig, ModelConfig, RuntimeConfig, print_per_rank, print_rank_0 + + +def _load_shard(shard_path, param_names, num_threads=None): + zstd_path = shard_path + ".zst" + if os.path.exists(zstd_path): + start_time = datetime.now() + print_per_rank(f"Decompressing {zstd_path} with {num_threads} threads") + cmd = ["zstd", "-d"] + if num_threads: + cmd.extend(["-T", str(num_threads)]) + + process = subprocess.Popen(cmd + ["-c", zstd_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) + + decompressed_data = process.stdout.read() + process.stdout.close() + + retcode = process.wait() + if retcode != 0: + raise RuntimeError(f"Decompression failed: {process.stderr.read().decode()}") + print_per_rank( + f"Decompressed {zstd_path} with {num_threads} threads, duration: {(datetime.now() - start_time).total_seconds()}s" + ) + + buffer = io.BytesIO(decompressed_data) + start_time = datetime.now() + print_per_rank(f"Loading {shard_path} from zstd file, start time: {start_time}") + weights = load_from_bytes(buffer.getvalue()) + print_per_rank(f"Loaded {shard_path} from zstd file, duration: {(datetime.now() - start_time).total_seconds()}s") + buffer.close() + else: + weights = load_file(shard_path) + + return {name: weights[name] for name in param_names} + + +def load_sharded_safetensors_parallel_with_progress(checkpoint_dir): + index_path = os.path.join(checkpoint_dir, "model.safetensors.index.json") + if not os.path.exists(index_path): + model_file_path = os.path.join(checkpoint_dir, "model.safetensors") + state_dict = load_file(model_file_path) + return state_dict + + with open(index_path, "r") as f: + index = json.load(f) + + state_dict = {} + shard_map = {} + + # Group parameters by shard file + for param_name, shard_file in index["weight_map"].items(): + shard_path = os.path.join(checkpoint_dir, shard_file) + if shard_path not in shard_map: + shard_map[shard_path] = [] + shard_map[shard_path].append(param_name) + + # Load shards in parallel with a progress bar + with ThreadPoolExecutor() as executor: + futures = { + executor.submit(_load_shard, shard_path, param_names): shard_path for shard_path, param_names in shard_map.items() + } + pbar = tqdm(futures, desc="Loading shards", total=len(futures)) + for future in pbar: + result = future.result() + state_dict.update(result) + + return state_dict + + +def unwrap_model(model): + return_list = True + if not isinstance(model, list): + model = [model] + return_list = False + unwrapped_model = [] + for model_module in model: + while hasattr(model_module, "module"): + model_module = model_module.module + unwrapped_model.append(model_module) + if not return_list: + return unwrapped_model[0] + return unwrapped_model + + +def _split_state_dict_for_pp(weight_dict: OrderedDict, model_config: ModelConfig): + num_layers = model_config.num_layers + partition = mpu.get_pp_world_size() + + ## use partition and num_layers to get current rank layer order + layers_for_each_stage = np.array_split(range(num_layers), partition) + current_stage = mpu.get_pp_rank() + allow_layer_num = layers_for_each_stage[current_stage] + layer_offset = allow_layer_num[0] + new_weight_dict = {} + for k, v in weight_dict.items(): + if "videodit_blocks.layers" in k: + layer_num = int(re.search(r"videodit_blocks\.layers\.(\d+)", k).group(1)) + if layer_num not in allow_layer_num: + continue + ## replace the old key name by new layer number + new_layer_num = layer_num - layer_offset + new_k = k.replace(f"videodit_blocks.layers.{layer_num}", f"videodit_blocks.layers.{new_layer_num}") + new_weight_dict[new_k] = v + else: + new_weight_dict[k] = v + return new_weight_dict + + +def load_state_dict(runtime_config: RuntimeConfig, engine_config: EngineConfig): + load_dir = runtime_config.load + + default_subdir = "inference_weight" + if engine_config.fp8_quant: + default_subdir = f"{default_subdir}.fp8" + if engine_config.distill: + default_subdir = f"{default_subdir}.distill" + inference_weight_dir = os.path.join(load_dir, default_subdir) + + print_rank_0(f"load {default_subdir} weight from {inference_weight_dir}") + assert ( + os.path.exists(inference_weight_dir) and len(os.listdir(inference_weight_dir)) > 0 + ), f"Ckpt directory {inference_weight_dir} does not exist or empty. If you are using fp8_quant, please run calibration first." + state_dict = load_sharded_safetensors_parallel_with_progress(inference_weight_dir) + return state_dict + + +def load_checkpoint(model): + state_dict = load_state_dict(model.runtime_config, model.engine_config) + + model = unwrap_model(model) + # if we use pipeline parallelism, we need to load the state dict for each stage + # as it always record layer from 0 -> num_layers//pipeline_parallel_size + # so we need to choose correct layer weight when load_state_dict + if mpu.get_pp_world_size() > 1: + state_dict = _split_state_dict_for_pp(state_dict, model.model_config) + + missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False, assign=True) + model.cuda(torch.cuda.current_device()) # bottleneck for loading + + if mpu.get_pp_world_size() > 1: + rank_msg = f"CP_rank={mpu.get_cp_rank()} PP_rank={mpu.get_pp_rank()}" + print_per_rank( + f"""[{rank_msg}] Load Weight Missing Keys: {missing_keys} Load Weight Unexpected Keys: {unexpected_keys} You should see message [missing fianl layer norm weight] except the final pipeline stage""" + ) + else: + print_rank_0(f"Load Weight Missing Keys: {missing_keys}") + print_rank_0(f"Load Weight Unexpected Keys: {unexpected_keys}") + + return model diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0ee9562fb933de643436dece53cc66c979214f --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__init__.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .dist_utils import dist_init, get_device, get_world_size, is_last_rank, is_last_tp_cp_rank +from .parallel_state import ( + destroy_model_parallel, + get_cp_group, + get_cp_rank, + get_cp_world_size, + get_dp_group, + get_dp_group_gloo, + get_dp_rank, + get_dp_world_size, + get_pipeline_model_parallel_first_rank, + get_pipeline_model_parallel_last_rank, + get_pipeline_model_parallel_next_rank, + get_pipeline_model_parallel_prev_rank, + get_pp_group, + get_pp_rank, + get_pp_world_size, + get_tensor_model_parallel_last_rank, + get_tensor_model_parallel_ranks, + get_tensor_model_parallel_src_rank, + get_tp_group, + get_tp_rank, + get_tp_world_size, + is_initialized, + is_pipeline_first_stage, + is_pipeline_last_stage, +) + +__all__ = [ + "dist_init", + "is_initialized", + "get_tp_group", + "get_pp_group", + "get_dp_group", + "get_dp_group_gloo", + "get_cp_group", + "get_tp_world_size", + "get_pp_world_size", + "get_dp_world_size", + "get_cp_world_size", + "get_tp_rank", + "get_pp_rank", + "get_dp_rank", + "get_cp_rank", + "is_pipeline_first_stage", + "is_pipeline_last_stage", + "get_tensor_model_parallel_src_rank", + "get_tensor_model_parallel_ranks", + "get_tensor_model_parallel_last_rank", + "get_pipeline_model_parallel_first_rank", + "get_pipeline_model_parallel_last_rank", + "get_pipeline_model_parallel_next_rank", + "get_pipeline_model_parallel_prev_rank", + "destroy_model_parallel", + "is_last_rank", + "is_last_tp_cp_rank", + "get_world_size", + "get_device", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e5de7a8da07ba3b66b66a629746fb4838ae89d9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67c69c69dce9213ac36266570160d21871109134 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d231e55dd8988ec7630b4d02ea464f10697b70a7 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..792980803713fdff6b6414946ecfc6752eeb8ef5 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..629bfc2ab8e6e541f0514b9b8daaf359a0e6a884 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2396ec53d901e897a97de447d29846ed475e43e7 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/dist_utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..35168c40b3413e91db14fa09c1a2e7e30f4da957 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/dist_utils.py @@ -0,0 +1,92 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from datetime import timedelta + +import torch + +import inference.infra.distributed.parallel_state as mpu +from inference.common import print_rank_0 +from inference.infra.parallelism.pipeline_parallel import init_pp_scheduler + +from . import parallel_state as mpu + + +def dist_init(config): + """Initialize torch.distributed and core model parallel.""" + + assert torch.cuda.is_available() + device_count = torch.cuda.device_count() + if torch.distributed.is_initialized(): + print_rank_0("Torch distribution already initialized, skipping initialization ...") + else: + rank = int(os.getenv("RANK", "0")) + world_size = int(os.getenv("WORLD_SIZE", "1")) + # Manually set the device ids. + if device_count > 0: + device = rank % device_count + torch.cuda.set_device(device) + # Call the init process + torch.distributed.init_process_group( + backend=config.engine_config.distributed_backend, + world_size=world_size, + rank=rank, + timeout=timedelta(minutes=config.engine_config.distributed_timeout_minutes), + ) + assert config.engine_config.cp_size * config.engine_config.pp_size == torch.distributed.get_world_size() + if device_count > 0: + if mpu.model_parallel_is_initialized(): + print_rank_0("Model parallel is already initialized") + else: + mpu.initialize_model_parallel( + cp_size=config.engine_config.cp_size, + pp_size=config.engine_config.pp_size, + nccl_communicator_config_path=None, + distributed_timeout_minutes=config.engine_config.distributed_timeout_minutes, + order="tp-cp-pp-dp", + ) + if mpu.get_pp_world_size() > 1: + init_pp_scheduler() + print_rank_0("Initialize torch distribution and model parallel successfully") + + +def is_last_rank(): + return torch.distributed.get_rank() == (torch.distributed.get_world_size() - 1) + + +def is_last_tp_cp_rank(): + return mpu.get_tp_rank(with_context_parallel=True) == mpu.get_tp_world_size(with_context_parallel=True) - 1 + + +def get_world_size(): + if torch.distributed.is_available() and torch.distributed.is_initialized(): + world_size = torch.distributed.get_world_size() + else: + world_size = 1 + return world_size + + +def get_device(local_rank=None): + backend = torch.distributed.get_backend() + if backend == "nccl": + if local_rank is None: + device = torch.device("cuda") + else: + device = torch.device(f"cuda:{local_rank}") + elif backend == "gloo": + device = torch.device("cpu") + else: + raise RuntimeError + return device diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/parallel_state.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/parallel_state.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec2d14525eabcf739ab8eb1d4afebc3d58b29ca --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/distributed/parallel_state.py @@ -0,0 +1,672 @@ +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model and data parallel groups.""" + +import warnings +from datetime import timedelta +from typing import List, Optional + +import torch + +# Intra-layer model parallel group that the current rank belongs to. +_TENSOR_MODEL_PARALLEL_GROUP = None +# Tensor parallel group information with context parallel combined. +_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None +_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None +# Inter-layer model parallel group that the current rank belongs to. +_PIPELINE_MODEL_PARALLEL_GROUP = None +# Model parallel group (both intra- and pipeline) that the current rank belongs to. +_MODEL_PARALLEL_GROUP = None +# Data parallel group that the current rank belongs to. +_DATA_PARALLEL_GROUP = None +_DATA_PARALLEL_GROUP_GLOO = None +# tensor model parallel group and data parallel group combined +# used for fp8 and moe training +_TENSOR_AND_DATA_PARALLEL_GROUP = None + +# A list of global ranks for each pipeline group to ease calculation of the source +# rank when broadcasting from the first or last pipeline stage. +_PIPELINE_GLOBAL_RANKS = None + +# A list of global ranks for each data parallel group to ease calculation of the source +# rank when broadcasting weights from src to all other data parallel ranks +_DATA_PARALLEL_GLOBAL_RANKS = None + +# A list of global ranks for each tensor model parallel group to ease calculation of +# the first local rank in the tensor model parallel group +_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None + +# Context parallel group that the current rank belongs to +_CONTEXT_PARALLEL_GROUP = None +# A list of global ranks for each context parallel group to ease calculation of the +# destination rank when exchanging KV/dKV between context parallel_ranks +_CONTEXT_PARALLEL_GLOBAL_RANKS = None + +# Data parallel group information with context parallel combined. +_DATA_PARALLEL_GROUP_WITH_CP = None +_DATA_PARALLEL_GROUP_WITH_CP_GLOO = None +_DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None + +# combined parallel group of TP, DP, and CP used for fp8 +_TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None + + +def get_nccl_options(pg_name, nccl_comm_cfgs): + """Set the NCCL process group options. + + Args: + pg_name (str): process group name + nccl_comm_cfgs (dict): nccl communicator configurations + + When an option (e.g., max_ctas) is not found in the config, use the NCCL default setting. + """ + if pg_name in nccl_comm_cfgs: + nccl_options = torch.distributed.ProcessGroupNCCL.Options() + nccl_options.config.cga_cluster_size = nccl_comm_cfgs[pg_name].get("cga_cluster_size", 4) + nccl_options.config.max_ctas = nccl_comm_cfgs[pg_name].get("max_ctas", 32) + nccl_options.config.min_ctas = nccl_comm_cfgs[pg_name].get("min_ctas", 1) + return nccl_options + else: + return None + + +def generate_masked_orthogonal_rank_groups(world_size: int, parallel_size: List[int], mask: List[bool]) -> List[List[int]]: + """Generate orthogonal parallel groups based on the parallel size and mask. + + Arguments: + world_size (int): world size + + parallel_size (List[int]): + The parallel size of each orthogonal parallel type. For example, if + tensor_parallel_size = 2, pipeline_model_parallel_group = 3, data_parallel_size = 4, + and the parallel mapping order is tp-pp-dp, then the parallel_size = [2, 3, 4]. + + mask (List[bool]): + The mask controls which parallel methods the generated groups represent. If mask[i] is + True, it means the generated group contains the i-th parallelism method. For example, + if parallel_size = [tp_size, pp_size, dp_size], and mask = [True, False , True], then + the generated group is the `tp-dp` group, if the mask = [False, True, False], then the + generated group is the `pp` group. + + Algorithm: + For orthogonal parallelism, such as tp/dp/pp/cp, the global_rank and + local_rank satisfy the following equation: + global_rank = tp_rank + dp_rank * tp_size + pp_rank * tp_size * dp_size (1) + tp_rank \in [0, tp_size) + dp_rank \in [0, dp_size) + pp_rank \in [0, pp_size) + + If we want to get the `dp_group` (tp_size * pp_size groups of dp_size ranks each. + For example, if the gpu size is 8 and order is 'tp-pp-dp', size is '2-2-2', and the + dp_group here is [[0, 4], [1, 5], [2, 6], [3, 7]].) + The tp_rank and pp_rank will be combined to form the `dp_group_index`. + dp_group_index = tp_rank + pp_rank * tp_size (2) + + So, Given that tp_rank and pp_rank satisfy equation (2), and dp_rank in + range(0, dp_size), the ranks in dp_group[dp_group_index] satisfies the + equation (1). + + This function solve this math problem. + + For example, if the parallel_size = [tp_size, dp_size, pp_size] = [2, 3, 4], + and the mask = [False, True, False]. Then, + dp_group_index(0) = tp_rank(0) + pp_rank(0) * 2 + dp_group_index(1) = tp_rank(1) + pp_rank(0) * 2 + ... + dp_group_index(7) = tp_rank(1) + pp_rank(3) * 2 + + dp_group[0] = 0 + range(0, 3) * 2 + 0 = [0, 2, 4] + dp_group[1] = 1 + range(0, 3) * 2 + 0 = [1, 3, 5] + ... + dp_group[7] = 1 + range(0, 3) * 2 + 3 * 2 * 3 = [19, 21, 23] + """ + + def prefix_product(a: List[int], init=1) -> List[int]: + r = [init] + for v in a: + init = init * v + r.append(init) + return r + + def inner_product(a: List[int], b: List[int]) -> int: + return sum([x * y for x, y in zip(a, b)]) + + def decompose(index, shape, stride=None): + """ + This function solve the math problem below: + There is an equation: + index = sum(idx[i] * stride[i]) + And given the value of index, stride. + Return the idx. + This function will used to get the pp/dp/pp_rank + from group_index and rank_in_group. + """ + if stride is None: + stride = prefix_product(shape) + idx = [(index // d) % s for s, d in zip(shape, stride)] + # stride is a prefix_product result. And the value of stride[-1] + # is not used. + assert ( + sum([x * y for x, y in zip(idx, stride[:-1])]) == index + ), "idx {} with shape {} mismatch the return idx {}".format(index, shape, idx) + return idx + + masked_shape = [s for s, m in zip(parallel_size, mask) if m] + unmasked_shape = [s for s, m in zip(parallel_size, mask) if not m] + + global_stride = prefix_product(parallel_size) + masked_stride = [d for d, m in zip(global_stride, mask) if m] + unmasked_stride = [d for d, m in zip(global_stride, mask) if not m] + + group_size = prefix_product(masked_shape)[-1] + num_of_group = world_size // group_size + + ranks = [] + for group_index in range(num_of_group): + # get indices from unmaksed for group_index. + decomposed_group_idx = decompose(group_index, unmasked_shape) + rank = [] + for rank_in_group in range(group_size): + # get indices from masked for rank_in_group. + decomposed_rank_idx = decompose(rank_in_group, masked_shape) + rank.append( + inner_product(decomposed_rank_idx, masked_stride) + inner_product(decomposed_group_idx, unmasked_stride) + ) + ranks.append(rank) + return ranks + + +class RankGenerator(object): + def __init__(self, tp: int, dp: int, pp: int, cp: int, order: str) -> None: + self.tp = tp + self.dp = dp + self.pp = pp + self.cp = cp + self.world_size = tp * dp * pp * cp + + self.name_to_size = {"tp": self.tp, "pp": self.pp, "dp": self.dp, "cp": self.cp} + order = order.lower() + for name in self.name_to_size.keys(): + if name not in order and self.name_to_size[name] != 1: + raise RuntimeError( + f"The size of ({name}) is ({self.name_to_size[name]}), but you haven't specified the order ({self.order})." + ) + elif name not in order: + order = order + "-" + name + + self.order = order + self.ordered_size = [self.name_to_size[token] for token in order.split("-")] + + def get_mask(self, order: str, token: str): + ordered_token = order.split("-") + token = token.split("-") + mask = [False] * len(ordered_token) + for t in token: + mask[ordered_token.index(t)] = True + return mask + + def get_ranks(self, token): + """Get rank group by input token. + + Arguments: + token (str): + Specify the ranks type that want to get. If we want + to obtain multiple parallel types, we can use a hyphen + '-' to separate them. For example, if we want to obtain + the TP_DP group, the token should be 'tp-dp'. + """ + mask = self.get_mask(self.order, token) + ranks = generate_masked_orthogonal_rank_groups(self.world_size, self.ordered_size, mask) + return ranks + + +def initialize_model_parallel( + tp_size: int = 1, + pp_size: int = 1, + cp_size: int = 1, + nccl_communicator_config_path: Optional[str] = None, + distributed_timeout_minutes: int = 30, + order: str = "tp-cp-pp-dp", +) -> None: + """Initialize model data parallel groups. + Borrow from: https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py + + Args: + tp_size (int, default = 1): + The number of GPUs to split individual tensors across. + + pp_size (int, default = 1): + The number of tensor parallel GPU groups to split the + Transformer layers across. For example, if tp_size is 4 and + pp_size is 2, the model will be split into 2 groups of 4 GPUs. + + cp_size (int, default = 1): + The number of tensor parallel GPU groups to split the + network input sequence length across. Compute of attention + module requires tokens of full sequence length, so GPUs + in a context parallel group need to communicate with each + other to exchange information of other sequence chunks. + Each GPU and its counterparts in other tensor parallel + groups compose a context parallel group. + + For example, assume we have 8 GPUs, if tensor model parallel + size is 4 and context parallel size is 2, the network input + will be split into two sequence chunks, which are processed + by 2 different groups of 4 GPUs. One chunk is processed by + GPU0-3, the other chunk is processed by GPU4-7. Four groups + are build to do context parallel communications: [GPU0, GPU4], + [GPU1, GPU5], [GPU2, GPU6], and [GPU3, GPU7]. + + Context parallelism partitions sequence length, so it has no + impact on weights, which means weights are duplicated among + GPUs in a context parallel group. Hence, weight gradients + all-reduce is required in backward. For simplicity, we piggyback + GPUs of context parallelism on data parallel group for + weight gradient all-reduce. + + nccl_communicator_config_path (str, default = None): + Path to the yaml file of NCCL communicator configurations. + `min_ctas`, `max_ctas`, and `cga_cluster_size` can be set + for each communicator. + + distributed_timeout_minutes (int, default = 30): Timeout, in + minutes,for operations executed against distributed + process groups. See PyTorch documentation at + https://pytorch.org/docs/stable/distributed.html for + caveats. + + order (str, default=tp-dp-pp): + The rank initialization order of parallelism. Now we support + tp-dp-pp and tp-pp-dp orders. + + Let's say we have a total of 16 GPUs denoted by g0 ... g15 and we + use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize + the model pipeline. The present function will + create 8 tensor model-parallel groups, 4 pipeline model-parallel groups + and 8 data-parallel groups as: + 8 data_parallel groups: + [g0, g2], [g1, g3], [g4, g6], [g5, g7], [g8, g10], [g9, g11], [g12, g14], [g13, g15] + 8 tensor model-parallel groups: + [g0, g1], [g2, g3], [g4, g5], [g6, g7], [g8, g9], [g10, g11], [g12, g13], [g14, g15] + 4 pipeline model-parallel groups: + [g0, g4, g8, g12], [g1, g5, g9, g13], [g2, g6, g10, g14], [g3, g7, g11, g15] + Note that for efficiency, the caller should make sure adjacent ranks + are on the same DGX box. For example if we are using 2 DGX-1 boxes + with a total of 16 GPUs, rank 0 to 7 belong to the first box and + ranks 8 to 15 belong to the second box. + + """ + # Get world size and rank. Ensure some consistencies. + assert torch.distributed.is_initialized() + world_size: int = torch.distributed.get_world_size() + if world_size % (tp_size * pp_size * cp_size) != 0: + raise RuntimeError( + f"world_size ({world_size}) is not divisible by tp_size " + f"({tp_size}) x pp_size ({pp_size}) " + f"x cp_size ({cp_size})" + ) + + nccl_comm_cfgs = {} + if nccl_communicator_config_path is not None: + try: + import yaml + except ImportError: + raise RuntimeError("Cannot import `yaml`. Setting custom nccl communicator configs " "requires the yaml package.") + + with open(nccl_communicator_config_path, "r") as stream: + nccl_comm_cfgs = yaml.safe_load(stream) + + dp_size: int = world_size // (tp_size * pp_size * cp_size) + rank = torch.distributed.get_rank() + rank_generator = RankGenerator(tp=tp_size, dp=dp_size, pp=pp_size, cp=cp_size, order=order) + timeout = timedelta(minutes=distributed_timeout_minutes) + + # Build the data-parallel groups. + global _DATA_PARALLEL_GROUP + global _DATA_PARALLEL_GROUP_GLOO + global _DATA_PARALLEL_GLOBAL_RANKS + global _DATA_PARALLEL_GROUP_WITH_CP + global _DATA_PARALLEL_GROUP_WITH_CP_GLOO + global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP + assert _DATA_PARALLEL_GROUP is None, "data parallel group is already initialized" + + for ranks in rank_generator.get_ranks("dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("dp", nccl_comm_cfgs)) + group_gloo = torch.distributed.new_group(ranks, timeout=timeout, backend="gloo") + if rank in ranks: + _DATA_PARALLEL_GROUP = group + _DATA_PARALLEL_GROUP_GLOO = group_gloo + _DATA_PARALLEL_GLOBAL_RANKS = ranks + for ranks_with_cp in rank_generator.get_ranks("dp-cp"): + group_with_cp = torch.distributed.new_group( + ranks_with_cp, timeout=timeout, pg_options=get_nccl_options("dp_cp", nccl_comm_cfgs) + ) + group_with_cp_gloo = torch.distributed.new_group(ranks_with_cp, timeout=timeout, backend="gloo") + if rank in ranks_with_cp: + _DATA_PARALLEL_GROUP_WITH_CP = group_with_cp + _DATA_PARALLEL_GROUP_WITH_CP_GLOO = group_with_cp_gloo + _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks_with_cp + + # Build the context-parallel groups. + global _CONTEXT_PARALLEL_GROUP + global _CONTEXT_PARALLEL_GLOBAL_RANKS + assert _CONTEXT_PARALLEL_GROUP is None, "context parallel group is already initialized" + for ranks in rank_generator.get_ranks("cp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("cp", nccl_comm_cfgs)) + if rank in ranks: + _CONTEXT_PARALLEL_GROUP = group + _CONTEXT_PARALLEL_GLOBAL_RANKS = ranks + + # Build the model-parallel groups. + global _MODEL_PARALLEL_GROUP + assert _MODEL_PARALLEL_GROUP is None, "model parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp-pp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("mp", nccl_comm_cfgs)) + if rank in ranks: + _MODEL_PARALLEL_GROUP = group + + # Build the tensor model-parallel groups. + global _TENSOR_MODEL_PARALLEL_GROUP + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + assert _TENSOR_MODEL_PARALLEL_GROUP is None, "tensor model parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_MODEL_PARALLEL_GROUP = group + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = ranks + + # Build the tensor + context parallel groups. + global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + assert ( + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is None + ), "tensor model parallel group with context parallel is already initialized" + for ranks in rank_generator.get_ranks("tp-cp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = group + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks + + # Build the pipeline model-parallel groups + global _PIPELINE_MODEL_PARALLEL_GROUP + global _PIPELINE_GLOBAL_RANKS + assert _PIPELINE_MODEL_PARALLEL_GROUP is None, "pipeline model parallel group is already initialized" + for ranks in rank_generator.get_ranks("pp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("pp", nccl_comm_cfgs)) + if rank in ranks: + _PIPELINE_MODEL_PARALLEL_GROUP = group + _PIPELINE_GLOBAL_RANKS = ranks + + # Build the tensor + data parallel groups. + global _TENSOR_AND_DATA_PARALLEL_GROUP + global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP + assert _TENSOR_AND_DATA_PARALLEL_GROUP is None, "Tensor + data parallel group is already initialized" + for ranks in rank_generator.get_ranks("tp-cp-dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp_dp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = group + for ranks in rank_generator.get_ranks("tp-dp"): + group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_dp", nccl_comm_cfgs)) + if rank in ranks: + _TENSOR_AND_DATA_PARALLEL_GROUP = group + + +def is_initialized(): + """Useful for code segments that may be accessed with or without mpu initialization""" + return _DATA_PARALLEL_GROUP is not None + + +def is_unitialized() -> bool: + """Check if parallel state has been initialized + + Deprecated. Use is_initialized instead. + + """ + warnings.warn("is_unitialized is deprecated, use is_initialized instead", DeprecationWarning) + return not is_initialized() + + +def model_parallel_is_initialized(): + """Check if model and data parallel groups are initialized.""" + if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None: + return False + return True + + +def get_model_parallel_group(): + """Get the model parallel group the caller rank belongs to.""" + assert _MODEL_PARALLEL_GROUP is not None, "model parallel group is not initialized" + return _MODEL_PARALLEL_GROUP + + +def get_tp_group(check_initialized=True, with_context_parallel=False): + """Get the tensor model parallel group the caller rank belongs to.""" + if check_initialized: + assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is not None + ), "tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + else: + assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized" + return _TENSOR_MODEL_PARALLEL_GROUP + + +def get_pp_group(): + """Get the pipeline model parallel group the caller rank belongs to.""" + assert _PIPELINE_MODEL_PARALLEL_GROUP is not None, "pipeline_model parallel group is not initialized" + return _PIPELINE_MODEL_PARALLEL_GROUP + + +def get_dp_group(with_context_parallel=False): + """Get the data parallel group the caller rank belongs to.""" + if with_context_parallel: + assert ( + _DATA_PARALLEL_GROUP_WITH_CP is not None + ), "data parallel group with context parallel combined is not initialized" + return _DATA_PARALLEL_GROUP_WITH_CP + else: + assert _DATA_PARALLEL_GROUP is not None, "data parallel group is not initialized" + return _DATA_PARALLEL_GROUP + + +def get_dp_group_gloo(with_context_parallel=False): + """Get the data parallel group-gloo the caller rank belongs to.""" + if with_context_parallel: + assert ( + _DATA_PARALLEL_GROUP_WITH_CP_GLOO is not None + ), "data parallel group-gloo with context parallel combined is not initialized" + return _DATA_PARALLEL_GROUP_WITH_CP_GLOO + else: + assert _DATA_PARALLEL_GROUP_GLOO is not None, "data parallel group-gloo is not initialized" + return _DATA_PARALLEL_GROUP_GLOO + + +def get_cp_group(check_initialized=True): + """Get the context parallel group the caller rank belongs to.""" + if check_initialized: + assert _CONTEXT_PARALLEL_GROUP is not None, "context parallel group is not initialized" + return _CONTEXT_PARALLEL_GROUP + + +def get_tp_world_size(with_context_parallel=False): + """Return world size for the tensor model parallel group.""" + return torch.distributed.get_world_size(group=get_tp_group(with_context_parallel=with_context_parallel)) + + +def get_pp_world_size(): + """Return world size for the pipeline model parallel group.""" + return torch.distributed.get_world_size(group=get_pp_group()) + + +def get_tp_rank(with_context_parallel=False): + """Return my rank for the tensor model parallel group.""" + return torch.distributed.get_rank(group=get_tp_group(with_context_parallel=with_context_parallel)) + + +def get_pp_rank(): + """Return my rank for the pipeline model parallel group.""" + return torch.distributed.get_rank(group=get_pp_group()) + + +def is_pipeline_first_stage(): + """Return True if in the first pipeline model-parallel stage, False otherwise.""" + return get_pp_rank() == 0 + + +def is_pipeline_last_stage(): + """Return True if in the last pipeline model-parallel stage, False otherwise.""" + return get_pp_rank() == (get_pp_world_size() - 1) + + +def get_tensor_model_parallel_src_rank(with_context_parallel=False): + """Calculate the global rank corresponding to the first local rank + in the tensor model parallel group.""" + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[0] + else: + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[0] + + +def get_tensor_model_parallel_ranks(with_context_parallel=False): + """Return all global ranks for the tensor model parallel group.""" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + else: + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + + +def get_tensor_model_parallel_last_rank(with_context_parallel=False): + """Calculate the global rank corresponding to the first local rank + in the tensor model parallel group.""" + assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized" + if with_context_parallel: + assert ( + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None + ), "Tensor model parallel group with context parallel combined is not initialized" + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[-1] + else: + return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[-1] + + +def get_pipeline_model_parallel_first_rank(): + """Return the global rank of the first process in the pipeline for the + current tensor parallel group""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + return _PIPELINE_GLOBAL_RANKS[0] + + +def get_pipeline_model_parallel_last_rank(): + """Return the global rank of the last process in the pipeline for the + current tensor parallel group""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + last_rank_local = get_pp_world_size() - 1 + return _PIPELINE_GLOBAL_RANKS[last_rank_local] + + +def get_pipeline_model_parallel_next_rank(): + """Return the global rank that follows the caller in the pipeline""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + rank_in_pipeline = get_pp_rank() + world_size = get_pp_world_size() + return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline + 1) % world_size] + + +def get_pipeline_model_parallel_prev_rank(): + """Return the global rank that preceeds the caller in the pipeline""" + assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized" + rank_in_pipeline = get_pp_rank() + world_size = get_pp_world_size() + return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline - 1) % world_size] + + +def get_dp_world_size(with_context_parallel=False): + """Return world size for the data parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_world_size(group=get_dp_group(with_context_parallel=with_context_parallel)) + else: + return 0 + + +def get_dp_rank(with_context_parallel=False): + """Return my rank for the data parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(group=get_dp_group(with_context_parallel=with_context_parallel)) + else: + return 0 + + +def get_cp_world_size(): + """Return world size for the context parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_world_size(group=get_cp_group()) + else: + return 0 + + +def get_cp_rank(): + """Return my rank for the context parallel group.""" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + return torch.distributed.get_rank(group=get_cp_group()) + else: + return 0 + + +def destroy_model_parallel(): + """Set the groups to none.""" + global _MODEL_PARALLEL_GROUP + _MODEL_PARALLEL_GROUP = None + global _TENSOR_MODEL_PARALLEL_GROUP + _TENSOR_MODEL_PARALLEL_GROUP = None + global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP + _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None + global _PIPELINE_MODEL_PARALLEL_GROUP + _PIPELINE_MODEL_PARALLEL_GROUP = None + global _DATA_PARALLEL_GROUP + _DATA_PARALLEL_GROUP = None + global _DATA_PARALLEL_GROUP_GLOO + _DATA_PARALLEL_GROUP_GLOO = None + global _TENSOR_AND_DATA_PARALLEL_GROUP + _TENSOR_AND_DATA_PARALLEL_GROUP = None + global _PIPELINE_GLOBAL_RANKS + _PIPELINE_GLOBAL_RANKS = None + global _DATA_PARALLEL_GLOBAL_RANKS + _DATA_PARALLEL_GLOBAL_RANKS = None + global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS + _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None + global _CONTEXT_PARALLEL_GROUP + _CONTEXT_PARALLEL_GROUP = None + global _CONTEXT_PARALLEL_GLOBAL_RANKS + _CONTEXT_PARALLEL_GLOBAL_RANKS = None + global _DATA_PARALLEL_GROUP_WITH_CP + _DATA_PARALLEL_GROUP_WITH_CP = None + global _DATA_PARALLEL_GROUP_WITH_CP_GLOO + _DATA_PARALLEL_GROUP_WITH_CP_GLOO = None + global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP + _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None + global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP + _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..859ebeae3dfa76b926b41e78bab6af5cb99ae449 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .context_parallel import CSOHelper, UlyssesScheduler, cp_post_process, cp_pre_process, cso_communication +from .pipeline_parallel import pp_scheduler +from .tile_parallel import TileProcessor + +__all__ = [ + "CSOHelper", + "cso_communication", + "UlyssesScheduler", + "pp_scheduler", + "TileProcessor", + "cp_pre_process", + "cp_post_process", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b10923010d7bf491e6e43b2028dd8422e906c25 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc616b023cf6236155f83596110c5abb7a9ea44 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92df574166999fa8adf94b86bd93ff36aae26c95 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..017bc436a3ddec1e564aed028e8e51fd3c3d19b6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bae3f24edb5a418fda5600391307f35861d5faa0 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45db5d702b96e007b525f4bc6f4dfb63e8fc5a09 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bf651578157cbc9e729b34a080bcd968499b7bb Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1eec46261daa78ee57d40871e804cea1469b572 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/context_parallel.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/context_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b803c2e79da5ebd6afecca165e03481fcc0738 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/context_parallel.py @@ -0,0 +1,673 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Callable, List, Tuple, Union + +import torch +import torch.distributed +from einops import rearrange + +from inference.common import ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams, divide +from inference.infra.distributed import parallel_state as mpu + + +##################################################### +# Common Primitives +##################################################### +def scatter_to_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0): + """Split the tensor along its first dimension and keep the + corresponding slice.""" + + world_size = mpu.get_cp_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + # Split along first dimension with padding. + rank = mpu.get_cp_rank() + if cp_shuffle_num > 1: + cp_pad_size = divide(cp_pad_size, cp_shuffle_num) + cp_split_sizes = [divide(s, cp_shuffle_num) for s in cp_split_sizes] + dim_offset = sum(cp_split_sizes[:rank]) + xs = [] + for x in torch.chunk(input_, cp_shuffle_num, dim=0): + x = torch.nn.functional.pad(x, [0, 0] * (x.dim() - 1) + [0, cp_pad_size], mode="constant", value=0) + xs.append(x[dim_offset : dim_offset + cp_split_sizes[rank]]) + output = torch.concat(xs, dim=0) + else: + dim_offset = sum(cp_split_sizes[:rank]) + x = torch.nn.functional.pad(input_, [0, 0] * (input_.dim() - 1) + [0, cp_pad_size], mode="constant", value=0) + output = x[dim_offset : dim_offset + cp_split_sizes[rank]].contiguous() + return output + + +def gather_from_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0): + """Gather tensors and concatinate along the first dimension.""" + + world_size = mpu.get_cp_world_size() + # Bypass the function if we are using only 1 GPU. + if world_size == 1: + return input_ + + input_ = input_.contiguous() + total_seq_len = sum(cp_split_sizes) + dim_size = list(input_.size()) + dim_size[0] = total_seq_len + + output = torch.empty(dim_size, dtype=input_.dtype, device=input_.device) + outputs = list(torch.split(output, cp_split_sizes, dim=0)) + torch.distributed.all_gather(outputs, input_, group=mpu.get_cp_group()) + if cp_shuffle_num > 1: + total_seq_len = divide(total_seq_len, cp_shuffle_num) + cp_pad_size = divide(cp_pad_size, cp_shuffle_num) + chunks = [torch.chunk(o, cp_shuffle_num, dim=0) for o in outputs] + output = torch.concat( + [ + torch.concat([chunk[i] for chunk in chunks], dim=0)[: total_seq_len - cp_pad_size] + for i in range(cp_shuffle_num) + ], + dim=0, + ) + else: + output = torch.concat(outputs, dim=0)[: total_seq_len - cp_pad_size] + + return output + + +class FakeHandle: + def __init__(self): + pass + + def wait(self): + pass + + +##################################################### +# Context Parallel Process +##################################################### +def update_packed_seq_params_for_cuda_graph(cross_attn_params: PackedCrossAttnParams, xattn_mask: torch.Tensor): + assert xattn_mask is not None + # xattn_mask: (N * denoising_range_num, L, 1, 1) + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + batch_size, static_caption_length = xattn_mask.shape + + # Get index_map for kv_range injection, map y_index to static_caption_length + y_index = torch.sum(xattn_mask, dim=-1) + cu_seqlens_k = torch.cat([y_index.new_tensor([0]), y_index]).to(torch.int32).to(xattn_mask.device) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + static_cu_seqlens_k = torch.arange(0, (batch_size + 1) * static_caption_length, static_caption_length) + assert cu_seqlens_k.shape[0] == batch_size + 1 == static_cu_seqlens_k.shape[0] + start_index_map = dict(zip(cu_seqlens_k.flatten().tolist(), static_cu_seqlens_k.flatten().tolist())) + + # Move kv_range to the right position + kv_range_start_list = cross_attn_params.kv_ranges[:, 0].flatten().tolist() + static_kv_range_start = [start_index_map[kv_range_start_list[i]] for i in range(len(kv_range_start_list))] + static_kv_range_start = torch.tensor(static_kv_range_start, dtype=torch.int32, device=xattn_mask.device) + assert static_kv_range_start.shape[0] == cross_attn_params.kv_ranges.shape[0] + static_kv_range_diff = cross_attn_params.kv_ranges[:, 1] - cross_attn_params.kv_ranges[:, 0] + static_kv_range_end = static_kv_range_start + static_kv_range_diff + static_kv_range = torch.stack((static_kv_range_start, static_kv_range_end), dim=1) + + assert static_kv_range.shape == cross_attn_params.kv_ranges.shape + return PackedCrossAttnParams( + q_ranges=cross_attn_params.q_ranges, + kv_ranges=static_kv_range, + cu_seqlens_q=cross_attn_params.cu_seqlens_q, + cu_seqlens_kv=cross_attn_params.cu_seqlens_kv, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_kv=cross_attn_params.max_seqlen_kv, + ) + + +def cp_update_cross_attn_qkv_range( + cross_attn_params: PackedCrossAttnParams, + batch_size: int, + cp_split_sizes: List[int], + device: torch.device, + cp_shuffle_num: int = 1, + cp_pad_size: int = 0, +): + """ + Update cross_attn_params for cross_attn in context parallel. + + Input: + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + batch_size: int. Batch size + cp_split_sizes: List[int]. Split sizes for each rank + device: torch.device. Device + + Output: + cross_attn_params: PackedCrossAttnParams. Updated packed parameters for cross_atten + """ + # Update cu_seqlens_q and max_seqlen_q because split x maybe unbalanced + cp_rank = mpu.get_cp_rank() + seq_len_cur_rank = cp_split_sizes[cp_rank] + cp_split_sizes = [divide(x, cp_shuffle_num) for x in cp_split_sizes] + cp_split_sizes = torch.tensor(cp_split_sizes, dtype=torch.int32, device=device) + base_cp_boundaries = torch.cat((torch.zeros(1, dtype=torch.int32, device=device), cp_split_sizes.cumsum(0))) + total_seq_len = base_cp_boundaries[-1] + + cu_seqlens_q = cross_attn_params.cu_seqlens_q + cu_seqlens_k = cross_attn_params.cu_seqlens_kv + cu_seqlens_pad = torch.arange(cu_seqlens_q.shape[0], dtype=torch.int32, device=device) * divide( + cp_pad_size, cp_shuffle_num + ) + cu_seqlens_q = cu_seqlens_q + cu_seqlens_pad + + q_seg_starts, q_seg_ends = cu_seqlens_q[:-1], cu_seqlens_q[1:] + + xattn_q_ranges, xattn_k_ranges = [], [] + for i in range(batch_size): + inner_xattn_q_ranges, inner_xattn_k_ranges = [], [] + for j in range(cp_shuffle_num): + global_offset = i * total_seq_len * cp_shuffle_num + j * total_seq_len + cp_boundaries = base_cp_boundaries + global_offset + this_cp_start, this_cp_end = (cp_boundaries[cp_rank], cp_boundaries[cp_rank + 1]) + + q_inter_starts = torch.maximum(this_cp_start, q_seg_starts) + q_inter_ends = torch.minimum(this_cp_end, q_seg_ends) + + q_mask = q_inter_starts < q_inter_ends + valid_q_starts = q_inter_starts[q_mask] + valid_q_ends = q_inter_ends[q_mask] + + k_seg_starts, k_seg_ends = cu_seqlens_k[:-1], cu_seqlens_k[1:] + valid_indices = torch.nonzero(q_mask, as_tuple=True)[0] + + valid_k_starts = k_seg_starts[valid_indices] + valid_k_ends = k_seg_ends[valid_indices] + + part_xattn_q_rangs = torch.stack((valid_q_starts, valid_q_ends), dim=1) + offset = part_xattn_q_rangs[:, 0].min() + part_xattn_q_rangs = part_xattn_q_rangs - offset + + inner_xattn_q_ranges.append(part_xattn_q_rangs) + inner_xattn_k_ranges.append(torch.stack((valid_k_starts, valid_k_ends), dim=1)) + inner_end_values = torch.tensor([ranges[-1, -1] for ranges in inner_xattn_q_ranges], dtype=torch.int32) + inner_offsets = torch.cat((torch.zeros(1, dtype=inner_end_values.dtype), torch.cumsum(inner_end_values[:-1], dim=0))) + inner_xattn_q_ranges = [tensor + int(offset) for tensor, offset in zip(inner_xattn_q_ranges, inner_offsets)] + xattn_q_ranges.append(torch.cat(inner_xattn_q_ranges, dim=0)) + xattn_k_ranges.append(torch.cat(inner_xattn_k_ranges, dim=0)) + + end_values = torch.tensor([ranges[-1, -1].item() for ranges in xattn_q_ranges], dtype=torch.int32) + offsets = torch.cat((torch.zeros(1, dtype=end_values.dtype), torch.cumsum(end_values[:-1], dim=0))) + + shifted_tensors = [tensor + int(offset) for tensor, offset in zip(xattn_q_ranges, offsets)] + xattn_q_ranges_ts = torch.cat(shifted_tensors, dim=0) + xattn_k_ranges_ts = torch.cat(xattn_k_ranges, dim=0) + + cu_seqlens_q = torch.unique(xattn_q_ranges_ts) + cu_seqlens_k = torch.unique(xattn_k_ranges_ts) + assert ( + cu_seqlens_q.shape == cu_seqlens_k.shape + ), f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}, " + + return PackedCrossAttnParams( + q_ranges=xattn_q_ranges_ts, + kv_ranges=xattn_k_ranges_ts, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=seq_len_cur_rank, + max_seqlen_kv=cross_attn_params.max_seqlen_kv, + ) + + +def cp_ulysses_process( + cp_size: int, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + cross_attn_params: PackedCrossAttnParams, +): + seq_len, N, D = x.shape + assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}" + assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}" + + # Part1: split for CP + cp_split_sizes = [seq_len // cp_size] * cp_size + for i in range(seq_len % cp_size): + cp_split_sizes[i] += 1 + + # Part2: scatter to CP + x = scatter_to_context_parallel_region(x, cp_split_sizes) + condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes) + rope = scatter_to_context_parallel_region(rope, cp_split_sizes) + + # Part3: update cross_attn cross_attn_params + cross_attn_params = cp_update_cross_attn_qkv_range(cross_attn_params, N, cp_split_sizes, x.device) + if xattn_mask_for_cuda_graph is not None: + cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph) + + return x, condition_map, rope, cp_split_sizes, cross_attn_params + + +def cp_shuffle_overlap_process( + cp_size: int, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + ardf_meta: dict, + core_attn_params: PackedCoreAttnParams, + cross_attn_params: PackedCrossAttnParams, +): + seq_len, N, D = x.shape + assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}" + assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}" + cp_shuffle_num = ardf_meta["denoising_range_num"] + + # Part1: calculate cp_pad_size and cp_split_sizes + cp_pad_size = 0 + if divide(seq_len, cp_shuffle_num) % cp_size != 0: + cp_pad_size = (cp_size - divide(seq_len, cp_shuffle_num) % cp_size) * cp_shuffle_num + cp_split_sizes = [(seq_len + cp_pad_size) // cp_size] * cp_size + + # Part2: scatter to CP + x = scatter_to_context_parallel_region(x, cp_split_sizes, cp_shuffle_num, cp_pad_size) + condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes, cp_shuffle_num, cp_pad_size) + rope = scatter_to_context_parallel_region(rope, cp_split_sizes, cp_shuffle_num, cp_pad_size) + + # Part3: update core_attn_params + gcd = math.gcd(seq_len, seq_len + cp_pad_size) + _sq = seq_len // gcd + _psq = (seq_len + cp_pad_size) // gcd + q_range = ardf_meta["q_range"] * _psq // _sq + max_seqlen_q = ardf_meta["max_seqlen_q"] * _psq // _sq + core_attn_params = PackedCoreAttnParams( + q_range=q_range, + k_range=ardf_meta["k_range"], + np_q_range=q_range.cpu().numpy(), + np_k_range=ardf_meta["k_range"].cpu().numpy(), + max_seqlen_q=max_seqlen_q, + max_seqlen_k=ardf_meta["max_seqlen_k"], + ) + + # Part4: update cross_attn cross_attn_params + cross_attn_params = cp_update_cross_attn_qkv_range( + cross_attn_params, N, cp_split_sizes, x.device, cp_shuffle_num, cp_pad_size + ) + if xattn_mask_for_cuda_graph is not None: + cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph) + + return x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params + + +def cp_pre_process( + cp_size: int, + cp_strategy: str, + x: torch.Tensor, + condition_map: torch.Tensor, + rope: torch.Tensor, + xattn_mask_for_cuda_graph: Union[torch.Tensor, None], + ardf_meta: dict, + core_attn_params: PackedCoreAttnParams, + cross_attn_params: PackedCrossAttnParams, +): + """ + This function is used to handle context parallel behavior, + split input tensors into multiple parts and scatter them to different GPUs. + + Input: + cp_strategy: str. cp_ulysses for hopper or newer, cp_shuffle_overlap for 4090 or older + x: (S, N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition_map: (N * S). torch.Tensor determine which condition to use for each token + rope: (S, 96). torch.Tensor of rope + xattn_mask_for_cuda_graph: (N * denoising_range_num, L, 1, 1). torch.Tensor of xattn mask for cuda graph, None means no cuda graph + core_attn_params: PackedCoreAttnParams. Packed sequence parameters for core_atten + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + + Output: + x: (S', N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition_map: (N * S'). torch.Tensor determine which condition to use for each token + rope: (S', 96). torch.Tensor of rope + cp_split_sizes: List[int]. Split sizes for each rank + core_attn_params: PackedCoreAttnParams + cross_attn_params: PackedCrossAttnParams + """ + if cp_size == 1: + return x, condition_map, rope, None, None, core_attn_params, cross_attn_params + if cp_strategy == "cp_ulysses": + (x, condition_map, rope, cp_split_sizes, cross_attn_params) = cp_ulysses_process( + cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, cross_attn_params + ) + return (x, condition_map, rope, 0, cp_split_sizes, core_attn_params, cross_attn_params) + elif cp_strategy == "cp_shuffle_overlap": + ( + x, + condition_map, + rope, + cp_pad_size, + cp_split_sizes, + core_attn_params, + cross_attn_params, + ) = cp_shuffle_overlap_process( + cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, ardf_meta, core_attn_params, cross_attn_params + ) + return (x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params) + else: + raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap") + + +def cp_post_process(cp_size: int, cp_strategy: str, x: torch.Tensor, meta_args: ModelMetaArgs) -> torch.Tensor: + if cp_size == 1: + return x + if cp_strategy == "cp_shuffle_overlap": + x = gather_from_context_parallel_region( + x, meta_args.cp_split_sizes, meta_args.denoising_range_num, meta_args.cp_pad_size + ) + elif cp_strategy == "cp_ulysses": + x = gather_from_context_parallel_region(x, meta_args.cp_split_sizes) + else: + raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap") + return x + + +##################################################### +# Ulysses Attention Pipeline +##################################################### +def all_to_all_input_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]: + """ + Scatter head_number and gather seq_len, for example: + input: (seq_len, cp * hn, hd) + output: (seq_len * cp, hn, hd) + NOTE: seq_len of input maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()] + """ + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return tensor, FakeHandle() + assert cp_split_sizes is not None + _, hn, _ = tensor.shape + if cp_world_size % hn == 0 and cp_world_size != hn: + tensor = torch.repeat_interleave(tensor, repeats=divide(cp_world_size, hn), dim=1).contiguous() + assert tensor.is_contiguous() + input = rearrange(tensor, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + output = torch.empty([sum(cp_split_sizes), *input.shape[1:]], device=input.device, dtype=input.dtype) + handle = torch.distributed.all_to_all_single( + output, input, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + return output, handle + + +def all_to_all_output_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]: + """ + Scatter seq_len and gather head_number, for example: + input: (seq_len * cp, hn, hd) + output: (seq_len, cp * hn, hd) + NOTE: seq_len of output maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()] + """ + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return tensor, FakeHandle() + assert cp_split_sizes is not None + assert tensor.is_contiguous() + _, hn, _ = tensor.shape + output = torch.empty( + [cp_split_sizes[mpu.get_cp_rank()] * cp_world_size, *tensor.shape[1:]], device=tensor.device, dtype=tensor.dtype + ) + handle = torch.distributed.all_to_all_single( + output, tensor, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + return output, handle + + +def fused_qkv_communication( + q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cp_split_sizes: List[int] +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + cp_world_size = mpu.get_cp_world_size() + if cp_world_size == 1: + return q, k, v + assert cp_split_sizes is not None + _, k_head, _ = k.shape + if cp_world_size % k_head == 0 and cp_world_size != k_head: + k = torch.repeat_interleave(k, repeats=divide(cp_world_size, k_head), dim=1) + v = torch.repeat_interleave(v, repeats=divide(cp_world_size, k_head), dim=1) + + q = rearrange(q, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + k = rearrange(k, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + v = rearrange(v, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous() + head_split_number = [q.shape[1], k.shape[1], v.shape[1]] + qkv = torch.cat([q, k, v], dim=1).contiguous() + + qkv_output = torch.empty([sum(cp_split_sizes), *qkv.shape[1:]], device=qkv.device, dtype=qkv.dtype) + torch.distributed.all_to_all_single( + qkv_output, qkv, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=False + ) + q, k, v = torch.split(qkv_output, head_split_number, dim=1) + return q, k, v + + +class UlyssesScheduler: + def __init__(self): + pass + + @staticmethod + def get_attn_and_xattn_with_comm_overlap( + get_q_func: Callable, # [seq hn hd] + get_k_func: Callable, # [seq hn hd] + get_v_func: Callable, # [seq hn hd] + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + Get Q, K, V with communication overlap. + Input: + get_q: Callable, function to get q, shape [b, sq, hn, hd] + get_k: Callable, function to get k, shape [sq, b, hn, hd] + get_v: Callable, function to get v, shape [sq, b, hn, hd] + NOTE: Why follow such compute and comm order? + 1. v_compute + 2. k_compute(overlap with v_comm) + 3. q_compute(overlap with k_comm) + 4. kv_cache_func(overlap with q_comm) + Follow the principle: We need to begin comm as soon as possible to hide the comm latency. + The computation flops and commnunication order is: + flops order: q_compute (larger hidden_size + layernorm) > k_compute (layernorm) > v_compute + comm order: q_compute (larger hidden_size) > k_compute = v_compute + """ + value = get_v_func() + value, handle_v = all_to_all_input_split(value, cp_split_sizes) + key = get_k_func() + key, handle_k = all_to_all_input_split(key, cp_split_sizes) + query = get_q_func() + query, handle_q = all_to_all_input_split(query, cp_split_sizes) + + handle_v.wait() + handle_k.wait() + kv = torch.concat([key, value], dim=-1) + + key, value = kv_cache_func(kv) + handle_q.wait() + return UlyssesScheduler.get_attn_and_xattn_base( + query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + @staticmethod + def get_attn_and_xattn_with_fused_kv_comm( + get_q_func: Callable, + get_kv_func: Callable, + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + When seq_len is very small, CPU-bound issues are severe. By fusing kv communication, + CPU operations and the number of kernel launches are reduced. + """ + kv = get_kv_func() + kv, handle_kv = all_to_all_input_split(kv, cp_split_sizes) + query = get_q_func() + query, handle_q = all_to_all_input_split(query, cp_split_sizes) + handle_kv.wait() + key, value = kv_cache_func(kv) + handle_q.wait() + return UlyssesScheduler.get_attn_and_xattn_base( + query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + def get_attn_and_xattn_with_fused_qkv_comm( + get_qkv_func: Callable, + kv_cache_func: Callable, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + """ + By fusing the communication of q, k, and v together, further optimize CPU-bound issues. + """ + q, k, v = get_qkv_func() + q, k, v = fused_qkv_communication(q, k, v, cp_split_sizes) + k, v = kv_cache_func(torch.cat([k, v], dim=-1)) + return UlyssesScheduler.get_attn_and_xattn_base( + q, k, v, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes + ) + + @staticmethod + def get_attn_and_xattn_base( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + core_attn_func: Callable, + cross_attn_func: Callable, + overlap_degree: int, + batch_size: int, + cp_size: int, + cp_split_sizes: List[int] = None, + ): + # Split Query, Key, Value into multiple parts + # k/v may have different sequence length with q due to kv cache + q_seq, q_head, q_hidden = query.shape + kv_seq, kv_head, kv_hidden = key.shape + if overlap_degree == -1: + overlap_degree = q_head // kv_head + else: + assert overlap_degree <= q_head + + if overlap_degree == 1: + query = [query] + elif kv_head == 1: # MQA + query = query.chunk(overlap_degree, dim=1) + else: # GQA + assert q_head % (overlap_degree * kv_head) == 0 + query = query.reshape(q_seq, kv_head, -1, q_hidden) + query = query.chunk(overlap_degree, dim=2) + query = [q.reshape(q_seq, -1, q_hidden) for q in query] + + # Compute Core Attention + handle_attn = None + core_attn_out = None + core_attn_outs = [] + for i in range(overlap_degree): + core_attn_out_new = core_attn_func(query[i], key, value) + if not torch.isfinite(core_attn_out_new).all(): + import pdb; pdb.set_trace() + if handle_attn is not None: + handle_attn.wait() + core_attn_outs.append(core_attn_out) + core_attn_out, handle_attn = all_to_all_output_split(core_attn_out_new, cp_split_sizes) + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + + xattn_out = cross_attn_func() + handle_attn.wait() + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + core_attn_outs.append(core_attn_out) + core_attn_out = torch.cat(core_attn_outs, dim=1) + + if not torch.isfinite(core_attn_out).all(): + import pdb; pdb.set_trace() + + core_attn_out = rearrange(core_attn_out, "(cp sq b) hn hd -> (sq) b (cp hn hd)", cp=cp_size, b=batch_size) + return core_attn_out, xattn_out + + +##################################################### +# CSO(context shuffle overlap) Attention Pipeline +##################################################### +def cso_communication( + input: torch.Tensor, cp_world_size: int, cp_split_sizes: List[int], comm_type: str = None +) -> Tuple[torch.Tensor, torch.distributed.Work]: + if cp_world_size == 1: + return input, FakeHandle() + assert cp_split_sizes is not None + _, hn, _ = input.shape + if comm_type == "kv": + if cp_world_size % hn == 0 and cp_world_size != hn: + input = torch.repeat_interleave(input, repeats=divide(cp_world_size, hn), dim=1) + input = rearrange(input, "spb (cp hn) hd -> (cp spb) hn hd", cp=cp_world_size).contiguous() + output = torch.empty(input.shape, device=input.device, dtype=input.dtype) + + handle = torch.distributed.all_to_all_single( + output, input, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True + ) + + return output, handle + + +class CSOHelper: + def __init__(self, cp_shuffle_num, cp_world_size, cp_split_sizes): + self.cp_shuffle_num = cp_shuffle_num + self.cp_world_size = cp_world_size + self.cp_split_sizes = [divide(x, self.cp_shuffle_num) for x in cp_split_sizes] + + def split_query_for_overlap(self, query): + query = rearrange( + query, "(dn spb) (cp hn) hd -> (dn cp spb) hn hd", cp=self.cp_world_size, dn=self.cp_shuffle_num + ).contiguous() + querys = list(torch.chunk(query, self.cp_shuffle_num, dim=0)) + querys[0], handle_q = cso_communication(querys[0], self.cp_world_size, self.cp_split_sizes) + return querys, handle_q + + def overlap(self, fattn, qs, k, v): + core_attn_outs = [] + for i in range(self.cp_shuffle_num): + if self.cp_shuffle_num == 1: + q = qs[0] + elif i == 0: + q = qs[0] + loop_var, loop_handle = cso_communication(qs[i + 1], self.cp_world_size, self.cp_split_sizes) + else: + loop_handle.wait() + if loop_var.numel() == qs[0].numel(): + q = loop_var + else: + assert loop_var.numel() == qs[0].numel() * 2 + q, ready_o = torch.chunk(loop_var, 2, dim=-1) + core_attn_outs.append(ready_o) + loop_var = torch.concat([qs[i + 1], o], dim=-1) if i < self.cp_shuffle_num - 1 else o + loop_var, loop_handle = cso_communication(loop_var, self.cp_world_size, self.cp_split_sizes) + + o = fattn(q, k, v, i) + if i == self.cp_shuffle_num - 1: + if i != 0: + loop_handle.wait() + assert loop_var.numel() == qs[0].numel() + core_attn_outs.append(loop_var) + last_o, handle_attn = cso_communication(o, self.cp_world_size, self.cp_split_sizes) + core_attn_outs.append(last_o) + return core_attn_outs, handle_attn diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/pipeline_parallel.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/pipeline_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..d97c91112392843d089f35eb3b28f7f6ed4674f5 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/pipeline_parallel.py @@ -0,0 +1,123 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import queue +from dataclasses import dataclass +from typing import Optional + +import torch + +from inference.infra.distributed import parallel_state as mpu + + +@dataclass +class TensorAndHandler: + tensor: torch.Tensor + handler: torch.distributed.Work + + +class PPScheduler: + def __init__(self): + """Initialize an instance of the PPScheduler class""" + + self.device: torch.device = torch.device(f"cuda:{torch.cuda.current_device()}") + self.recv_queue: queue.Queue = queue.Queue() + + def isend_next(self, tensor: torch.Tensor) -> torch.distributed.Work: + """Asynchronously send a tensor to the next pipeline and return the send handle. + + Args: + tensor (torch.Tensor): The tensor to be sent. + + Returns: + torch.distributed.Work: The handle for the send operation. + """ + handle = torch.distributed.isend( + tensor.contiguous(), dst=mpu.get_pipeline_model_parallel_next_rank(), group=mpu.get_pp_group() + ) + return handle + + def irecv_prev(self, buffer: torch.Tensor) -> torch.distributed.Work: + """Asynchronously receive a tensor from the previous pipeline and return the receive handle. + + Args: + buffer (torch.Tensor): The buffer tensor for receiving data. + + Returns: + torch.distributed.Work: The handle for the receive operation. + """ + handle = torch.distributed.irecv(buffer, src=mpu.get_pipeline_model_parallel_prev_rank(), group=mpu.get_pp_group()) + return handle + + def recv_prev_data(self, shape: torch.Size, dtype: torch.dtype) -> torch.Tensor: + """Receive data from the previous pipeline and return the received tensor. + + Args: + shape (torch.Size): The shape of the tensor to receive. + dtype (torch.dtype): The data type of the tensor to receive. + + Returns: + torch.Tensor: The received tensor. + """ + recv_tensor = torch.empty(shape, dtype=dtype, device=self.device) + self.irecv_prev(recv_tensor).wait() + return recv_tensor + + def queue_irecv_prev(self, shape: torch.Size, dtype: torch.dtype) -> None: + """Put the asynchronously received tensor and handle into the receive queue. + + Args: + shape (torch.Size): The shape of the tensor to receive. + dtype (torch.dtype): The data type of the tensor to receive. + """ + recv_tensor = torch.empty(shape, dtype=dtype, device=self.device) + handle = self.irecv_prev(recv_tensor) + self.recv_queue.put(TensorAndHandler(tensor=recv_tensor, handler=handle)) + + def queue_irecv_prev_data(self) -> torch.Tensor: + """Get a tensor from the receive queue and wait for the receive operation to complete. + + Returns: + torch.Tensor: The received tensor obtained from the queue. + """ + tensor_and_handler = self.recv_queue.get() + tensor_and_handler.handler.wait() + return tensor_and_handler.tensor + + +_PP_SCHEDULER: Optional[PPScheduler] = None + + +def init_pp_scheduler(): + """Initialize the PPScheduler instance. + + Raises: + AssertionError: If the PPScheduler is already initialized. + """ + global _PP_SCHEDULER + assert _PP_SCHEDULER is None, "pipeline model parallel group is already initialized" + _PP_SCHEDULER = PPScheduler() + + +def pp_scheduler() -> PPScheduler: + """Get the current PPScheduler instance. + + Returns: + PPScheduler: The current PPScheduler instance. + + Raises: + AssertionError: If the PPScheduler has not been initialized. + """ + assert _PP_SCHEDULER is not None, "pipeline model parallel group is not initialized" + return _PP_SCHEDULER diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/tile_parallel.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/tile_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe0c1b78b4b69e96b9b9e1b1d365b968561199d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/infra/parallelism/tile_parallel.py @@ -0,0 +1,448 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import OrderedDict +from typing import List + +import torch +from tqdm import tqdm + + +class ParallelHelper: + def __init__(self): + pass + + @staticmethod + def split_tile_list( + tile_numel_dict: OrderedDict[int, int], parallel_group: torch.distributed.ProcessGroup = None + ) -> List[int]: + """ + Splits the given tile size into a list of sizes that each rank should handle. + + This method takes into account the number of ranks in a distributed setting. + If the distributed environment is not initialized, it returns a list of + integers from 0 to tile_size - 1, representing each tile index. + + If the distributed environment is initialized, it calculates the base tile size + for each rank and distributes any remaining tiles among the ranks. + + Args: + tile_numel_dict (OrderedDict[int, int]): Dict of index and numel of tiles. + parallel_group (torch.distributed.ProcessGroup, optional): + Distributed decoding group. Defaults to None. + + Returns: + List[int]: A list of tile indices assigned to the current rank. + List[int]: A list of global tile indices. + """ + if not torch.distributed.is_initialized(): + return list(range(len(tile_numel_dict))), list(range(len(tile_numel_dict))) + else: + tile_idxs = list(OrderedDict(sorted(tile_numel_dict.items(), key=lambda x: x[1], reverse=True)).keys()) + world_size = torch.distributed.get_world_size(group=parallel_group) + cur_rank = torch.distributed.get_rank(group=parallel_group) + global_tile_idxs = [] + cur_rank_tile_idxs = [] + for rank in range(world_size): + rank_tile_idxs = [tile_idxs[rank + world_size * i] for i in range(len(tile_idxs) // world_size)] + if rank < len(tile_idxs) % world_size: + rank_tile_idxs.append(tile_idxs[len(tile_idxs) // world_size * world_size + rank]) + if rank == cur_rank: + cur_rank_tile_idxs = rank_tile_idxs + global_tile_idxs = global_tile_idxs + rank_tile_idxs + return cur_rank_tile_idxs, global_tile_idxs + + @staticmethod + def gather_frames( + frames: List[torch.Tensor], global_tile_idxs: List[int], parallel_group: torch.distributed.ProcessGroup = None + ) -> List[torch.Tensor]: + """ + Gathers frame data from all ranks in a distributed environment. + + This method collects frames from all ranks and combines them into a single list. + If the distributed environment is not initialized, it simply returns the input frames. + + Args: + frames (List[torch.Tensor]): A list of frames (tensors) from the current rank. + global_tile_idxs (List[int]): A list of global tile indices. + parallel_group (torch.distributed.ProcessGroup, optional): + Distributed decoding group. Defaults to None. + + Returns: + List[torch.Tensor]: A list of frames (tensors) from all ranks. + """ + if not torch.distributed.is_initialized(): + return frames + else: + # assert len(frames) > 0 + # Communicate shapes + if len(frames) == 0: + cur_rank_shapes = [] + else: + cur_rank_shapes = [frame.shape for frame in frames] + all_rank_shapes = [None] * torch.distributed.get_world_size(group=parallel_group) + torch.distributed.all_gather_object(all_rank_shapes, cur_rank_shapes, group=parallel_group) + + all_rank_sizes = [] + total_size = [] + for per_rank_shapes in all_rank_shapes: + per_rank_sizes = [] + per_rank_total_size = 0 + for shape in per_rank_shapes: + per_rank_sizes.append(shape[0] * shape[1] * shape[2] * shape[3] * shape[4]) + per_rank_total_size += shape[0] * shape[1] * shape[2] * shape[3] * shape[4] + all_rank_sizes.append(per_rank_sizes) + total_size.append(per_rank_total_size) + + # Gather all frames + if len(frames) == 0: + flattened_frames = torch.zeros([0], dtype=torch.bfloat16, device="cuda") + else: + flattened_frames = torch.cat([frame.flatten().contiguous() for frame in frames], dim=0) + assert flattened_frames.dtype == torch.bfloat16 + gather_tensors = [ + torch.zeros(total_size[i], dtype=torch.bfloat16, device="cuda") + for i in range(torch.distributed.get_world_size(group=parallel_group)) + ] + torch.distributed.all_gather(gather_tensors, flattened_frames, group=parallel_group) + + result_frames = [] + for idx, per_rank_shapes in enumerate(all_rank_shapes): + offset = 0 + for j, shape in enumerate(per_rank_shapes): + result_frames.append(gather_tensors[idx][offset : offset + all_rank_sizes[idx][j]].view(shape)) + offset += all_rank_sizes[idx][j] + result_frames_dict = OrderedDict((idx, frame) for idx, frame in zip(global_tile_idxs, result_frames)) + result_frames = list(OrderedDict(sorted(result_frames_dict.items())).values()) + return result_frames + + @staticmethod + def index_undot(index: int, loop_size: List[int]) -> List[int]: + """ + Converts a single index into a list of indices, representing the position in a multi-dimensional space. + + This method takes an integer index and a list of loop sizes, and converts the index into a list of indices + that correspond to the position in a multi-dimensional space. + + Args: + index (int): The single index to be converted. + loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space. + + Returns: + List[int]: A list of integers representing the position in the multi-dimensional space. + """ + undotted_index = [] + for i in range(len(loop_size) - 1, -1, -1): + undotted_index.append(index % loop_size[i]) + index = index // loop_size[i] + undotted_index.reverse() + assert len(undotted_index) == len(loop_size) + return undotted_index + + @staticmethod + def index_dot(index: List[int], loop_size: List[int]) -> int: + """ + Converts a list of indices into a single index, representing the position in a multi-dimensional space. + + This method takes a list of indices and a list of loop sizes, and converts the list of indices into a single index + that corresponds to the position in a multi-dimensional space. + + Args: + index (List[int]): A list of integers representing the position in the multi-dimensional space. + loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space. + + Returns: + int: A single integer representing the position in the multi-dimensional space. + """ + assert len(index) == len(loop_size) + dot_index = 0 + strides = [1] + for i in range(len(loop_size) - 1, -1, -1): + strides.append(strides[-1] * loop_size[i]) + strides.reverse() + strides = strides[1:] + assert len(index) == len(strides) + for i in range(len(index)): + dot_index += index[i] * strides[i] + return dot_index + + +class TileProcessor: + def __init__( + self, + encode_fn, + decode_fn, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + tile_sample_min_length: int = 16, + spatial_downsample_factor: int = 8, + temporal_downsample_factor: int = 1, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + sr_ratio=1, + first_frame_as_image: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ): + """ + Initializes an instance of the class. + + Args: + encode_fn (function): The encoding function used for tile sampling. + decode_fn (function): The decoding function used for tile reconstruction. + tile_sample_min_size (int, optional): The minimum size of the sampled tiles. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of the sampled tiles. Defaults to 16. + spatial_downsample_factor (int, optional): The actual spataial downsample factor of given encode_fn. Defaults to 8. + temporal_downsample_factor (int, optional): The actual temporal downsample factor of the latent space tiles. Defaults to 1. + tile_overlap_factor (float, optional): The overlap factor between adjacent tiles. Defaults to 0.25. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed decoding group. Defaults to None. + """ + self.encode_fn = encode_fn + self.decode_fn = decode_fn + + self.spatial_downsample_factor = spatial_downsample_factor + self.temporal_downsample_factor = temporal_downsample_factor + self.tile_sample_min_height = tile_sample_min_height + self.tile_sample_min_width = tile_sample_min_width + self.tile_sample_min_length = tile_sample_min_length + self.tile_latent_min_height = tile_sample_min_height // spatial_downsample_factor + self.tile_latent_min_width = tile_sample_min_width // spatial_downsample_factor + + self.tile_latent_min_length = tile_sample_min_length // temporal_downsample_factor + if first_frame_as_image: + self.tile_latent_min_length += 1 + + self.spatial_tile_overlap_factor = spatial_tile_overlap_factor + self.temporal_tile_overlap_factor = temporal_tile_overlap_factor + self.sr_ratio = sr_ratio + self.parallel_group = parallel_group + + def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[2], b.shape[2], blend_extent) + for t in range(blend_extent): + b[:, :, t, :, :] = a[:, :, -blend_extent + t, :, :] * (1 - t / blend_extent) + b[:, :, t, :, :] * ( + t / blend_extent + ) + return b + + def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[3], b.shape[3], blend_extent) + for y in range(blend_extent): + b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( + y / blend_extent + ) + return b + + def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: + blend_extent = min(a.shape[4], b.shape[4], blend_extent) + for x in range(blend_extent): + b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( + x / blend_extent + ) + return b + + def tiled_encode(self, x: torch.FloatTensor, verbose: bool = False): + overlap_height = int(self.tile_sample_min_height * (1 - self.spatial_tile_overlap_factor)) + overlap_width = int(self.tile_sample_min_width * (1 - self.spatial_tile_overlap_factor)) + overlap_length = int(self.tile_sample_min_length * (1 - self.temporal_tile_overlap_factor)) + blend_extent_h = int(self.tile_latent_min_height * self.spatial_tile_overlap_factor) + blend_extent_w = int(self.tile_latent_min_width * self.spatial_tile_overlap_factor) + blend_extent_t = int(self.tile_latent_min_length * self.temporal_tile_overlap_factor) + height_limit = self.tile_latent_min_height - blend_extent_h + width_limit = self.tile_latent_min_width - blend_extent_w + frame_limit = self.tile_latent_min_length - blend_extent_t + + length_tile_size = (x.shape[2] + overlap_length - 1) // overlap_length + height_tile_size = (x.shape[3] + overlap_height - 1) // overlap_height + width_tile_size = (x.shape[4] + overlap_width - 1) // overlap_width + total_tile_size = length_tile_size * height_tile_size * width_tile_size + for_loop_size = [length_tile_size, height_tile_size, width_tile_size] + + tiles = [] + tile_numel_dict = OrderedDict() + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f_idx, i_idx, j_idx = undot_tile_index + f = f_idx * overlap_length + i = i_idx * overlap_height + j = j_idx * overlap_width + + # Extract the tile from the latent representation and decode it + tile = x[ + :, + :, + f : f + self.tile_sample_min_length, + i : i + self.tile_sample_min_height, + j : j + self.tile_sample_min_width, + ] + tiles.append(tile) + tile_numel_dict[tile_index] = tile.numel() + tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list( + tile_numel_dict, parallel_group=self.parallel_group + ) + progress_bar = tqdm( + total=len(tile_index_list), + desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Encoding Tiles", + disable=not verbose, + ) + + frames = [] + # Encode each tile based on the tile index list + for tile_index in tile_index_list: + tile = tiles[tile_index] + encoded = self.encode_fn(tile) + frames.append(encoded) + progress_bar.update(1) + + # Gather all decoded frames from different ranks + frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(frames) == total_tile_size + progress_bar.close() + + result_frames = [] + # Blend the encoded tiles to create the final output + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f, i, j = undot_tile_index + + tile = frames[tile_index] + # Blend with previous tiles if applicable + if f > 0: + idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size) + tile = self.blend_t(frames[idx], tile, blend_extent_t) + if i > 0: + idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size) + tile = self.blend_v(frames[idx], tile, blend_extent_h) + if j > 0: + idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size) + tile = self.blend_h(frames[idx], tile, blend_extent_w) + result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit]) + + assert len(result_frames) == total_tile_size + + concat_frames = [] + for f in range(length_tile_size): + result_rows = [] + for i in range(height_tile_size): + result_row = [] + for j in range(width_tile_size): + idx = ParallelHelper.index_dot([f, i, j], for_loop_size) + result_row.append(result_frames[idx]) + result_rows.append(torch.cat(result_row, dim=4)) + concat_frames.append(torch.cat(result_rows, dim=3)) + + # Concatenate all result frames along the temporal dimension + result = torch.cat(concat_frames, dim=2) + return result + + def tiled_decode(self, z: torch.FloatTensor, verbose: bool = False): + overlap_height = int(self.tile_latent_min_height * (1 - self.spatial_tile_overlap_factor)) + overlap_width = int(self.tile_latent_min_width * (1 - self.spatial_tile_overlap_factor)) + overlap_length = int(self.tile_latent_min_length * (1 - self.temporal_tile_overlap_factor)) + + real_tile_sample_min_height = int(self.tile_latent_min_height * self.spatial_downsample_factor * self.sr_ratio) + real_tile_sample_min_width = int(self.tile_latent_min_width * self.spatial_downsample_factor * self.sr_ratio) + real_tile_sample_min_length = int(self.tile_latent_min_length * self.temporal_downsample_factor) + + blend_extent_h = int(real_tile_sample_min_height * self.spatial_tile_overlap_factor) + blend_extent_w = int(real_tile_sample_min_width * self.spatial_tile_overlap_factor) + blend_extent_t = int(real_tile_sample_min_length * self.temporal_tile_overlap_factor) + + height_limit = real_tile_sample_min_height - blend_extent_h + width_limit = real_tile_sample_min_width - blend_extent_w + frame_limit = real_tile_sample_min_length - blend_extent_t + + length_tile_size = (z.shape[2] + overlap_length - 1) // overlap_length + height_tile_size = (z.shape[3] + overlap_height - 1) // overlap_height + width_tile_size = (z.shape[4] + overlap_width - 1) // overlap_width + total_tile_size = length_tile_size * height_tile_size * width_tile_size + for_loop_size = [length_tile_size, height_tile_size, width_tile_size] + + tiles = [] + tile_numel_dict = OrderedDict() + for tile_index in range(total_tile_size): + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f_idx, i_idx, j_idx = undot_tile_index + f = f_idx * overlap_length + i = i_idx * overlap_height + j = j_idx * overlap_width + + # Extract the tile from the latent representation and decode it + tile = z[ + :, + :, + f : f + self.tile_latent_min_length, + i : i + self.tile_latent_min_height, + j : j + self.tile_latent_min_width, + ] + tiles.append(tile) + tile_numel_dict[tile_index] = tile.numel() + tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list( + tile_numel_dict, parallel_group=self.parallel_group + ) + progress_bar = tqdm( + total=len(tile_index_list), + desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Decoding Tiles", + disable=not verbose, + ) + + frames = [] + # Decode each tile based on the tile index list + for tile_index in tile_index_list: + tile = tiles[tile_index] + decoded = self.decode_fn(tile) + frames.append(decoded) + progress_bar.update(1) + + progress_bar.close() + # Gather all decoded frames from different ranks + frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(frames) == total_tile_size + + result_frames = [] + # Blend the decoded tiles to create the final output + for tile_index in tile_index_list: + undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size) + f, i, j = undot_tile_index + + tile = frames[tile_index].clone() + # Blend with previous tiles if applicable + if f > 0: + idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size) + tile = torch.compile(self.blend_t, dynamic=False)(frames[idx], tile, blend_extent_t) + if i > 0: + idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size) + tile = torch.compile(self.blend_v, dynamic=False)(frames[idx], tile, blend_extent_h) + if j > 0: + idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size) + tile = torch.compile(self.blend_h, dynamic=False)(frames[idx], tile, blend_extent_w) + result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit]) + + # Gather and concatenate the final result frames + result_frames = ParallelHelper.gather_frames(result_frames, global_tile_index_list, parallel_group=self.parallel_group) + assert len(result_frames) == total_tile_size + + concat_frames = [] + for f in range(length_tile_size): + result_rows = [] + for i in range(height_tile_size): + result_row = [] + for j in range(width_tile_size): + idx = ParallelHelper.index_dot([f, i, j], for_loop_size) + result_row.append(result_frames[idx]) + result_rows.append(torch.cat(result_row, dim=4)) + concat_frames.append(torch.cat(result_rows, dim=3)) + + # Concatenate all result frames along the temporal dimension + result = torch.cat(concat_frames, dim=2) + return result diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..518895680251c2b1e91bd1a67426e1bd12ba9e08 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .dit_model import get_dit, VideoDiTModel +from .dit_module import FullyParallelAttention + +__all__ = ["get_dit", "VideoDiTModel", "FullyParallelAttention"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acf3bd371c8d9e4318a95e8cd2f7c84459e5e377 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0890233b3a89bd1d837e8c6b3214ae40d73e4048 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea6d63fddc7d2a4443555c07d55b69374f7e6330 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..155aaa26a9b1b3d8c59c5cb4ef7f5b66b860c9ad Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_model.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b916ca7c2697e7ff84ae63de6b3fc6514bba8a6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87945c00bef7641671e9da87871d118e09638cb9 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/__pycache__/dit_module.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_model.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b6cd2d98c52322baa2bf6519705e4a4cc65dd0c5 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_model.py @@ -0,0 +1,733 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import math +import os +from typing import Tuple + +import torch +import torch.distributed +import torch.nn as nn +from einops import rearrange + +from inference.common import ( + InferenceParams, + MagiConfig, + ModelMetaArgs, + PackedCoreAttnParams, + PackedCrossAttnParams, + env_is_true, + print_per_rank, + print_rank_0, +) +from inference.infra.checkpoint import load_checkpoint +from inference.infra.distributed import parallel_state as mpu +from inference.infra.parallelism import cp_post_process, cp_pre_process, pp_scheduler + +from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock + + +class VideoDiTModel(torch.nn.Module): + """VideoDiT model for video diffusion. + + Args: + config (MagiConfig): Transformer config + pre_process (bool, optional): Include embedding layer (used with pipeline parallelism). Defaults to True. + post_process (bool, optional): Include an output layer (used with pipeline parallelism). Defaults to True. + """ + + def __init__(self, config: MagiConfig, pre_process: bool = True, post_process: bool = True) -> None: + super().__init__() + + self.model_config = config.model_config + self.runtime_config = config.runtime_config + self.engine_config = config.engine_config + + self.pre_process = pre_process + self.post_process = post_process + self.in_channels = self.model_config.in_channels + self.out_channels = self.model_config.out_channels + self.patch_size = self.model_config.patch_size + self.t_patch_size = self.model_config.t_patch_size + self.caption_max_length = self.model_config.caption_max_length + self.num_heads = self.model_config.num_attention_heads + + self.x_embedder = nn.Conv3d( + self.model_config.in_channels, + self.model_config.hidden_size, + kernel_size=(self.model_config.t_patch_size, self.model_config.patch_size, self.model_config.patch_size), + stride=(self.model_config.t_patch_size, self.model_config.patch_size, self.model_config.patch_size), + bias=False, + ) + self.t_embedder = TimestepEmbedder(model_config=self.model_config) + self.y_embedder = CaptionEmbedder(model_config=self.model_config) + self.rope = LearnableRotaryEmbeddingCat( + self.model_config.hidden_size // self.model_config.num_attention_heads, in_pixels=False + ) + + # trm block + self.videodit_blocks = TransformerBlock( + model_config=self.model_config, + engine_config=self.engine_config, + pre_process=pre_process, + post_process=post_process, + ) + + self.final_linear = FinalLinear( + self.model_config.hidden_size, self.model_config.patch_size, self.model_config.t_patch_size, self.out_channels + ) + + def generate_kv_range_for_uncondition(self, uncond_x) -> torch.Tensor: + device = f"cuda:{torch.cuda.current_device()}" + B, C, T, H, W = uncond_x.shape + chunk_token_nums = ( + (T // self.model_config.t_patch_size) * (H // self.model_config.patch_size) * (W // self.model_config.patch_size) + ) + + k_chunk_start = torch.linspace(0, (B - 1) * chunk_token_nums, steps=B).reshape((B, 1)) + k_chunk_end = torch.linspace(chunk_token_nums, B * chunk_token_nums, steps=B).reshape((B, 1)) + return torch.concat([k_chunk_start, k_chunk_end], dim=1).to(torch.int32).to(device) + + def unpatchify(self, x, H, W): + return rearrange( + x, + "(T H W) N (pT pH pW C) -> N C (T pT) (H pH) (W pW)", + H=H, + W=W, + pT=self.t_patch_size, + pH=self.patch_size, + pW=self.patch_size, + ).contiguous() + + @torch.no_grad() + def get_embedding_and_meta(self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs): + """ + Forward embedding and meta for VideoDiT. + NOTE: This function should only handle single card behavior. + + Input: + x: (N, C, T, H, W). torch.Tensor of spatial inputs (images or latent representations of images) + t: (N, denoising_range_num). torch.Tensor of diffusion timesteps + y: (N * denoising_range_num, 1, L, C). torch.Tensor of class labels + caption_dropout_mask: (N). torch.Tensor of whether to drop caption + xattn_mask: (N * denoising_range_num, 1, L). torch.Tensor of xattn mask + kv_range: (N * denoising_range_num, 2). torch.Tensor of kv range + + Output: + x: (S, N, D). torch.Tensor of inputs embedding (images or latent representations of images) + condition: (N, denoising_range_num, D). torch.Tensor of condition embedding + condition_map: (S, N). torch.Tensor determine which condition to use for each token + rope: (S, 96). torch.Tensor of rope + y_xattn_flat: (total_token, D). torch.Tensor of y_xattn_flat + cuda_graph_inputs: (y_xattn_flat, xattn_mask) or None. None means no cuda graph + NOTE: y_xattn_flat and xattn_mask with static shape + H: int. Height of the input + W: int. Width of the input + ardf_meta: dict. Meta information for ardf + cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten + """ + + ################################### + # Part1: Embed x # + ################################### + x = self.x_embedder(x) # [N, C, T, H, W] + batch_size, _, T, H, W = x.shape + + # Prepare necessary variables + range_num = kwargs["range_num"] + denoising_range_num = kwargs["denoising_range_num"] + slice_point = kwargs.get("slice_point", 0) + frame_in_range = T // denoising_range_num + prev_clean_T = frame_in_range * slice_point + T_total = T + prev_clean_T + + ################################### + # Part2: rope # + ################################### + # caculate rescale_factor for multi-resolution & multi aspect-ratio training + # the base_size [16*16] is A predefined size based on data:(256x256) vae: (8,8,4) patch size: (1,1,2) + # This definition do not have any relationship with the actual input/model/setting. + # ref_feat_shape is used to calculate innner rescale factor, so it can be float. + rescale_factor = math.sqrt((H * W) / (16 * 16)) + rope = self.rope.get_embed(shape=[T_total, H, W], ref_feat_shape=[T_total, H / rescale_factor, W / rescale_factor]) + # the shape of rope is (T*H*W, -1) aka (seq_length, head_dim), as T is the first dimension, we can directly cut it. + rope = rope[-(T * H * W) :] + + + ################################### + # Part3: Embed t # + ################################### + assert t.shape[0] == batch_size, f"Invalid t shape, got {t.shape[0]} != {batch_size}" # nolint + assert t.shape[1] == denoising_range_num, f"Invalid t shape, got {t.shape[1]} != {denoising_range_num}" # nolint + t_flat = t.flatten() # (N * denoising_range_num,) + t = self.t_embedder(t_flat) # (N, D) + + if self.engine_config.distill: + distill_dt_scalar = 2 + if kwargs["num_steps"] == 12: + base_chunk_step = 4 + distill_dt_factor = base_chunk_step / kwargs["distill_interval"] * distill_dt_scalar + else: + distill_dt_factor = kwargs["num_steps"] / 4 * distill_dt_scalar + distill_dt = torch.ones_like(t_flat) * distill_dt_factor + distill_dt_embed = self.t_embedder(distill_dt) + t = t + distill_dt_embed + t = t.reshape(batch_size, denoising_range_num, -1) # (N, range_num, D) + + ###################################################### + # Part4: Embed y, prepare condition and y_xattn_flat # + ###################################################### + # (N * denoising_range_num, 1, L, D) + y_xattn, y_adaln = self.y_embedder(y, self.training, caption_dropout_mask) + + assert xattn_mask is not None + xattn_mask = xattn_mask.squeeze(1).squeeze(1) + + # condition: (N, range_num, D) + y_adaln = y_adaln.squeeze(1) # (N, D) + condition = t + y_adaln.unsqueeze(1) + + assert condition.shape[0] == batch_size + assert condition.shape[1] == denoising_range_num + seqlen_per_chunk = (T * H * W) // denoising_range_num + condition_map = torch.arange(batch_size * denoising_range_num, device=x.device) + condition_map = torch.repeat_interleave(condition_map, seqlen_per_chunk) + condition_map = condition_map.reshape(batch_size, -1).transpose(0, 1).contiguous() + + # y_xattn_flat: (total_token, D) + y_xattn_flat = torch.masked_select(y_xattn.squeeze(1), xattn_mask.unsqueeze(-1).bool()).reshape(-1, y_xattn.shape[-1]) + xattn_mask_for_cuda_graph = None + + ###################################################### + # Part5: Prepare cross_attn_params for cross_atten # + ###################################################### + # (N * denoising_range_num, L) + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + y_index = torch.sum(xattn_mask, dim=-1) + clip_token_nums = H * W * frame_in_range + + cu_seqlens_q = torch.Tensor([0] + ([clip_token_nums] * denoising_range_num * batch_size)).to(torch.int64).to(x.device) + cu_seqlens_k = torch.cat([y_index.new_tensor([0]), y_index]).to(torch.int64).to(x.device) + cu_seqlens_q = cu_seqlens_q.cumsum(-1).to(torch.int32) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + + assert ( + cu_seqlens_q.shape == cu_seqlens_k.shape + ), f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}" + + xattn_q_ranges = torch.cat([cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1) + xattn_k_ranges = torch.cat([cu_seqlens_k[:-1].unsqueeze(1), cu_seqlens_k[1:].unsqueeze(1)], dim=1) + assert ( + xattn_q_ranges.shape == xattn_k_ranges.shape + ), f"xattn_q_ranges.shape: {xattn_q_ranges.shape}, xattn_k_ranges.shape: {xattn_k_ranges.shape}" + + cross_attn_params = PackedCrossAttnParams( + q_ranges=xattn_q_ranges, + kv_ranges=xattn_k_ranges, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=clip_token_nums, + max_seqlen_kv=self.caption_max_length, + ) + + ################################################## + # Part6: Prepare core_atten related q/kv range # + ################################################## + q_range = torch.cat([cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1) + flat_kv = torch.unique(kv_range, sorted=True) + max_seqlen_k = (flat_kv[-1] - flat_kv[0]).cpu().item() + + ardf_meta = dict( + clip_token_nums=clip_token_nums, + slice_point=slice_point, + range_num=range_num, + denoising_range_num=denoising_range_num, + q_range=q_range, + k_range=kv_range, + max_seqlen_q=clip_token_nums, + max_seqlen_k=max_seqlen_k, + ) + + return (x, condition, condition_map, rope, y_xattn_flat, xattn_mask_for_cuda_graph, H, W, ardf_meta, cross_attn_params) + + @torch.no_grad() + def forward_pre_process( + self, x, t, y, caption_dropout_mask=None, xattn_mask=None, kv_range=None, **kwargs + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, ModelMetaArgs]: + assert kv_range is not None, "Please ensure kv_range is provided" + + x = x * self.model_config.x_rescale_factor + + if self.model_config.half_channel_vae: + assert x.shape[1] == 16 + x = torch.cat([x, x], dim=1) + + x = x.float() + t = t.float() + y = y.float() + # embedder context will ensure that the processing is in high precision even if the embedder params is in bfloat16 mode + with torch.autocast(device_type="cuda", dtype=torch.float32): + ( + x, + condition, + condition_map, + rope, + y_xattn_flat, + xattn_mask_for_cuda_graph, + H, + W, + ardf_meta, + cross_attn_params, + ) = self.get_embedding_and_meta(x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs) + + # Downcast x and rearrange x + x = x.to(self.model_config.params_dtype) + x = rearrange(x, "N C T H W -> (T H W) N C").contiguous() # (thw, N, D) + + # condition and y_xattn_flat will be downcast to bfloat16 in transformer block. + condition = condition.to(self.model_config.params_dtype) + y_xattn_flat = y_xattn_flat.to(self.model_config.params_dtype) + + core_attn_params = PackedCoreAttnParams( + q_range=ardf_meta["q_range"], + k_range=ardf_meta["k_range"], + np_q_range=ardf_meta["q_range"].cpu().numpy(), + np_k_range=ardf_meta["k_range"].cpu().numpy(), + max_seqlen_q=ardf_meta["max_seqlen_q"], + max_seqlen_k=ardf_meta["max_seqlen_k"], + ) + + (x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params) = cp_pre_process( + self.engine_config.cp_size, + self.engine_config.cp_strategy, + x, + condition_map, + rope, + xattn_mask_for_cuda_graph, + ardf_meta, + core_attn_params, + cross_attn_params, + ) + + meta_args = ModelMetaArgs( + H=H, + W=W, + cp_pad_size=cp_pad_size, + cp_split_sizes=cp_split_sizes, + slice_point=ardf_meta["slice_point"], + denoising_range_num=ardf_meta["denoising_range_num"], + range_num=ardf_meta["range_num"], + extract_prefix_video_feature=kwargs.get("extract_prefix_video_feature", False), + fwd_extra_1st_chunk=kwargs["fwd_extra_1st_chunk"], + distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False), + clip_token_nums=ardf_meta["clip_token_nums"], + enable_cuda_graph=xattn_mask_for_cuda_graph is not None, + core_attn_params=core_attn_params, + cross_attn_params=cross_attn_params, + timestep=t, # add to get attention weights for each timestep + get_attn_weights_layer_num=-1, + save_kvcache_every_forward=kwargs.get("save_kvcache_every_forward", False), + cur_denoise_step=kwargs.get("cur_denoise_step", 0), + start_chunk_id=kwargs["start_chunk_id"], + end_chunk_id=kwargs["end_chunk_id"], + compress_kv=kwargs.get("compress_kv", False), + total_cache_len=kwargs.get("total_cache_len", 0), + budget_cache_len=kwargs.get("budget_cache_len", 0), + chunk_num=kwargs["chunk_num"], + debug=kwargs.get("debug", False), + near_clean_chunk_idx=kwargs.get("near_clean_chunk_idx", -1), + ) + + return (x, condition, condition_map, y_xattn_flat, rope, meta_args) + + @torch.no_grad() + def forward_post_process(self, x, meta_args: ModelMetaArgs) -> torch.Tensor: + x = x.float() + # embedder context will ensure that the processing is in high precision even if the embedder params is in bfloat16 mode + with torch.autocast(device_type="cuda", dtype=torch.float32): + x = self.final_linear(x) # (thw/cp, N, patch_size ** 2 * out_channels) + + # leave context parallel region + x = cp_post_process(self.engine_config.cp_size, self.engine_config.cp_strategy, x, meta_args) + + # N C T H W + x = self.unpatchify(x, meta_args.H, meta_args.W) + + if self.model_config.half_channel_vae: + assert x.shape[1] == 32 + x = x[:, :16] + + x = x / self.model_config.x_rescale_factor + + return x + + @torch.no_grad() + def forward( + self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params: InferenceParams = None, + **kwargs, + ) -> torch.Tensor: + (x, condition, condition_map, y_xattn_flat, rope, meta_args) = self.forward_pre_process( + x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + if not self.pre_process: + x = pp_scheduler().recv_prev_data(x.shape, x.dtype) + self.videodit_blocks.set_input_tensor(x) + else: + # clone a new tensor to ensure x is not a view of other tensor + x = x.clone() + + x = self.videodit_blocks.forward( + hidden_states=x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + + if not self.post_process: + pp_scheduler().isend_next(x) + + return self.forward_post_process(x, meta_args) + + def forward_3cfg( + self, x, timestep, y, mask, kv_range, inference_params, **kwargs + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]: + """ + Forward pass of PixArt, but also batches the unconditional forward pass for classifier-free guidance. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + + assert x.shape[0] == 2 + assert mask.shape[0] % 2 == 0 # mask should be a multiple of 2 + x = torch.cat([x[0:1], x[0:1]], dim=0) + caption_dropout_mask = torch.tensor([False, True], dtype=torch.bool, device=x.device) + + inference_params.update_kv_cache = False + out_cond_pre_and_text = self.forward( + x[0:1], + timestep[0:1], + y[0 : y.shape[0] // 2], + caption_dropout_mask=caption_dropout_mask[0:1], + xattn_mask=mask[0 : y.shape[0] // 2], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + inference_params.update_kv_cache = True + out_cond_pre = self.forward( + x[1:2], + timestep[1:2], + y[y.shape[0] // 2 : y.shape[0]], + caption_dropout_mask=caption_dropout_mask[1:2], + xattn_mask=mask[y.shape[0] // 2 : y.shape[0]], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + def chunk_to_batch(input, denoising_range_num): + input = input.squeeze(0) + input = input.reshape(-1, denoising_range_num, kwargs["chunk_width"], *input.shape[2:]) + return input.transpose(0, 1) # (denoising_range_num, chn, chunk_width, h, w) + + def batch_to_chunk(input, denoising_range_num): + input = input.transpose(0, 1) + input = input.reshape(1, -1, denoising_range_num * kwargs["chunk_width"], *input.shape[3:]) + return input + + class UnconditionGuard: + def __init__(self, kwargs): + self.kwargs = kwargs + self.prev_state = { + "range_num": kwargs["range_num"], + "denoising_range_num": kwargs["denoising_range_num"], + "slice_point": kwargs["slice_point"], + "fwd_extra_1st_chunk": kwargs["fwd_extra_1st_chunk"], + } + + def __enter__(self): + if self.kwargs.get("fwd_extra_1st_chunk", False): + self.kwargs["denoising_range_num"] -= 1 + self.kwargs["slice_point"] += 1 + self.kwargs["fwd_extra_1st_chunk"] = False + + def __exit__(self, exc_type, exc_val, exc_tb): + self.kwargs["range_num"] = self.prev_state["range_num"] + self.kwargs["denoising_range_num"] = self.prev_state["denoising_range_num"] + self.kwargs["slice_point"] = self.prev_state["slice_point"] + self.kwargs["fwd_extra_1st_chunk"] = self.prev_state["fwd_extra_1st_chunk"] + + with UnconditionGuard(kwargs): + denoising_range_num = kwargs["denoising_range_num"] + denoise_width = kwargs["chunk_width"] * denoising_range_num + uncond_x = chunk_to_batch(x[0:1, :, -denoise_width:], denoising_range_num) + timestep = timestep[0:1, -denoising_range_num:].transpose(0, 1) + uncond_y = y[y.shape[0] // 2 : y.shape[0]][-denoising_range_num:] + caption_dropout_mask = torch.tensor([True], dtype=torch.bool, device=x.device) + uncond_mask = mask[y.shape[0] // 2 : y.shape[0]][-denoising_range_num:] + uncond_kv_range = self.generate_kv_range_for_uncondition(uncond_x) + + kwargs["range_num"] = 1 + kwargs["denoising_range_num"] = 1 + kwargs["slice_point"] = 0 + out_uncond = self.forward( + uncond_x, + timestep, + uncond_y, + caption_dropout_mask=caption_dropout_mask, + xattn_mask=uncond_mask, + kv_range=uncond_kv_range, + inference_params=None, + **kwargs, + ) + out_uncond = batch_to_chunk(out_uncond, denoising_range_num) + + return out_cond_pre_and_text, out_cond_pre, out_uncond, denoise_width + + def get_cfg_scale(self, t, cfg_t_range, prev_chunk_scale_s, text_scale_s): + indices = torch.searchsorted(cfg_t_range - 1e-7, t) - 1 + assert indices.min() >= 0 and indices.max() < len(prev_chunk_scale_s) + return prev_chunk_scale_s[indices], text_scale_s[indices] + + def forward_dispatcher(self, x, timestep, y, mask, kv_range, inference_params, **kwargs): + if self.runtime_config.cfg_number == 3: + (out_cond_pre_and_text, out_cond_pre, out_uncond, denoise_width) = self.forward_3cfg( + x, timestep, y, mask, kv_range, inference_params, **kwargs + ) + + prev_chunk_scale_s = torch.tensor(self.runtime_config.prev_chunk_scales).cuda() + text_scale_s = torch.tensor(self.runtime_config.text_scales).cuda() + cfg_t_range = torch.tensor(self.runtime_config.cfg_t_range).cuda() + applied_cfg_range_num, chunk_width = (kwargs["denoising_range_num"], kwargs["chunk_width"]) + if kwargs["fwd_extra_1st_chunk"]: + applied_cfg_range_num -= 1 + cfg_timestep = timestep[0, -applied_cfg_range_num:] + + assert len(prev_chunk_scale_s) == len(cfg_t_range), "prev_chunks_scale and t_range should have the same length" + assert len(text_scale_s) == len(cfg_t_range), "text_scale and t_range should have the same length" + + cfg_output_list = [] + + for chunk_idx in range(applied_cfg_range_num): + prev_chunk_scale, text_scale = self.get_cfg_scale( + cfg_timestep[chunk_idx], cfg_t_range, prev_chunk_scale_s, text_scale_s + ) + l = chunk_idx * chunk_width + r = (chunk_idx + 1) * chunk_width + cfg_output = ( + (1 - prev_chunk_scale) * out_uncond[:, :, l:r] + + (prev_chunk_scale - text_scale) * out_cond_pre[:, :, -denoise_width:][:, :, l:r] + + text_scale * out_cond_pre_and_text[:, :, -denoise_width:][:, :, l:r] + ) + cfg_output_list.append(cfg_output) + + cfg_output = torch.cat(cfg_output_list, dim=2) + + # Reconstruct input x for the next diffusion step + x = torch.cat([x[0:1, :, :-denoise_width], cfg_output], dim=2) + x = torch.cat([x, x], dim=0) + return x + elif self.runtime_config.cfg_number == 1: + assert x.shape[0] == 2 + x = torch.cat([x[0:1], x[0:1]], dim=0) + + kwargs["caption_dropout_mask"] = torch.tensor([False], dtype=torch.bool, device=x.device) + inference_params.update_kv_cache = True + if kwargs.get("distill_nearly_clean_chunk", False): + prev_chunks_scale = float(os.getenv("prev_chunks_scale", 0.7)) + slice_start = 1 if kwargs["fwd_extra_1st_chunk"] else 0 + cond_pre_and_text_channel = x.shape[2] + new_x_chunk = x[0:1, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"]] + new_kvrange = self.generate_kv_range_for_uncondition(new_x_chunk) + kwargs["denoising_range_num"] += 1 + cat_x_chunk = torch.cat([x[0:1], new_x_chunk], dim=2) + new_kvrange = new_kvrange + kv_range.max() + cat_kvrange = torch.cat([kv_range, new_kvrange], dim=0) + cat_t = torch.cat([timestep[0:1], timestep[0:1, slice_start : slice_start + 1]], dim=1) + cat_y = torch.cat([y[0 : y.shape[0] // 2], y[slice_start : slice_start + 1]], dim=0) + cat_xattn_mask = torch.cat([mask[0 : y.shape[0] // 2], mask[slice_start : slice_start + 1]], dim=0) + + cat_out = self.forward( + cat_x_chunk, + cat_t, + cat_y, + xattn_mask=cat_xattn_mask, + kv_range=cat_kvrange, + inference_params=inference_params, + **kwargs, + ) + # flowcache processes one chunk at a time and returns all chunks in a dictionary after processing is complete + if type(cat_out) == dict: + # No artifact chunk in 3 cases: + # 1. Discard artifact chunk is set + # 2. No recomputed output part + # 3. Although there is artifact chunk, the corresponding nearly clean chunk can be reused directly, so no need to compute artifact chunk separately + if self.discard_nearly_clean_chunk or (not cat_out.keys()) or max(cat_out) != self.near_clean_chunk_idx: + out_cond_pre_and_text = cat_out + else: + near_clean_out_cond_text = cat_out[max(cat_out)] + near_clean_out_cond_pre_and_text = cat_out[min(cat_out)] + cat_out[min(cat_out)] = ( + near_clean_out_cond_pre_and_text * prev_chunks_scale + near_clean_out_cond_text * (1 - prev_chunks_scale) + ) + # Remove the output corresponding to nearly clean chunk + cat_out.pop(max(cat_out)) + out_cond_pre_and_text = cat_out + elif type(cat_out) == torch.Tensor: + # Adapt to teacache + if hasattr(self, "discard_nearly_clean_chunk") and self.discard_nearly_clean_chunk: + # No need to do extra forward for nearly clean chunk, so no need to add proportionally + out_cond_pre_and_text = cat_out + # Reset + self.discard_nearly_clean_chunk = False + else: + near_clean_out_cond_pre_and_text = cat_out[ + :, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"] + ] + near_clean_out_cond_text = cat_out[:, :, cond_pre_and_text_channel:] + + near_out_cond_pre_and_text = ( + near_clean_out_cond_pre_and_text * prev_chunks_scale + near_clean_out_cond_text * (1 - prev_chunks_scale) + ) + + cat_out[ + :, :, slice_start * kwargs["chunk_width"] : (slice_start + 1) * kwargs["chunk_width"] + ] = near_out_cond_pre_and_text + out_cond_pre_and_text = cat_out[:, :, :cond_pre_and_text_channel] + else: + raise RuntimeError + else: + out_cond_pre_and_text = self.forward( + x[0:1], + timestep[0:1], + y[0 : y.shape[0] // 2], + xattn_mask=mask[0 : y.shape[0] // 2], + kv_range=kv_range, + inference_params=inference_params, + **kwargs, + ) + + if type(out_cond_pre_and_text) == dict: + return_velocity = {} + for key, value in out_cond_pre_and_text.items(): + return_velocity[key] = torch.cat([value[0:1], value[0:1]], dim=0) + return return_velocity + else: + # Adapt to teacache + # "denoising_range_num" will be modified inside forward, note that kwargs here is still before modification + if hasattr(self, "denoising_range_num"): + kwargs["denoising_range_num"] = self.denoising_range_num + del self.denoising_range_num + + denoise_width = kwargs["chunk_width"] * kwargs["denoising_range_num"] + if kwargs["fwd_extra_1st_chunk"]: + denoise_width -= kwargs["chunk_width"] + + if hasattr(self, "single_chunk_inference") and self.single_chunk_inference: + x = torch.cat([out_cond_pre_and_text, out_cond_pre_and_text], dim=0) + return x + else: + x = torch.cat([x[0:1, :, :-denoise_width], out_cond_pre_and_text[:, :, -denoise_width:]], dim=2) + x = torch.cat([x[0:1], x[0:1]], dim=0) + return x + else: + raise NotImplementedError + + +def _build_dit_model(config: MagiConfig): + """Builds the model""" + device = "cuda" if env_is_true("SKIP_LOAD_MODEL") else "meta" + with torch.device(device): + model = VideoDiTModel( + config=config, pre_process=mpu.is_pipeline_first_stage(), post_process=mpu.is_pipeline_last_stage() + ) + # print_rank_0(model) + + # Print number of parameters. + param_count = sum([p.nelement() for p in model.parameters()]) + model_size_gb = sum([p.nelement() * p.element_size() for p in model.parameters()]) / (1024**3) + print_per_rank( + f"(cp, pp) rank ({mpu.get_cp_rank()}, {mpu.get_pp_rank()}): param count {param_count}, model size {model_size_gb:.2f} GB".format( + mpu.get_cp_rank(), mpu.get_pp_rank(), param_count, model_size_gb + ) + ) + + return model + + +def _high_precision_promoter(module: VideoDiTModel): + module.x_embedder.float() + module.y_embedder.float() + module.t_embedder.float() + module.final_linear.float() + module.rope.float() + for name, sub_module in module.named_modules(): + # skip qk_layernorm_xattn + if "_xattn" in name: + continue + # high precision qk_layernorm by default + if "q_layernorm" in name or "k_layernorm" in name: + sub_module.float() + if "self_attn_post_norm" in name or "mlp_post_norm" in name: + sub_module.float() + if "final_layernorm" in name: + sub_module.float() + return module + + +def get_dit(config: MagiConfig): + """Build and load VideoDiT model""" + model = _build_dit_model(config) + print_rank_0("Build DiTModel successfully") + + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After build_dit_model, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + # To avoid Error in debug mode, set default iteration to 0 + if not env_is_true("SKIP_LOAD_MODEL"): + model = load_checkpoint(model) + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After load_checkpoint, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + model = _high_precision_promoter(model) + mem_allocated_gb = torch.cuda.memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.memory_reserved() / 1024**3 + print_rank_0( + f"After high_precision_promoter, memory allocated: {mem_allocated_gb:.2f} GB, memory reserved: {mem_reserved_gb:.2f} GB" + ) + + model.eval() + gc.collect() + torch.cuda.empty_cache() + + print_rank_0("Load checkpoint successfully") + return model diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_module.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_module.py new file mode 100644 index 0000000000000000000000000000000000000000..4d185fe1d9c2fb67b6eb07edb871d2553915dc14 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/dit/dit_module.py @@ -0,0 +1,1628 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import numbers +from functools import partial +from typing import Callable, List, Optional, Tuple, Dict, Set +import flashinfer +import torch +import torch.distributed +import torch.nn as nn +import torch.nn.functional as F +import triton +import triton.language as tl +from einops import rearrange +from flash_attn import flash_attn_varlen_func +from flash_attn.flash_attn_interface import flash_attn_func +from flash_attn.layers.rotary import apply_rotary_emb as flash_apply_rotary_emb +from flashinfer.gemm import bmm_fp8 + +try: + from magi_attention.functional import flex_flash_attn_func + + flex_attention = flex_flash_attn_func +except: + flex_attention = None + +from torch import Tensor +from torch.nn import Parameter + +from inference.common import EngineConfig, InferenceParams, ModelConfig, ModelMetaArgs, PackedCrossAttnParams, divide +from inference.infra.distributed import parallel_state +from inference.infra.parallelism import CSOHelper, UlyssesScheduler, cso_communication + +########################################################## +# TimestepEmbedder +########################################################## +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + """ + + def __init__(self, model_config: ModelConfig, frequency_embedding_size=256): + super().__init__() + + self.data_type = model_config.params_dtype + hidden_size = model_config.hidden_size + + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, int(hidden_size * model_config.cond_hidden_ratio), bias=True), + nn.SiLU(), + nn.Linear( + int(hidden_size * model_config.cond_hidden_ratio), int(hidden_size * model_config.cond_hidden_ratio), bias=True + ), + ) + self.frequency_embedding_size = frequency_embedding_size + + # rescale the timestep for the general transport model + self.timestep_rescale_factor = 1000 + + @staticmethod + def timestep_embedding(t, dim, max_period=10000, timestep_rescale_factor=1): + """ + Create sinusoidal timestep embeddings. + :param t: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( + device=t.device + ) + args = t[:, None].float() * freqs[None] * timestep_rescale_factor + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + def forward(self, t): + t = t.to(torch.float32) + t_freq = self.timestep_embedding( + t, self.frequency_embedding_size, timestep_rescale_factor=self.timestep_rescale_factor + ) + t_emb = self.mlp(t_freq.to(self.data_type)) + return t_emb + + +########################################################## +# CaptionEmbedder +########################################################## +class CaptionEmbedder(nn.Module): + """ + Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. + """ + + def __init__(self, model_config: ModelConfig): + super().__init__() + + in_channels = model_config.caption_channels + hidden_size = model_config.hidden_size + caption_max_length = model_config.caption_max_length + + self.y_proj_xattn = nn.Sequential( + nn.Linear(in_channels, int(hidden_size * model_config.xattn_cond_hidden_ratio), bias=True), nn.SiLU() + ) + + self.y_proj_adaln = nn.Sequential(nn.Linear(in_channels, int(hidden_size * model_config.cond_hidden_ratio), bias=True)) + + self.null_caption_embedding = Parameter(torch.empty(caption_max_length, in_channels)) + + def caption_drop(self, caption, caption_dropout_mask): + """ + Drops labels to enable classifier-free guidance. + caption.shape = (N, 1, cap_len, C) + """ + dropped_caption = torch.where( + caption_dropout_mask[:, None, None, None], # (N, 1, 1, 1) + self.null_caption_embedding[None, None, :], # (1, 1, cap_len, C) + caption, # (N, 1, cap_len, C) + ) + return dropped_caption + + def caption_drop_single_token(self, caption_dropout_mask): + dropped_caption = torch.where( + caption_dropout_mask[:, None, None], # (N, 1, 1) + self.null_caption_embedding[None, -1, :], # (1, 1, C) + self.null_caption_embedding[None, -2, :], # (1, 1, C) + ) + return dropped_caption # (N, 1, C) + + def forward(self, caption, train, caption_dropout_mask=None): + if train and caption_dropout_mask is not None: + caption = self.caption_drop(caption, caption_dropout_mask) + caption_xattn = self.y_proj_xattn(caption) + if caption_dropout_mask is not None: + caption = self.caption_drop_single_token(caption_dropout_mask) + + caption_adaln = self.y_proj_adaln(caption) + return caption_xattn, caption_adaln + + +########################################################## +# FinalLinear +########################################################## +class FinalLinear(nn.Module): + """ + The final linear layer of DiT. + """ + + def __init__(self, hidden_size, patch_size, t_patch_size, out_channels): + super().__init__() + self.linear = nn.Linear(hidden_size, patch_size * patch_size * t_patch_size * out_channels, bias=False) + + def forward(self, x): + x = self.linear(x) + return x + + +########################################################## +# AdaModulateLayer +########################################################## +class AdaModulateLayer(torch.nn.Module): + def __init__(self, model_config: ModelConfig): + super().__init__() + self.model_config = model_config + + self.gate_num_chunks = 2 + self.act = nn.SiLU() + self.proj = nn.Sequential( + nn.Linear( + int(self.model_config.hidden_size * self.model_config.cond_hidden_ratio), + int(self.model_config.hidden_size * self.model_config.cond_gating_ratio * self.gate_num_chunks), + bias=True, + dtype=self.model_config.params_dtype, + ) + ) + + def forward(self, c): + c = self.act(c) + return self.proj(c) + + +########################################################## +# bias_modulate_add +########################################################## +@triton.jit +def range_mod_kernel_fwd( + X, # pointer to the input + MAP, # map x index to gating index + GATINGS, # pointer to the gatings + Y, # pointer to the output + M, # number of rows in X, unused + N, # number of columns in X + stride_xm, # how much to increase the pointer when moving by 1 row in X + stride_xn, # how much to increase the pointer when moving by 1 column in X + stride_gm, # how much to increase the pointer when moving by 1 row in GATINGS + stride_gn, # how much to increase the pointer when moving by 1 column in GATINGS + stride_ym, # how much to increase the pointer when moving by 1 row in Y + stride_yn, # how much to increase the pointer when moving by 1 column in Y + BLOCK_SIZE: tl.constexpr, # number of columns in a block +): + # Map the program id to the row of X and Y it should compute. + row = tl.program_id(0) + + cur_X = X + row * stride_xm + x_cols = tl.arange(0, BLOCK_SIZE) * stride_xn + x_mask = x_cols < N * stride_xn + x = tl.load(cur_X + x_cols, mask=x_mask, other=0.0) + + cur_MAP = MAP + row + gating_index = tl.load(cur_MAP) + cur_GATING = GATINGS + gating_index * stride_gm + gating_cols = tl.arange(0, BLOCK_SIZE) * stride_gn + gating_mask = gating_cols < N * stride_gn + gating = tl.load(cur_GATING + gating_cols, mask=gating_mask, other=0.0) + + cur_Y = Y + row * stride_ym + y_cols = tl.arange(0, BLOCK_SIZE) * stride_yn + y_mask = y_cols < N * stride_yn + tl.store(cur_Y + y_cols, x * gating, mask=y_mask) + + +def range_mod_triton(x, c_mapping, gatings): + """ + Inputs: + x: (s, b, h). Tensor of inputs embedding (images or latent representations of images) + c_mapping: (s, b). Tensor of condition map + gatings: (b, denoising_range_num, h). Tensor of condition embedding + """ + + assert x.is_cuda, "x is not on cuda" + assert c_mapping.is_cuda, "c_mapping is not on cuda" + assert gatings.is_cuda, "gatings is not on cuda" + + # TODO: use 3D tensor for x, c_mapping, and gatings + s, b, h = x.shape + x = x.transpose(0, 1).flatten(0, 1) + c_mapping = c_mapping.transpose(0, 1).flatten(0, 1) + gatings = gatings.flatten(0, 1) + + assert x.dim() == 2, f"x must be a 2D tensor but got {x.dim()}D" + assert c_mapping.dim() == 1, f"c_mapping must be a 1D tensor but got {c_mapping.dim()}D" + assert gatings.dim() == 2, f"gatings must be a 2D tensor but got {gatings.dim()}D" + + M, N = x.shape + if c_mapping.size(0) != M: + import pdb; pdb.set_trace() # noqa: T201 + assert c_mapping.size(0) == M, "c_mapping must have the same number of rows as x" + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_SIZE: + raise RuntimeError("range_mod_triton doesn't support feature dim >= 64KB.") + + MAP = c_mapping + y = torch.empty_like(x) + + range_mod_kernel_fwd[(M,)]( + x, + MAP, + gatings, + y, + M, + N, + x.stride(0), + x.stride(1), + gatings.stride(0), + gatings.stride(1), + y.stride(0), + y.stride(1), + BLOCK_SIZE=BLOCK_SIZE, + ) + y = y.reshape(b, s, h).transpose(0, 1) + + return y + + +def bias_modulate_add( + x: torch.Tensor, residual: torch.Tensor, condition_map: torch.Tensor, gate: torch.Tensor, post_norm: torch.nn.Module +): + assert gate.shape[-1] == x.shape[-1] + + original_dtype = x.dtype + x = x.float() + residual = residual.float() + gate = gate.float() + + try: + x = range_mod_triton(x, condition_map, gate) + except RuntimeError as e: + print(f"RuntimeError in range_mod_triton: {e}") + import pdb;pdb.set_trace() + + x = post_norm(x) + x = x + residual + x = x.to(original_dtype) + + return x + + +########################################################## +# FusedLayerNorm +########################################################## +def make_viewless_tensor(inp, requires_grad): + # return tensor as-is, if not a 'view' + if inp._base is None: + return inp + + out = torch.empty((1,), dtype=inp.dtype, device=inp.device, requires_grad=requires_grad) + out.data = inp.data + return out + + +class FusedLayerNorm(torch.nn.Module): + + """ + Layer Norm, fused into a single CUDA kernel. + Borrow from: https://github.com/NVIDIA/Megatron-LM/blob/6501752396e9cc360ce894cda4b2217a58c1c09d/megatron/core/fusions/fused_layer_norm.py#L30 + + Args: + hidden_size (int): Transformer hidden dimension. + + eps (float): Epsilon added to denominator, for numerical stability. + + zero_centered_gamma (bool): Adjust LayerNorm weights such that they are + centered around zero. This improves numerical stability. + + model_config (ModelConfig): Transformer config. Include to match custom + layer norm interfaces. + + normalization (str): Normalization type, used for Transformer Engine. + Must equal 'LayerNorm' here. + """ + + def __init__(self, model_config: ModelConfig, hidden_size: int): + super().__init__() + + self.zero_centered_gamma = model_config.apply_layernorm_1p + if isinstance(hidden_size, numbers.Integral): + hidden_size = (hidden_size,) + self.hidden_size = torch.Size(hidden_size) + self.eps = model_config.layernorm_epsilon + self.weight = Parameter(torch.empty(*hidden_size, dtype=model_config.params_dtype)) + self.bias = Parameter(torch.empty(*hidden_size, dtype=model_config.params_dtype)) + + def forward(self, input: Tensor) -> Tensor: + weight = self.weight + 1 if self.zero_centered_gamma else self.weight + return torch.nn.functional.layer_norm(input, self.hidden_size, weight, self.bias, self.eps) + + +def softcap(x: torch.Tensor, cap: int): + return (cap * torch.tanh(x.float() / cap)).to(x.dtype) + + +def div_clamp_to(x: torch.Tensor, scale: torch.Tensor): + fp8_min = torch.finfo(torch.float8_e4m3fn).min + fp8_max = torch.finfo(torch.float8_e4m3fn).max + prefix_shape = x.shape[:-1] + last_shape = x.shape[-1] + x = x.flatten().reshape(-1, last_shape) + # Split x into 256 MB parts to avoid big memory peak + part_size = 256 * 1024 * 1024 // last_shape + part_num = (x.shape[0] + part_size - 1) // part_size + return ( + torch.cat( + [ + torch.clamp(x[i * part_size : (i + 1) * part_size].float() / scale.float(), fp8_min, fp8_max).bfloat16() + for i in range(part_num) + ], + dim=0, + ) + .to(torch.float8_e4m3fn) + .reshape(*prefix_shape, last_shape) + .contiguous() + ) + + +########################################################## +# CustomLayerNormLinear +########################################################## +class CustomLayerNormLinear(torch.nn.Module): + def __init__( + self, + input_size: int, + output_size_q: int, + output_size_kv: int, + layer_number: int, + model_config: ModelConfig, + engine_config: EngineConfig, + ): + super().__init__() + self.layer_norm = torch.nn.LayerNorm(input_size, eps=model_config.layernorm_epsilon, dtype=model_config.params_dtype) + + self.layer_number = layer_number + layers = {"q": output_size_q, "qx": output_size_q, "k": output_size_kv, "v": output_size_kv} + + for name, output_size in layers.items(): + if not engine_config.fp8_quant or self.layer_number == 0 or self.layer_number == model_config.num_layers - 1: + setattr(self, name, torch.nn.Linear(input_size, output_size, bias=False, dtype=model_config.params_dtype)) + else: + setattr(self, name, PerTensorQuantizedFp8Linear(input_size, output_size)) + + def forward_ln(self, hidden_states): + return self.layer_norm(hidden_states) + + def forward_q(self, hidden_states): + return self.q(hidden_states) + + def forward_qx(self, hidden_states): + return self.qx(hidden_states) + + def forward_k(self, hidden_states): + return self.k(hidden_states) + + def forward_v(self, hidden_states): + return self.v(hidden_states) + + +########################################################## +# PerTensorQuantizedFp8Linear +########################################################## +class PerTensorQuantizedFp8Linear(torch.nn.Module): + # The bias and device parameter is not used; it is included for compatibility with Linear's parameters. + def __init__(self, in_features: int, out_features: int, bias=False, dtype=torch.bfloat16, device=None) -> None: + super().__init__() + + self.in_features = in_features + self.out_features = out_features + self.finfo = torch.finfo(torch.float8_e4m3fn) + self.output_dtype = dtype + + self.weight = Parameter(torch.empty((1, out_features, in_features), dtype=torch.float8_e4m3fn)) + self.weight_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.input_scale = Parameter(torch.empty(in_features, dtype=torch.float32)) + + def forward(self, input: torch.Tensor): + input = div_clamp_to(input, self.input_scale) + + prefix_shape = input.shape[:-1] + # column major weight + return bmm_fp8( + input.reshape(1, -1, self.in_features), + self.weight.transpose(-2, -1), + self.input_scale, + self.weight_scale, + dtype=self.output_dtype, + ).reshape(prefix_shape + (self.out_features,)) + + +########################################################## +# PerChannelQuantizedFp8Linear +########################################################## +class PerChannelQuantizedFp8Linear(torch.nn.Module): + # The bias and device parameter is not used; it is included for compatibility with Linear's parameters. + def __init__(self, in_features: int, out_features: int, bias=False, dtype=torch.bfloat16, device=None) -> None: + super().__init__() + + self.in_features = in_features + self.out_features = out_features + self.output_dtype = dtype + self.finfo = torch.finfo(torch.float8_e4m3fn) + + self.weight = Parameter(torch.empty((1, out_features, in_features), dtype=torch.float8_e4m3fn)) + self.weight_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.input_scale = Parameter(torch.empty(1, dtype=torch.float32)) + self.smooth_scale = Parameter(torch.empty(1, in_features, dtype=torch.float32)) + + def forward(self, x): + x = div_clamp_to(x, self.smooth_scale.to(torch.float32)) + + prefix_shape = x.shape[:-1] + return bmm_fp8( + x.reshape(1, -1, self.in_features), + self.weight.transpose(-2, -1), + self.input_scale, + self.weight_scale, + dtype=self.output_dtype, + ).reshape(prefix_shape + (self.out_features,)) + + +########################################################## +# CustomMLP +########################################################## +class CustomMLP(torch.nn.Module): + """ + CustomMLP will take the input with h hidden state, project it to 4*h + hidden dimension, perform nonlinear transformation, and project the + state back into h hidden dimension. + + + Returns an output and a bias to be added to the output. + + We use the following notation: + h: hidden size + p: number of tensor model parallel partitions + b: batch size + s: sequence length + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int, input_size: int = None): + super().__init__() + + self.model_config: ModelConfig = model_config + self.engine_config: EngineConfig = engine_config + self.layer_number = layer_number + + self.input_size = input_size if input_size != None else self.model_config.hidden_size + self.layer_norm = torch.nn.LayerNorm( + self.input_size, eps=self.model_config.layernorm_epsilon, dtype=self.model_config.params_dtype + ) + + submodules_linear_fc1 = torch.nn.Linear + if self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1: + submodules_linear_fc1 = PerTensorQuantizedFp8Linear + + if self.model_config.gated_linear_unit: + self.linear_fc1 = submodules_linear_fc1( + self.input_size, 2 * self.model_config.ffn_hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + else: + self.linear_fc1 = submodules_linear_fc1( + self.input_size, self.model_config.ffn_hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + + submodules_linear_fc2 = torch.nn.Linear + if engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1: + submodules_linear_fc2 = PerChannelQuantizedFp8Linear + + self.linear_fc2 = submodules_linear_fc2( + self.model_config.ffn_hidden_size, self.model_config.hidden_size, bias=False, dtype=self.model_config.params_dtype + ) + + def forward(self, hidden_states): + hidden_states = self.layer_norm(hidden_states) + hidden_states = self.linear_fc1(hidden_states) + if self.model_config.gated_linear_unit: + hidden_states = flashinfer.activation.silu_and_mul(hidden_states) + else: + hidden_states = torch.nn.functional.gelu(hidden_states) + hidden_states = self.linear_fc2(hidden_states) + + return hidden_states + + +########################################################## +# LearnableRotaryEmbeddingCat +########################################################## +def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: + """generate N-D grid in dimension order. + + The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. + + That is, the statement + [X1,X2,X3] = ndgrid(x1,x2,x3) + + produces the same result as + + [X2,X1,X3] = meshgrid(x2,x1,x3) + + This naming is based on MATLAB, the purpose is to avoid confusion due to torch's change to make + torch.meshgrid behaviour move from matching ndgrid ('ij') indexing to numpy meshgrid defaults of ('xy'). + + """ + try: + return torch.meshgrid(*tensors, indexing="ij") + except TypeError: + # old PyTorch < 1.10 will follow this path as it does not have indexing arg, + # the old behaviour of meshgrid was 'ij' + return torch.meshgrid(*tensors) + + +def pixel_freq_bands( + num_bands: int, max_freq: float = 224.0, linear_bands: bool = True, device: Optional[torch.device] = None +): + if linear_bands: + bands = torch.linspace(1.0, max_freq / 2, num_bands, dtype=torch.float32, device=device) + else: + bands = 2 ** torch.linspace(0, math.log(max_freq, 2) - 1, num_bands, dtype=torch.float32, device=device) + return bands * torch.pi + + +def freq_bands( + num_bands: int, temperature: float = 10000.0, step: int = 2, device: Optional[torch.device] = None +) -> torch.Tensor: + exp = torch.arange(0, num_bands, step, dtype=torch.int64, device=device).to(torch.float32) / num_bands + bands = 1.0 / (temperature**exp) + return bands + + +def build_fourier_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + num_bands: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + include_grid: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, +) -> List[torch.Tensor]: + """ + + Args: + feat_shape: Feature shape for embedding. + bands: Pre-calculated frequency bands. + num_bands: Number of frequency bands (determines output dim). + max_res: Maximum resolution for pixel based freq. + temperature: Temperature for non-pixel freq. + linear_bands: Linear band spacing for pixel based freq. + include_grid: Include the spatial grid in output. + in_pixels: Output in pixel freq. + ref_feat_shape: Reference feature shape for resize / fine-tune. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + if bands is None: + if in_pixels: + bands = pixel_freq_bands(num_bands, float(max_res), linear_bands=linear_bands, device=device) + else: + bands = freq_bands(num_bands, temperature=temperature, step=1, device=device) + else: + if device is None: + device = bands.device + if dtype is None: + dtype = bands.dtype + + if in_pixels: + t = [torch.linspace(-1.0, 1.0, steps=s, device=device, dtype=torch.float32) for s in feat_shape] + else: + t = [torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) for s in feat_shape] + # align spatial center (H/2,W/2) to (0,0) + t[1] = t[1] - (feat_shape[1] - 1) / 2 + t[2] = t[2] - (feat_shape[2] - 1) / 2 + if ref_feat_shape is not None: + # eva's scheme for resizing rope embeddings (ref shape = pretrain) + # aligning to the endpoint e.g [0,1,2] -> [0, 0.4, 0.8, 1.2, 1.6, 2] + t_rescaled = [] + for x, f, r in zip(t, feat_shape, ref_feat_shape): + # deal with image input + if f == 1: + assert r == 1, "ref_feat_shape must be 1 when feat_shape is 1" + t_rescaled.append(x) + else: + t_rescaled.append(x / (f - 1) * (r - 1)) + t = t_rescaled + + grid = torch.stack(ndgrid(t), dim=-1) + grid = grid.unsqueeze(-1) + pos = grid * bands + + pos_sin, pos_cos = pos.sin().to(dtype=dtype), pos.cos().to(dtype) + out = [grid, pos_sin, pos_cos] if include_grid else [pos_sin, pos_cos] + return out + + +def build_rotary_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + dim: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, +): + """ + + Args: + feat_shape: Spatial shape of the target tensor for embedding. + bands: Optional pre-generated frequency bands + dim: Output dimension of embedding tensor. + max_res: Maximum resolution for pixel mode. + temperature: Temperature (inv freq) for non-pixel mode + linear_bands: Linearly (instead of log) spaced bands for pixel mode + in_pixels: Pixel vs language (inv freq) mode. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + sin_emb, cos_emb = build_fourier_pos_embed( + feat_shape, + bands=bands, + num_bands=dim // 8, + max_res=max_res, + temperature=temperature, + linear_bands=linear_bands, + in_pixels=in_pixels, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + ) + num_spatial_dim = 1 + # this would be much nicer as a .numel() call to torch.Size(), but torchscript sucks + for x in feat_shape: + num_spatial_dim *= x + + sin_emb = sin_emb.reshape(num_spatial_dim, -1) + cos_emb = cos_emb.reshape(num_spatial_dim, -1) + return sin_emb, cos_emb + + +class LearnableRotaryEmbeddingCat(nn.Module): + """Rotary position embedding w/ concatenatd sin & cos + + The following impl/resources were referenced for this impl: + * https://github.com/lucidrains/vit-pytorch/blob/6f3a5fcf0bca1c5ec33a35ef48d97213709df4ba/vit_pytorch/rvt.py + * https://blog.eleuther.ai/rotary-embeddings/ + """ + + def __init__( + self, + dim, + max_res=224, + temperature=10000, + in_pixels=True, + linear_bands: bool = False, + feat_shape: Optional[List[int]] = None, + ref_feat_shape: Optional[List[int]] = None, + ): + super().__init__() + self.dim = dim + self.max_res = max_res + self.temperature = temperature + self.in_pixels = in_pixels + self.linear_bands = linear_bands + self.feat_shape = feat_shape + self.ref_feat_shape = ref_feat_shape + self.bands = nn.Parameter(self.get_default_bands()) + + def get_default_bands(self): + if self.in_pixels: + bands = pixel_freq_bands( + self.dim // 8, float(self.max_res), linear_bands=self.linear_bands, devicse=torch.cuda.current_device() + ) + else: + bands = freq_bands(self.dim // 8, temperature=self.temperature, step=1, device=torch.cuda.current_device()) + return bands + + def get_embed(self, shape: Optional[List[int]], ref_feat_shape: Optional[List[int]] = None): + # rebuild bands and embeddings every call, use if target shape changes + embeds = build_rotary_pos_embed( + feat_shape=shape, + bands=self.bands, # use learned bands + dim=self.dim, + max_res=self.max_res, + linear_bands=self.linear_bands, + in_pixels=self.in_pixels, + ref_feat_shape=ref_feat_shape if ref_feat_shape else self.ref_feat_shape, + temperature=self.temperature, + device=torch.cuda.current_device(), + ) + return torch.cat(embeds, -1) + + +########################################################## +# Attention +########################################################## +class Attention(torch.nn.Module): + """ + Attention layer abstract class. + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int): + super().__init__() + + self.model_config: ModelConfig = model_config + self.engine_config: EngineConfig = engine_config + self.layer_number = layer_number + + self.hidden_size_per_attention_head = self.model_config.kv_channels + # num_query_groups and num_attention_heads are different for GQA + self.query_projection_size = self.model_config.kv_channels * self.model_config.num_attention_heads + self.kv_projection_size = self.model_config.kv_channels * self.model_config.num_query_groups + + # Per attention head and per partition values. + world_size = parallel_state.get_tp_world_size(with_context_parallel=True) + if world_size > self.model_config.num_query_groups and world_size % self.model_config.num_query_groups == 0: + self.num_query_groups_per_partition = 1 + else: + self.num_query_groups_per_partition = divide(self.model_config.num_query_groups, world_size) + + def _allocate_key_and_value_memory(self, sequence_length, batch_size, dtype): + """Allocate memory to store kv cache during inference.""" + + if self.engine_config.kv_offload: + return torch.empty( + sequence_length * batch_size, + self.num_query_groups_per_partition, + self.hidden_size_per_attention_head * 2, + dtype=dtype, + device=torch.cpu.current_device(), + pin_memory=True, + ) + else: + return torch.empty( + sequence_length * batch_size, + self.num_query_groups_per_partition, + self.hidden_size_per_attention_head * 2, + dtype=dtype, + device=torch.cuda.current_device(), + ) + + +########################################################## +# FullyParallelAttention +########################################################## +def split_tensor_along_last_dim( + tensor: torch.Tensor, num_partitions: int, contiguous_split_chunks: bool = False +) -> List[torch.Tensor]: + """Split a tensor along its last dimension. + + Args: + tensor: input tensor. + num_partitions: number of partitions to split the tensor + contiguous_split_chunks: If True, make each chunk contiguous + in memory. + + Returns: + A list of Tensors + """ + # Get the size and dimension. + last_dim = tensor.dim() - 1 + last_dim_size = divide(tensor.size()[last_dim], num_partitions) + # Split. + tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) + # Note: torch.split does not create contiguous tensors by default. + if contiguous_split_chunks: + return tuple(chunk.contiguous() for chunk in tensor_list) + + return tensor_list + + +class FullyParallelAttention(Attention): + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int): + super().__init__(model_config=model_config, engine_config=engine_config, layer_number=layer_number) + + # output 2x query, one for self-attn, one for cross-attn with condition + self.linear_qkv = CustomLayerNormLinear( + input_size=self.model_config.hidden_size, + output_size_q=self.query_projection_size, + output_size_kv=self.kv_projection_size, + layer_number=self.layer_number, + model_config=self.model_config, + engine_config=self.engine_config, + ) + + # kv from condition, e.g., caption + self.linear_kv_xattn = torch.nn.Linear( + int(self.model_config.hidden_size * self.model_config.xattn_cond_hidden_ratio), # 6144 + 2 * self.kv_projection_size, # 2048 + dtype=self.model_config.params_dtype, + bias=False, + ) + + # Output. + self.adapt_linear_quant = ( + self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1 + ) + submodules_linear_proj = PerChannelQuantizedFp8Linear if self.adapt_linear_quant else torch.nn.Linear + self.linear_proj = submodules_linear_proj( + 2 * self.query_projection_size, self.model_config.hidden_size, dtype=self.model_config.params_dtype, bias=False + ) + + self.q_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.q_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + self.k_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.k_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + + self.attn_weights_history = [] + + def _full_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + """ + Saves the generated key and value tensors to the end of the buffers in inference_params. + Returns the full size keys and values from the provided inference_params + + Returns a tuple: (key, value) + """ + # ================================================= + # Pre-allocate memory for key-values for inference. + # ================================================= + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + inf_max_seq_length, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + # Get the pre-allocated buffers for this layer + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + sequence_start = meta_args.slice_point * meta_args.clip_token_nums * inf_max_batch_size + # Only take clean kv cache here, but for partial reuse, the kv of the currently denoising chunk is not passed to forward, so this part of kv is also needed + get_key_and_value = inference_key_and_value_memory[:sequence_start, ...].cuda() + + # Copy key and values. + if inference_params.update_kv_cache: + key_and_value_total = key_and_value + + clip_size = ( + key_and_value_total.size(0) - meta_args.clip_token_nums * inf_max_batch_size + if meta_args.distill_nearly_clean_chunk + else key_and_value_total.size(0) + ) + sequence_end = sequence_start + clip_size + assert sequence_end <= inference_key_and_value_memory.size(0) + # update kv cache + inference_key_and_value_memory[sequence_start:sequence_end, ...] = key_and_value_total[:clip_size] + + return torch.cat([get_key_and_value, key_and_value], dim=0) + + def _custom_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + """ + Saves the generated key and value tensors to the end of the buffers in inference_params. + Returns the full size keys and values from the provided inference_params + + Returns a tuple: (key, value) + """ + # ================================================= + # Pre-allocate memory for key-values for inference. + # ================================================= + + # 1. The principle is to update the kv cache for whichever chunk is passed in + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + inf_max_seq_length, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + # Get the pre-allocated buffers for this layer + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + chunk_start = meta_args.start_chunk_id + chunk_end = meta_args.end_chunk_id + if meta_args.distill_nearly_clean_chunk: + chunk_end -= 1 + + sequence_start = chunk_start * meta_args.clip_token_nums * inf_max_batch_size + sequence_end = chunk_end * meta_args.clip_token_nums * inf_max_batch_size + # 1. Update values in inference_key_and_value_memory + clip_size = ( + key_and_value.size(0) - meta_args.clip_token_nums * inf_max_batch_size + if meta_args.distill_nearly_clean_chunk + else key_and_value.size(0) + ) + try: + inference_key_and_value_memory[sequence_start:sequence_end, ...] = key_and_value[:clip_size] + except Exception as e: + print(f"Error updating inference key and value memory: {e}") + import pdb; pdb.set_trace() + + # 2. Concatenate kv values from previous chunks + key_and_value_total = key_and_value + past_chunk_kv = inference_key_and_value_memory[:sequence_start, ...].cuda() + key_and_value_total = torch.cat([past_chunk_kv, key_and_value], dim=0) + + return key_and_value_total + + def _compresskv_adjust_key_and_value( + self, inference_params: InferenceParams, key_and_value: torch.Tensor, meta_args: ModelMetaArgs + ): + inf_max_seq_length = inference_params.max_sequence_length + inf_max_batch_size = inference_params.max_batch_size + + if self.layer_number not in inference_params.key_value_memory_dict: + inference_key_and_value_memory = self._allocate_key_and_value_memory( + meta_args.total_cache_len, inf_max_batch_size, key_and_value.dtype + ) + inference_params.key_value_memory_dict[self.layer_number] = inference_key_and_value_memory + else: + inference_key_and_value_memory = inference_params.key_value_memory_dict[self.layer_number] + + tracker = inference_params.kv_chunk_tracker + + # Calculate the chunk range being processed + chunk_start = meta_args.start_chunk_id + chunk_end = meta_args.end_chunk_id + if meta_args.distill_nearly_clean_chunk: + chunk_end -= 1 + + current_chunk_ids = list(range(chunk_start, chunk_end)) # e.g., [3, 4, 5] + + if len(current_chunk_ids) > 0: + # Allocate kv cache ranges, skip if already allocated + tracker.register_chunks(current_chunk_ids) + + tokens_per_chunk = meta_args.clip_token_nums + + if meta_args.sparse_active_indices is not None and meta_args.sparse_total_tokens > 0: + active_idx = meta_args.sparse_active_indices + num_active = int(active_idx.numel()) + assert key_and_value.size(0) == num_active, ( + f"Sparse KV size mismatch: got {key_and_value.size(0)}, expected {num_active}" + ) + for cid in current_chunk_ids: + s, e = tracker.get_range(cid) + chunk_len = e - s + assert chunk_len == meta_args.sparse_total_tokens == tokens_per_chunk + chunk_buffer = inference_key_and_value_memory[s:e, ...].clone() + if chunk_buffer.dtype != key_and_value.dtype: + chunk_buffer = chunk_buffer.to(key_and_value.dtype) + chunk_buffer[active_idx.to(chunk_buffer.device)] = key_and_value + inference_key_and_value_memory[s:e, ...] = chunk_buffer + key_and_value = inference_key_and_value_memory[ + tracker.get_range(current_chunk_ids[0])[0] : + tracker.get_range(current_chunk_ids[-1])[1] + , ...].cuda() + else: + # === Split key_and_value by chunk === + # Split tensor: one segment per chunk + chunk_tensors = [] + start_idx = 0 + for i, cid in enumerate(current_chunk_ids): + chunk_len = tokens_per_chunk + end_idx = start_idx + chunk_len + chunk_tensors.append(key_and_value[start_idx:end_idx, ...]) + start_idx = end_idx + + # === Write each chunk to its allocated position === + for cid, chunk_kv in zip(current_chunk_ids, chunk_tensors): + s, e = tracker.get_range(cid) + target_length = e - s + assert chunk_kv.size(0) == target_length, f"Chunk size mismatch: chunk {cid}, expected {target_length}, got {chunk_kv.size(0)}" + + inference_key_and_value_memory[s : s + chunk_kv.size(0), ...] = chunk_kv + + + # === Concatenate past KV === + past_ranges = tracker.get_all_ranges_previous(current_chunk_ids) + past_chunks = [] + for s, e in past_ranges: + past_chunks.append(inference_key_and_value_memory[s:e, ...].cuda()) + + if past_chunks: + past_kv = torch.cat(past_chunks, dim=0) + key_and_value_total = torch.cat([past_kv, key_and_value], dim=0) + else: + key_and_value_total = key_and_value.cuda() + + return key_and_value_total + + def adjust_key_and_value_for_inference( + self, key_and_value: torch.Tensor, inference_params: InferenceParams, meta_args: ModelMetaArgs + ): + if inference_params is None: + return torch.chunk(key_and_value, 2, dim=-1) + + # Only update kvcache when necessary, include 3 conditions: + # 1. extract prefix video clean feature + # 2. the first chunk of current kv is clean, we need to save their feature + # 3. previous chunk is clean and we need to save/load their feature + + # Priority: compress_kv > save_kvcache_every_forward > full_adjust + if meta_args.compress_kv: + key_and_value = self._compresskv_adjust_key_and_value(inference_params, key_and_value, meta_args) + elif meta_args.save_kvcache_every_forward: + key_and_value = self._custom_adjust_key_and_value(inference_params, key_and_value, meta_args) + elif (meta_args.extract_prefix_video_feature or meta_args.fwd_extra_1st_chunk or meta_args.slice_point > 0) and \ + not meta_args.save_kvcache_every_forward: + key_and_value = self._full_adjust_key_and_value(inference_params, key_and_value, meta_args) + key, value = torch.chunk(key_and_value, 2, dim=-1) + return key.contiguous(), value.contiguous() + + # ===================== + # Get Query for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_q(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + query = self.linear_qkv.forward_q(mixed_qqkv) + query = query.reshape(query.size(0), query.size(1), -1, self.hidden_size_per_attention_head) + assert self.q_layernorm is not None + original_dtype = query.dtype + query = query.float() + query = self.q_layernorm(query) + query = query.transpose(0, 1).contiguous() + query = flash_apply_rotary_emb(query, cos_emb, sin_emb) + query = query.to(original_dtype) + return rearrange(query, "b sq hn hd -> (sq b) hn hd").contiguous() + + # ===================== + # Get Key for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_k(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + key = self.linear_qkv.forward_k(mixed_qqkv) + key = key.reshape(key.size(0), key.size(1), -1, self.hidden_size_per_attention_head) + assert self.k_layernorm is not None + original_dtype = key.dtype + key = key.float() + key = self.k_layernorm(key) + key = key.transpose(0, 1).contiguous() + key = flash_apply_rotary_emb(key, cos_emb, sin_emb) + key = key.to(original_dtype) + return rearrange(key, "b sq hn hd -> (sq b) hn hd").contiguous() + + # ===================== + # Get Value for core attn + # [sq, b, (hn hd)] -> [(sq b), hn, hd] + # ===================== + + def get_v(self, mixed_qqkv: torch.Tensor): + value = self.linear_qkv.forward_v(mixed_qqkv) + return rearrange(value, "sq b (hn hd) -> (sq b) hn hd", hd=self.hidden_size_per_attention_head).contiguous() + + def get_kv(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + # Get KV together for better performance when encoutering cpu-bound, mainly used by cuda graph + key = self.get_k(mixed_qqkv, cos_emb, sin_emb) + value = self.get_v(mixed_qqkv) + # [(sq b), hn, hd] -> [(sq b), hn, 2 * hd] + return torch.cat([key, value], dim=-1) + + def get_qkv(self, mixed_qqkv: torch.Tensor, cos_emb: torch.Tensor, sin_emb: torch.Tensor): + # Get QKV together for better performance when encoutering cpu-bound, mainly used by cuda graph + q = self.get_q(mixed_qqkv, cos_emb, sin_emb) + k = self.get_k(mixed_qqkv, cos_emb, sin_emb) + v = self.get_v(mixed_qqkv) + return q, k, v + + def get_xqkv(self, mixed_qqkv: torch.Tensor, key_value_states: torch.Tensor): + query_xattn = self.linear_qkv.forward_qx(mixed_qqkv) + query_xattn = rearrange(query_xattn, "sq b (hn hd) -> (b sq) hn hd", hd=self.hidden_size_per_attention_head) + query_xattn = self.q_layernorm_xattn(query_xattn) + + # [y_total_token, h] --> [y_total_token, 2*hp] + mixed_kv_xattn = torch.concat( + [torch.matmul(key_value_states, w.t()) for w in torch.chunk(self.linear_kv_xattn.weight, 8, axis=0)], axis=1 + ) + # [y_total_token, 2*hn*hd] --> [y_total_token, hn, 2*hd] + mixed_kv_xattn = mixed_kv_xattn.view(key_value_states.shape[0], -1, 2 * self.hidden_size_per_attention_head) + + # [y_total_token, hn, 2*hd] --> 2 [y_total_token, hn, hd] + (key_xattn, value_xattn) = split_tensor_along_last_dim(mixed_kv_xattn, 2) + + key_xattn = self.k_layernorm_xattn(key_xattn) + return query_xattn, key_xattn, value_xattn + + + def core_attention(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, bs: int, meta_args: ModelMetaArgs): + + # (sq b) hn hd -> b sq hn hd + query = query.reshape(-1, bs, query.shape[1], query.shape[2]).transpose(0, 1).contiguous() + # (sq b) hn hd -> b sq hn hd + key = key.reshape(-1, bs, key.shape[1], key.shape[2]).transpose(0, 1).contiguous() + # (sq b) hn hd -> b sq hn hd + value = value.reshape(-1, bs, value.shape[1], value.shape[2]).transpose(0, 1).contiguous() + + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + core_attn_out, _ = flex_attention( + query.flatten(0, 1), + key.flatten(0, 1), + value.flatten(0, 1), + meta_args.core_attn_params.q_range, + meta_args.core_attn_params.k_range, + max_seqlen_q=meta_args.core_attn_params.max_seqlen_q, + max_seqlen_k=meta_args.core_attn_params.max_seqlen_k, + softmax_scale=None, + deterministic=torch.are_deterministic_algorithms_enabled(), + disable_fwd_atomic_reduction=True, + ) + # (b sq) hn hd -> (sq b) hn hd + core_attn_out = rearrange(core_attn_out, "(b sq) h d -> (sq b) h d", b=bs) + else: + # NOTE(lml): We convert multi denoising_range_num input into multi batch_size input at third time forward under 3_cfg mode, thus could not support normal multi batch_size input. We use an assert statement to ensure that it is still in this situation, thereby guaranteeing the correct use of q_range and k_range later on. + assert not (bs > 1 and meta_args.denoising_range_num > 1) + q_range = meta_args.core_attn_params.np_q_range + k_range = meta_args.core_attn_params.np_k_range + core_attn_outs = [] + q_seqlen = query.shape[1] + + try: + # Adapt to flowcache case where only a single chunk is passed + if q_seqlen == meta_args.clip_token_nums: + q = query + i = meta_args.start_chunk_id - meta_args.slice_point + k = key[:, k_range[i, 0] : k_range[i, 1]] + v = value[:, k_range[i, 0] : k_range[i, 1]] + o = flash_attn_func(q=q, k=k, v=v, deterministic=torch.are_deterministic_algorithms_enabled()) + o = rearrange(o, "b sq h d -> (sq b) h d", b=bs) + core_attn_outs.append(o) + elif meta_args.sparse_active_indices is not None and meta_args.denoising_range_num == 1: + i = meta_args.start_chunk_id - meta_args.slice_point + q = query + k = key[:, k_range[i, 0] : k_range[i, 1]] + v = value[:, k_range[i, 0] : k_range[i, 1]] + o = flash_attn_func(q=q, k=k, v=v, deterministic=torch.are_deterministic_algorithms_enabled()) + o = rearrange(o, "b sq h d -> (sq b) h d", b=bs) + core_attn_outs.append(o) + # Original + else: + for i in range(meta_args.denoising_range_num): # chunk_end - chunk_start + if bs == 1: + q = query[:, q_range[i, 0] : q_range[i, 1]] + k = key[:, k_range[i, 0] : k_range[i, 1]] + v = value[:, k_range[i, 0] : k_range[i, 1]] + else: + assert i == 0 + q = query[:, q_range[0, 0] : q_range[0, 1]] + k = key[:, k_range[0, 0] : k_range[0, 1]] + v = value[:, k_range[0, 0] : k_range[0, 1]] + + o = flash_attn_func(q=q, k=k, v=v, deterministic=torch.are_deterministic_algorithms_enabled()) + o = rearrange(o, "b sq h d -> (sq b) h d", b=bs) + core_attn_outs.append(o) + except RuntimeError as e: + print(f"RuntimeError in core_attention: {e}") + import pdb; pdb.set_trace() + + core_attn_out = torch.cat(core_attn_outs, dim=0) + return core_attn_out + + def full_attention(self, bs: int, meta_args: ModelMetaArgs, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, i: int): + # NOTE(lml): full_attention is used under cp_shuffle_overlap strategy. We further limit it to the case of bs=1, so that we do not need to pay attention to the arrangement of sq and bs dimensions. + assert bs == 1 + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + q_range = meta_args.core_attn_params.q_range[i : i + 1] - meta_args.core_attn_params.q_range[i, 0] + k_range = meta_args.core_attn_params.k_range[i : i + 1] + o, _ = flex_attention( + q, + k, + v, + q_ranges=q_range, + k_ranges=k_range, + max_seqlen_q=meta_args.core_attn_params.max_seqlen_q, + max_seqlen_k=meta_args.core_attn_params.max_seqlen_k, + softmax_scale=None, + deterministic=torch.are_deterministic_algorithms_enabled(), + disable_fwd_atomic_reduction=True, + ) + else: + k_range = meta_args.core_attn_params.np_k_range[i : i + 1] + k = k[k_range[0, 0] : k_range[0, 1]] + v = v[k_range[0, 0] : k_range[0, 1]] + o = flash_attn_func( + q=q.unsqueeze(0), + k=k.unsqueeze(0), + v=v.unsqueeze(0), + deterministic=torch.are_deterministic_algorithms_enabled(), + ).flatten(0, 1) + return o + + def cross_attention( + self, + mixed_qqkv: torch.Tensor, + key_value_states: torch.Tensor, + cross_attn_params: PackedCrossAttnParams, + get_xqkv_func: Callable, + ): + # ================= + # cross-attn for aggragating caption / condition + # ================= + query_xattn, key_xattn, value_xattn = get_xqkv_func(mixed_qqkv, key_value_states) + + if torch.cuda.get_device_capability()[0] >= 9 and flex_attention is not None: + xattn_out, _ = flex_attention( + query_xattn, + key_xattn, + value_xattn, + cross_attn_params.q_ranges, + cross_attn_params.kv_ranges, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_k=cross_attn_params.max_seqlen_kv, + softmax_scale=None, + deterministic=False, + disable_fwd_atomic_reduction=True, + ) + else: + xattn_out = flash_attn_varlen_func( + query_xattn, # [b*sq, hn, hd] + key_xattn, # [y_total_token, hn, hd] + value_xattn, # [y_total_token, hn, hd] + cu_seqlens_q=cross_attn_params.cu_seqlens_q, + cu_seqlens_k=cross_attn_params.cu_seqlens_kv, + max_seqlen_q=cross_attn_params.max_seqlen_q, + max_seqlen_k=cross_attn_params.max_seqlen_kv, + deterministic=torch.are_deterministic_algorithms_enabled(), + ) + + batch_size = mixed_qqkv.shape[1] + xattn_out = rearrange(xattn_out, "(b sq) hn hd -> sq b (hn hd)", b=batch_size).contiguous() + return xattn_out + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: torch.Tensor, + inference_params: InferenceParams, + rotary_pos_emb: torch.Tensor, + meta_args: ModelMetaArgs, + ): + assert rotary_pos_emb is not None, "FullyParallelAttention needs rotary_pos_emb" + sin_emb, cos_emb = rotary_pos_emb.tensor_split(2, -1) + batch_size = hidden_states.shape[1] + # All comminications operate on dimensions shaped as (cp * sq * b) + batch_cp_split_sizes = None if meta_args.cp_split_sizes is None else [x * batch_size for x in meta_args.cp_split_sizes] + + # Attention heads [sq, b, h] --> [sq, b, q + qx + k + v] + mixed_qqkv = self.linear_qkv.forward_ln(hidden_states) + + # ===================== + # Function wrapper + # ===================== + get_kv_func = self.get_kv + get_q_func = self.get_q + get_qkv_func = self.get_qkv + get_xqkv_func = self.get_xqkv + + # ===================== + # Parallel Strategy + # ===================== + if self.engine_config.cp_strategy == "none": + assert self.engine_config.cp_size == 1 + key_and_value = get_kv_func(mixed_qqkv, cos_emb, sin_emb) + query = get_q_func(mixed_qqkv, cos_emb, sin_emb) + + key, value = self.adjust_key_and_value_for_inference(key_and_value, inference_params, meta_args) + + # Save current query for subsequent compression + self._last_query = query.detach().clone() + + core_attn_out = self.core_attention(query, key, value, batch_size, meta_args) + core_attn_out = rearrange(core_attn_out, "(sq b) hn hd -> sq b (hn hd)", b=batch_size) + xattn_out = self.cross_attention(mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func) + + elif self.engine_config.cp_strategy == "cp_ulysses": + get_kv_func = partial(get_kv_func, mixed_qqkv, cos_emb, sin_emb) + get_q_func = partial(get_q_func, mixed_qqkv, cos_emb, sin_emb) + get_qkv_func = partial(get_qkv_func, mixed_qqkv, cos_emb, sin_emb) + kv_cache_func = partial( + self.adjust_key_and_value_for_inference, inference_params=inference_params, meta_args=meta_args + ) + if meta_args.enable_cuda_graph and meta_args.denoising_range_num <= 3: + # Temporal solution for first chunk opt + core_attn_out, xattn_out = UlyssesScheduler.get_attn_and_xattn_with_fused_qkv_comm( + get_qkv_func, + kv_cache_func, + partial(self.core_attention, bs=batch_size, meta_args=meta_args), + partial(self.cross_attention, mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func), + self.engine_config.ulysses_overlap_degree, + batch_size, + self.engine_config.cp_size, + batch_cp_split_sizes, + ) + else: + core_attn_out, xattn_out = UlyssesScheduler.get_attn_and_xattn_with_fused_kv_comm( + get_q_func, + get_kv_func, + kv_cache_func, + partial(self.core_attention, bs=batch_size, meta_args=meta_args), + partial(self.cross_attention, mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func), + self.engine_config.ulysses_overlap_degree, + batch_size, + self.engine_config.cp_size, + batch_cp_split_sizes, + ) + + elif self.engine_config.cp_strategy == "cp_shuffle_overlap": + key_and_value = self.get_kv(mixed_qqkv, cos_emb, sin_emb) + key_and_value, handle_kv = cso_communication(key_and_value, self.engine_config.cp_size, batch_cp_split_sizes, "kv") + + query = get_q_func(mixed_qqkv, cos_emb, sin_emb) + cso_helper = CSOHelper(meta_args.denoising_range_num, self.engine_config.cp_size, batch_cp_split_sizes) + query, handle_q = cso_helper.split_query_for_overlap(query) + + handle_kv.wait() + # NOTE(lml): rearrange and unpad key_and_value for later attention compute under cp_shuffle_overlap strategy, and we should split sqb into sq and b when support multi batch_size input. + key_and_value = ( + rearrange( + key_and_value, + "(cp dn sqb) hn nhd -> dn (cp sqb) hn nhd", + dn=meta_args.denoising_range_num, + cp=self.engine_config.cp_size, + )[:, : meta_args.clip_token_nums] + .flatten(0, 1) + .contiguous() + ) + key, value = self.adjust_key_and_value_for_inference(key_and_value, inference_params, meta_args) + + handle_q.wait() + core_attn_out, handle_attn = cso_helper.overlap( + partial(self.full_attention, hidden_states.shape[1], meta_args), query, key, value + ) + xattn_out = self.cross_attention(mixed_qqkv, key_value_states, meta_args.cross_attn_params, get_xqkv_func) + + handle_attn.wait() + core_attn_out = rearrange( + torch.concat(core_attn_out, dim=0), + "(dn cp sq b) hn hd -> (dn sq) b (cp hn hd)", + cp=self.engine_config.cp_size, + b=hidden_states.shape[1], + dn=meta_args.denoising_range_num, + ) + else: + raise ValueError(f"Unsupported cp_strategy: {self.engine_config.cp_strategy}") + + return core_attn_out, xattn_out + + +########################################################## +# TransformerLayer +########################################################## +class TransformerLayer(torch.nn.Module): + """A single transformer layer. + + Transformer layer takes input with size [s, b, h] and returns an + output of the same size. + """ + + def __init__(self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int = 1): + super().__init__() + self.model_config = model_config + self.engine_config = engine_config + self.layer_number = layer_number + self._get_layer_offset() + ## [Module 1: ada_modulate_layer + self.ada_modulate_layer = AdaModulateLayer(model_config=self.model_config) + + ## [Module 2: SelfAttention] + self.self_attention = FullyParallelAttention( + model_config=self.model_config, engine_config=self.engine_config, layer_number=self.layer_number + ) + + ## [Module 3: SelfAttention PostNorm] + self.self_attn_post_norm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + ## [Module 4: MLP block] + self.mlp = CustomMLP(model_config=self.model_config, engine_config=self.engine_config, layer_number=self.layer_number) + + ## [Module 5: MLP PostNorm] + self.mlp_post_norm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + def _get_layer_offset(self): + pipeline_rank = parallel_state.get_pp_rank() + + num_layers_per_pipeline_rank = self.model_config.num_layers // parallel_state.get_pp_world_size() + + # Each stage gets a contiguous set of layers. + if parallel_state.get_pp_world_size() > 1: + offset = pipeline_rank * num_layers_per_pipeline_rank + else: + offset = 0 + + return offset + + def forward( + self, + hidden_states: torch.Tensor, + condition: torch.Tensor, + condition_map: torch.Tensor, + y_xattn_flat: torch.Tensor, + rotary_pos_emb: torch.Tensor, + inference_params: InferenceParams, + meta_args: ModelMetaArgs, + ): + # hidden_states: [s/cp/sp, b, h] + residual = hidden_states + + # Self attention. + core_attn_out, cross_attn_out = self.self_attention( + hidden_states, + key_value_states=y_xattn_flat, + inference_params=inference_params, + rotary_pos_emb=rotary_pos_emb, + meta_args=meta_args, + ) + hidden_states = self.attn_post_process(core_attn_out, cross_attn_out, residual, condition, condition_map) + + return hidden_states + + def attn_post_process( + self, + core_attn_out: torch.Tensor, + cross_attn_out: torch.Tensor, + residual: torch.Tensor, + condition: torch.Tensor, + condition_map: torch.Tensor, + ): + hidden_states = self.attn_linear_proj(core_attn_out, cross_attn_out) + hidden_states = self.gating_and_mlp(hidden_states, residual, condition, condition_map) + return hidden_states + + def attn_linear_proj(self, core_attn_out: torch.Tensor, cross_attn_out: torch.Tensor): + # ============================================ + # attention post-process , output. [sq, b, h] + # ============================================ + + attn_out = torch.concat([core_attn_out, cross_attn_out], dim=2) + # NOTE: hn=8 is hardcoded to align with TP8 traning and TP1 inference + attn_out = rearrange(attn_out, "sq b (n hn hd) -> sq b (hn n hd)", n=2, hn=8) + if self.self_attention.adapt_linear_quant: + attn_out = self.self_attention.linear_proj(attn_out) + else: + # Use high-precision for non-quantized linear projection + with torch.autocast(device_type="cuda", dtype=torch.float32): + attn_out = self.self_attention.linear_proj(attn_out) + + return attn_out + + def gating_and_mlp( + self, hidden_states: torch.Tensor, residual: torch.Tensor, condition: torch.Tensor, condition_map: torch.Tensor + ): + gate_output = self.ada_modulate_layer(condition) + softcap_gate_cap = 1.0 + gate_output = softcap(gate_output, softcap_gate_cap) + gate_msa, gate_mlp = gate_output.chunk(2, dim=-1) + + # Residual connection for self-attention. + hidden_states = bias_modulate_add(hidden_states, residual, condition_map, gate_msa, self.self_attn_post_norm).to( + self.model_config.params_dtype + ) + + residual = hidden_states + hidden_states = self.mlp(hidden_states) + # Residual connection for MLP. + hidden_states = bias_modulate_add(hidden_states, residual, condition_map, gate_mlp, self.mlp_post_norm).to( + self.model_config.params_dtype + ) + return hidden_states + + +########################################################## +# TransformerBlock +########################################################## +class TransformerBlock(torch.nn.Module): + """Transformer class.""" + + def __init__( + self, model_config: ModelConfig, engine_config: EngineConfig, pre_process: bool = True, post_process: bool = True + ): + super().__init__() + + self.model_config = model_config + self.engine_config = engine_config + self.pre_process = pre_process + self.post_process = post_process + + # required for pipeline parallel schedules + self.input_tensor = None + + layer_number = self.model_config.num_layers // parallel_state.get_pp_world_size() + # offset is implicit in TransformerLayer + self.layers = torch.nn.ModuleList( + [ + TransformerLayer(model_config=self.model_config, engine_config=self.engine_config, layer_number=i) + for i in range(layer_number) + ] + ) + if self.post_process: + # Final layer norm before output. + self.final_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.model_config.hidden_size) + + def set_input_tensor(self, input_tensor: Tensor): + """Set input tensor to be used instead of forward()'s input. + + When doing pipeline parallelism the input from the previous + stage comes from communication, not from the input, so the + model's forward_step_func won't have it. This function is thus + used by internal code to bypass the input provided by the + forward_step_func""" + self.input_tensor = input_tensor + + @torch.no_grad() + def forward( + self, + hidden_states: Tensor, + condition: Tensor, + condition_map: Tensor, + y_xattn_flat: Tensor, + rotary_pos_emb: Tensor, + inference_params: InferenceParams, + meta_args: ModelMetaArgs, + ) -> torch.Tensor: + if not self.pre_process: + assert self.input_tensor is not None, "please call set_input_tensor for pp" + hidden_states = self.input_tensor + + for layer in self.layers: + hidden_states = layer( + hidden_states=hidden_states, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rotary_pos_emb, + inference_params=inference_params, + meta_args=meta_args, + ) + + # Final layer norm. + if self.post_process: + hidden_states = self.final_layernorm(hidden_states.float()) + + return hidden_states \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0a916be0148ab30dac23af283700ba551f72ac --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .t5_model import T5Embedder + +__all__ = ["T5Embedder"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62652e58bc78cd3187c3f79bb39360b0db57d11d Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/t5_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/t5_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9f9e6bb6d0f0526b44607c1fd69160e4d92f35 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/__pycache__/t5_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/t5_model.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/t5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1f3ccbee178b51cd0cfa781d0479ff961e848f41 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/t5/t5_model.py @@ -0,0 +1,286 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import html +import os +import re +import urllib.parse as ul + +import ftfy +import torch +from bs4 import BeautifulSoup +from huggingface_hub import hf_hub_download +from transformers import AutoTokenizer, T5EncoderModel + + +def save_model_as_safetensors(model): + from safetensors.torch import save_file + state_dict = model.state_dict() + for k in state_dict: + state_dict[k] = state_dict[k].contiguous() + + save_file(state_dict, "/path/to/t5/model.safetensors") + +class T5Embedder: + available_models = ["t5-v1_1-xxl"] + bad_punct_regex = re.compile( + r"[" + "#®•©™&@·º½¾¿¡§~" + "\)" + "\(" + "\]" + "\[" + "\}" + "\{" + "\|" + "\\" + "\/" + "\*" + r"]{1,}" + ) # noqa + + def __init__( + self, + device, + dir_or_name="t5-v1_1-xxl", + *, + local_cache=False, + cache_dir=None, + hf_token=None, + use_text_preprocessing=True, + t5_model_kwargs=None, + torch_dtype=None, + use_offload_folder=None, + model_max_length=120, + ): + self.device = torch.device(device) + self.torch_dtype = torch_dtype or torch.bfloat16 + if t5_model_kwargs is None: + t5_model_kwargs = {"low_cpu_mem_usage": True, "torch_dtype": self.torch_dtype} + if use_offload_folder is not None: + t5_model_kwargs["offload_folder"] = use_offload_folder + t5_model_kwargs["device_map"] = { + "shared": self.device, + "encoder.embed_tokens": self.device, + "encoder.block.0": self.device, + "encoder.block.1": self.device, + "encoder.block.2": self.device, + "encoder.block.3": self.device, + "encoder.block.4": self.device, + "encoder.block.5": self.device, + "encoder.block.6": self.device, + "encoder.block.7": self.device, + "encoder.block.8": self.device, + "encoder.block.9": self.device, + "encoder.block.10": self.device, + "encoder.block.11": self.device, + "encoder.block.12": "disk", + "encoder.block.13": "disk", + "encoder.block.14": "disk", + "encoder.block.15": "disk", + "encoder.block.16": "disk", + "encoder.block.17": "disk", + "encoder.block.18": "disk", + "encoder.block.19": "disk", + "encoder.block.20": "disk", + "encoder.block.21": "disk", + "encoder.block.22": "disk", + "encoder.block.23": "disk", + "encoder.final_layer_norm": "disk", + "encoder.dropout": "disk", + } + else: + t5_model_kwargs["device_map"] = {"shared": self.device, "encoder": self.device} + self.use_text_preprocessing = use_text_preprocessing + self.hf_token = hf_token + self.cache_dir = cache_dir or os.path.expanduser("~/.cache/IF_") + self.dir_or_name = dir_or_name + tokenizer_path, path = dir_or_name, dir_or_name + if local_cache: + cache_dir = os.path.join(self.cache_dir, dir_or_name) + tokenizer_path, path = cache_dir, cache_dir + elif dir_or_name in self.available_models: + cache_dir = os.path.join(self.cache_dir, dir_or_name) + for filename in [ + "config.json", + "special_tokens_map.json", + "spiece.model", + "tokenizer_config.json", + "pytorch_model.bin.index.json", + "pytorch_model-00001-of-00002.bin", + "pytorch_model-00002-of-00002.bin", + ]: + hf_hub_download( + repo_id=f"DeepFloyd/{dir_or_name}", + filename=filename, + cache_dir=cache_dir, + force_filename=filename, + token=self.hf_token, + ) + tokenizer_path, path = cache_dir, cache_dir + else: + cache_dir = os.path.join(self.cache_dir, "t5-v1_1-xxl") + for filename in ["config.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"]: + hf_hub_download( + repo_id="DeepFloyd/t5-v1_1-xxl", + filename=filename, + cache_dir=cache_dir, + force_filename=filename, + token=self.hf_token, + ) + tokenizer_path = cache_dir + + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) + self.model = T5EncoderModel.from_pretrained(path, **t5_model_kwargs).eval() + self.model_max_length = model_max_length + + + def get_text_embeddings(self, texts): + texts = [self.text_preprocessing(text) for text in texts] + + text_tokens_and_mask = self.tokenizer( + texts, + max_length=self.model_max_length, + padding="max_length", + truncation=True, + return_attention_mask=True, + add_special_tokens=True, + return_tensors="pt", + ) + + text_tokens_and_mask["input_ids"] = text_tokens_and_mask["input_ids"] + text_tokens_and_mask["attention_mask"] = text_tokens_and_mask["attention_mask"] + + with torch.no_grad(): + text_encoder_embs = self.model( + input_ids=text_tokens_and_mask["input_ids"].to(self.device), + attention_mask=text_tokens_and_mask["attention_mask"].to(self.device), + )["last_hidden_state"].detach() + return text_encoder_embs, text_tokens_and_mask["attention_mask"].to(self.device) + + def text_preprocessing(self, text): + if self.use_text_preprocessing: + # The exact text cleaning as was in the training stage: + text = self.clean_caption(text) + text = self.clean_caption(text) + return text + else: + return text.lower().strip() + + @staticmethod + def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + def clean_caption(self, caption): + caption = str(caption) + caption = ul.unquote_plus(caption) + caption = caption.strip().lower() + caption = re.sub("", "person", caption) + # urls: + caption = re.sub( + r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa + "", + caption, + ) # regex for urls + caption = re.sub( + r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa + "", + caption, + ) # regex for urls + # html: + caption = BeautifulSoup(caption, features="html.parser").text + + # @ + caption = re.sub(r"@[\w\d]+\b", "", caption) + + # 31C0—31EF CJK Strokes + # 31F0—31FF Katakana Phonetic Extensions + # 3200—32FF Enclosed CJK Letters and Months + # 3300—33FF CJK Compatibility + # 3400—4DBF CJK Unified Ideographs Extension A + # 4DC0—4DFF Yijing Hexagram Symbols + # 4E00—9FFF CJK Unified Ideographs + caption = re.sub(r"[\u31c0-\u31ef]+", "", caption) + caption = re.sub(r"[\u31f0-\u31ff]+", "", caption) + caption = re.sub(r"[\u3200-\u32ff]+", "", caption) + caption = re.sub(r"[\u3300-\u33ff]+", "", caption) + caption = re.sub(r"[\u3400-\u4dbf]+", "", caption) + caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption) + caption = re.sub(r"[\u4e00-\u9fff]+", "", caption) + ####################################################### + + # все виды тире / all types of dash --> "-" + caption = re.sub( + r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa + "-", + caption, + ) + + # кавычки к одному стандарту + caption = re.sub(r"[`´«»“”¨]", '"', caption) + caption = re.sub(r"[‘’]", "'", caption) + + # " + caption = re.sub(r""?", "", caption) + # & + caption = re.sub(r"&", "", caption) + + # ip adresses: + caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption) + + # article ids: + caption = re.sub(r"\d:\d\d\s+$", "", caption) + + # \n + caption = re.sub(r"\\n", " ", caption) + + # "#123" + caption = re.sub(r"#\d{1,3}\b", "", caption) + # "#12345.." + caption = re.sub(r"#\d{5,}\b", "", caption) + # "123456.." + caption = re.sub(r"\b\d{6,}\b", "", caption) + # filenames: + caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption) + + # + caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT""" + caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT""" + + caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT + caption = re.sub(r"\s+\.\s+", r" ", caption) # " . " + + # this-is-my-cute-cat / this_is_my_cute_cat + regex2 = re.compile(r"(?:\-|\_)") + if len(re.findall(regex2, caption)) > 3: + caption = re.sub(regex2, " ", caption) + + caption = self.basic_clean(caption) + + caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640 + caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc + caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231 + + caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption) + caption = re.sub(r"(free\s)?download(\sfree)?", "", caption) + caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption) + caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption) + caption = re.sub(r"\bpage\s+\d+\b", "", caption) + + caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a... + + caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption) + + caption = re.sub(r"\b\s+\:\s+", r": ", caption) + caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption) + caption = re.sub(r"\s+", " ", caption) + + caption.strip() + + caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption) + caption = re.sub(r"^[\'\_,\-\:;]", r"", caption) + caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption) + caption = re.sub(r"^\.\S+$", "", caption) + + return caption.strip() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc68d8a76ae0ccc0b43d5faa4cafc5c7d1e1c2d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .vae_model import AutoModel, VideoTokenizerABC, ViTVAE +from .vae_module import DiagonalGaussianDistribution + +__all__ = ["AutoModel", "VideoTokenizerABC", "ViTVAE", "DiagonalGaussianDistribution"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2f898376d1bae9a26dd8fefabb0ddfece4d6cfa Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_model.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf2f95e938b0fbd703d977fc94e3b57da81f0197 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_model.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_module.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c09721362bcb6646a7e21f45daac4ad4a5e69daf Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/__pycache__/vae_module.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_model.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b8812c11b0b084ff65a3d74c1d485a0a038d28b0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_model.py @@ -0,0 +1,361 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from abc import ABC, abstractmethod +from typing import Literal + +import torch +from diffusers import ConfigMixin, ModelMixin +from diffusers.configuration_utils import register_to_config + +from inference.infra.parallelism import TileProcessor + +from .vae_module import DiagonalGaussianDistribution, ViTDecoder, ViTEncoder + + +class VideoTokenizerABC(ABC): + """ + Abstract base class for video tokenizers. + + This class defines the interface for video tokenizers and provides common methods and properties. + """ + + @property + @abstractmethod + def spatial_downsample_factor(self): + """ + Property representing the spatial downsample factor. + + Returns: + int: The spatial downsample factor. + """ + raise NotImplementedError + + @property + @abstractmethod + def temporal_downsample_factor(self): + """ + Property representing the temporal downsample factor. + + Returns: + int: The temporal downsample factor. + """ + raise NotImplementedError + + @property + def first_frame_as_image(self): + """ + Property representing the first frame as image. + For tokenizer like CausalVAE, Omnitokenizer, the first frame is treated as image. + in this case if the temporal downsample factor is 4, the input should be 4*x+1, and encoded tensor would be x+1. + for example encode 65 frames to 17 frames. and decode 17 frames to 65 frames. + + Returns: + bool: The first frame as image. + """ + return False + + @property + def allow_spatial_tiling(self): + """ + Determines whether spatial tiling is allowed or not. + + Returns: + bool: True if spatial tiling is allowed, False otherwise. + """ + return True + + @abstractmethod + def encode(self, x) -> torch.Tensor: + """ + Abstract method for encoding the input tensor. + + Args: + x (torch.Tensor [N C T H W] range[-1, 1]): The input tensor to be encoded. + + Returns: + torch.Tensor: The encoded tensor. + """ + raise NotImplementedError + + @abstractmethod + def decode(self, x) -> torch.Tensor: + """ + Abstract method for decoding the input tensor. + + Args: + x (torch.Tensor [N C T H W]): The input tensor to be decoded. + + Returns: + torch.Tensor [N C T H W] range[-1, 1]: The decoded tensor. + """ + raise NotImplementedError + + def tile_processor( + self, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length=16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> TileProcessor: + """ + Property representing the tiled encoder or decoder. + + Returns: + TileProcessor: The tiled encoder or decoder. + """ + return TileProcessor( + encode_fn=self.encode, + decode_fn=self.decode, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + sr_ratio=getattr(self, 'sr_ratio', 1), + spatial_downsample_factor=self.spatial_downsample_factor, + temporal_downsample_factor=self.temporal_downsample_factor, + first_frame_as_image=self.first_frame_as_image, + parallel_group=parallel_group, + ) + + @torch.inference_mode() + def tiled_encode_3d( + self, + x, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length: int = 16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = None, + verbose: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Encodes the input tensor `x` using tiled encoding. + + Args: + x (torch.Tensor shape:[N C T H W]): The input tensor to be encoded. + tile_sample_min_height (int, optional): The minimum height of each tile sample. Defaults to 256. + tile_sample_min_width (int, optional): The minimum width of each tile sample. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of each tile sample. Defaults to 16. + spatial_tile_overlap_factor (float, optional): Overlap factor for spatial tiles. Defaults to 0.25. + temporal_tile_overlap_factor (float, optional): Overlap factor for temporal tiles. Defaults to 0. + allow_spatial_tiling (bool, optional): Whether spatial tiling is allowed. Defaults to None. + verbose (bool, optional): Whether to print verbose information. Defaults to False. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed encoding group. Defaults to None. + Returns: + torch.Tensor: The encoded tensor. + """ + allow_spatial_tiling = allow_spatial_tiling if allow_spatial_tiling is not None else self.allow_spatial_tiling + if not allow_spatial_tiling: + tile_sample_min_height = 100000 + tile_sample_min_width = 100000 + return self.tile_processor( + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + parallel_group=parallel_group, + ).tiled_encode(x, verbose) + + @torch.inference_mode() + def tiled_decode_3d( + self, + x, + tile_sample_min_height=256, + tile_sample_min_width=256, + tile_sample_min_length: int = 16, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = None, + verbose: bool = False, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Decodes the input tensor using the tile autoencoder. + + Args: + x (torch.Tensor): The input tensor to be decoded. + tile_sample_min_height (int, optional): The minimum height of each tile sample. Defaults to 256. + tile_sample_min_width (int, optional): The minimum width of each tile sample. Defaults to 256. + tile_sample_min_length (int, optional): The minimum length of each tile sample. Defaults to 16. + spatial_tile_overlap_factor (float, optional): Overlap factor for spatial tiles. Defaults to 0.25. + temporal_tile_overlap_factor (float, optional): Overlap factor for temporal tiles. Defaults to 0. + allow_spatial_tiling (bool, optional): Whether spatial tiling is allowed. Defaults to None. + verbose (bool, optional): Whether to print verbose information. Defaults to False. + parallel_group (torch.distributed.ProcessGroup, optional): Distributed decoding group. Defaults to None. + Returns: + torch.Tensor shape:[N C T H W]: The decoded tensor. + """ + allow_spatial_tiling = allow_spatial_tiling if allow_spatial_tiling is not None else self.allow_spatial_tiling + if not allow_spatial_tiling: + tile_sample_min_height = 100000 + tile_sample_min_width = 100000 + return self.tile_processor( + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + tile_sample_min_length=tile_sample_min_length, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + parallel_group=parallel_group, + ).tiled_decode(x, verbose) + + +class ViTVAE(ModelMixin, ConfigMixin, VideoTokenizerABC): + @register_to_config + def __init__(self, ddconfig: dict, model_type: Literal['vit', 'vit_ncthw'] = 'vit'): + super().__init__() + + if model_type == 'vit': + self.encoder = ViTEncoder(**ddconfig) + self.decoder = ViTDecoder(**ddconfig) + elif model_type == 'vit_ncthw': + from videotokenizer.modules.vit_ncthw import ViTDecoderNCTHW, ViTEncoderNCTHW + + self.encoder = ViTEncoderNCTHW(**ddconfig) + self.decoder = ViTDecoderNCTHW(**ddconfig) + else: + raise ValueError(f"model_type {model_type} not supported") + + if 'patch_length' in ddconfig: + self._temporal_downsample_factor = ddconfig['patch_length'] + else: + self._temporal_downsample_factor = 1 + + if 'patch_size' in ddconfig: + self._spatial_downsample_factor = ddconfig['patch_size'] + else: + self._spatial_downsample_factor = 8 + + @property + def spatial_downsample_factor(self): + return self._spatial_downsample_factor + + @property + def temporal_downsample_factor(self): + return self._temporal_downsample_factor + + def init_from_ckpt(self, path, ignore_keys=list()): + raise NotImplementedError + + def encode(self, x, sample_posterior=True): + """ + Encode the input video. + + Args: + x (torch.Tensor): Input video tensor has shape N C T H W + + Returns: + tuple: Tuple containing the quantized tensor, embedding loss, and additional information. + """ + N, C, T, H, W = x.shape + if T == 1 and self._temporal_downsample_factor > 1: + x = x.expand(-1, -1, 4, -1, -1) + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + return z[:, :, :1, :, :].type(x.dtype) + else: + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + return z.type(x.dtype) + + def decode(self, x): + """ + Decode the quantized tensor. + + Args: + quant (torch.Tensor): Quantized tensor. + + Returns: + torch.Tensor: Decoded tensor. + """ + N, C, T, H, W = x.shape + if T == 1: + x = x.expand(-1, -1, 1, -1, -1) + x = self.decoder(x) + x = x[:, :, :1, :, :] + return x + else: + x = self.decoder(x) + return x + + def forward(self, x, sample_posterior=True): + x = self.encoder(x) + posterior = DiagonalGaussianDistribution(x) + + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + + dec = self.decoder(z) + return dec, posterior + + def get_last_layer(self): + """ + Get the last layer of the decoder. + + Returns: + torch.Tensor: Last layer of the decoder. + """ + return self.decoder.last_layer.weight + + @property + def allow_spatial_tiling(self): + return False + + +class AutoModel: + r""" + :class:`~models.AutoModel` is a generic model class + that will be instantiated as one of the base model classes of the library + when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)` + + + This class cannot be instantiated using `__init__()` (throws an error). + """ + + def __init__(self): + raise EnvironmentError( + "AutoModel is designed to be instantiated " + "using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` method." + ) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs) -> VideoTokenizerABC: + config = os.path.join(pretrained_model_name_or_path, 'config.json') + if not os.path.exists(config): + raise ValueError("Can't find a model config file at {}.".format(config)) + # Load config + with open(config, 'r') as json_file: + config_dict = json.load(json_file) + assert config_dict['_class_name'] == 'ViTVAE' + return ViTVAE.from_pretrained(pretrained_model_name_or_path, *args, **kwargs) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_module.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_module.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4501b045bd11fde4920ea316a39b792eca92e1 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/model/vae/vae_module.py @@ -0,0 +1,757 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from functools import lru_cache +from typing import List, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn +from einops import rearrange +from flash_attn import flash_attn_func, flash_attn_qkvpacked_func +from timm.models.layers import to_2tuple, trunc_normal_ + +################################################### +# modified 3D rotary embedding from timm +################################################### + + +def ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: + """generate N-D grid in dimension order. + + The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. + + That is, the statement + [X1,X2,X3] = ndgrid(x1,x2,x3) + + produces the same result as + + [X2,X1,X3] = meshgrid(x2,x1,x3) + + This naming is based on MATLAB, the purpose is to avoid confusion due to torch's change to make + torch.meshgrid behaviour move from matching ndgrid ('ij') indexing to numpy meshgrid defaults of ('xy'). + + """ + try: + return torch.meshgrid(*tensors, indexing='ij') + except TypeError: + # old PyTorch < 1.10 will follow this path as it does not have indexing arg, + # the old behaviour of meshgrid was 'ij' + return torch.meshgrid(*tensors) + + +def freq_bands( + num_bands: int, temperature: float = 10000.0, step: int = 2, device: Optional[torch.device] = None +) -> torch.Tensor: + exp = torch.arange(0, num_bands, step, dtype=torch.int64, device=device).to(torch.float32) / num_bands + bands = 1.0 / (temperature**exp) + return bands + + +def pixel_freq_bands( + num_bands: int, max_freq: float = 224.0, linear_bands: bool = True, device: Optional[torch.device] = None +): + if linear_bands: + bands = torch.linspace(1.0, max_freq / 2, num_bands, dtype=torch.float32, device=device) + else: + bands = 2 ** torch.linspace(0, math.log(max_freq, 2) - 1, num_bands, dtype=torch.float32, device=device) + return bands * torch.pi + + +def build_fourier_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + num_bands: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + include_grid: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, + center_imgidx=True, +) -> List[torch.Tensor]: + """ + + Args: + feat_shape: Feature shape for embedding. + bands: Pre-calculated frequency bands. + num_bands: Number of frequency bands (determines output dim). + max_res: Maximum resolution for pixel based freq. + temperature: Temperature for non-pixel freq. + linear_bands: Linear band spacing for pixel based freq. + include_grid: Include the spatial grid in output. + in_pixels: Output in pixel freq. + ref_feat_shape: Reference feature shape for resize / fine-tune. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + if bands is None: + if in_pixels: + bands = pixel_freq_bands(num_bands, float(max_res), linear_bands=linear_bands, device=device) + else: + bands = freq_bands(num_bands, temperature=temperature, step=1, device=device) + else: + if device is None: + device = bands.device + if dtype is None: + dtype = bands.dtype + + if in_pixels: + t = [torch.linspace(-1.0, 1.0, steps=s, device=device, dtype=torch.float32) for s in feat_shape] + else: + if center_imgidx: + t = [ + torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) - (s - 1) / 2 + if len(feat_shape) == 2 or i != 0 + else torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) + for i, s in enumerate(feat_shape) + ] + else: + t = [torch.arange(s, device=device, dtype=torch.int64).to(torch.float32) for s in feat_shape] + + if ref_feat_shape is not None: + assert len(feat_shape) == len(ref_feat_shape), 'shape must be in same dimension' + # eva's scheme for resizing rope embeddings (ref shape = pretrain) + t = [x / f * r for x, f, r in zip(t, feat_shape, ref_feat_shape)] + + grid = torch.stack(ndgrid(t), dim=-1) + grid = grid.unsqueeze(-1) + pos = grid * bands + pos_sin, pos_cos = pos.sin().to(dtype=dtype), pos.cos().to(dtype) + out = [grid, pos_sin, pos_cos] if include_grid else [pos_sin, pos_cos] + return out + + +def rot(x): + return torch.stack([-x[..., 1::2], x[..., ::2]], -1).reshape(x.shape) + + +def apply_rot_embed(x: torch.Tensor, sin_emb, cos_emb): + if sin_emb.ndim == 3: + return x * cos_emb.unsqueeze(1).expand_as(x) + rot(x) * sin_emb.unsqueeze(1).expand_as(x) + # import ipdb; ipdb.set_trace() + return x * cos_emb + rot(x) * sin_emb + + +def build_rotary_pos_embed( + feat_shape: List[int], + bands: Optional[torch.Tensor] = None, + dim: int = 64, + max_res: int = 224, + temperature: float = 10000.0, + linear_bands: bool = False, + in_pixels: bool = True, + ref_feat_shape: Optional[List[int]] = None, + dtype: torch.dtype = torch.float32, + device: Optional[torch.device] = None, + center_imgidx=True, +): + """ + + Args: + feat_shape: Spatial shape of the target tensor for embedding. + bands: Optional pre-generated frequency bands + dim: Output dimension of embedding tensor. + max_res: Maximum resolution for pixel mode. + temperature: Temperature (inv freq) for non-pixel mode + linear_bands: Linearly (instead of log) spaced bands for pixel mode + in_pixels: Pixel vs language (inv freq) mode. + dtype: Output dtype. + device: Output device. + + Returns: + + """ + sin_emb, cos_emb = build_fourier_pos_embed( + feat_shape, + bands=bands, + num_bands=dim // (len(feat_shape) * 2), + max_res=max_res, + temperature=temperature, + linear_bands=linear_bands, + in_pixels=in_pixels, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + center_imgidx=center_imgidx, + ) + num_spatial_dim = 1 + # this would be much nicer as a .numel() call to torch.Size(), but torchscript sucks + for x in feat_shape: + num_spatial_dim *= x + sin_emb = sin_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1) + cos_emb = cos_emb.reshape(num_spatial_dim, -1).repeat_interleave(2, -1) + return sin_emb, cos_emb + + +################################################### +# Mlp +################################################### +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +################################################### +# ManualLayerNorm +################################################### +class ManualLayerNorm(nn.Module): + def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): + super(ManualLayerNorm, self).__init__() + self.normalized_shape = normalized_shape + self.eps = eps + self.elementwise_affine = elementwise_affine + + def forward(self, x): + mean = x.mean(dim=-1, keepdim=True) + std = x.std(dim=-1, keepdim=True, unbiased=False) + + x_normalized = (x - mean) / (std + self.eps) + + return x_normalized + + +################################################### +# Attention +################################################### +@lru_cache(maxsize=50) +def cache_rotary_emb(feat_shape, device='cuda', dim=64, dtype=torch.bfloat16, max_res=512, ref_feat_shape=(4, 16, 16)): + return build_rotary_pos_embed( + feat_shape=feat_shape, + dim=dim, + max_res=max_res, + in_pixels=False, + ref_feat_shape=ref_feat_shape, + device=device, + dtype=dtype, + ) + + +class Attention(nn.Module): + def __init__( + self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, ln_in_attn=False, use_rope=False + ): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop_rate = attn_drop + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + if ln_in_attn: + self.qkv_norm = ManualLayerNorm(head_dim, elementwise_affine=False) + else: + self.qkv_norm = nn.Identity() + self.use_rope = use_rope + + def forward(self, x, feat_shape=None): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + qkv = self.qkv_norm(qkv) + q, k, v = qkv.chunk(3, dim=2) + if self.use_rope: + assert feat_shape is not None + q, k, v = qkv.chunk(3, dim=2) + rope_emb = cache_rotary_emb(feat_shape=feat_shape, dim=C // self.num_heads, device=x.device, dtype=x.dtype) + sin_emb = rope_emb[0].unsqueeze(0).unsqueeze(2) + cos_emb = rope_emb[1].unsqueeze(0).unsqueeze(2) + print(q.shape, sin_emb.shape) + q[:, 1:, :] = apply_rot_embed(q[:, 1:, :], sin_emb, cos_emb).bfloat16() + k[:, 1:, :] = apply_rot_embed(k[:, 1:, :], sin_emb, cos_emb).bfloat16() + x = flash_attn_func(q, k, v, dropout_p=self.attn_drop_rate) + else: + x = flash_attn_qkvpacked_func(qkv=qkv.bfloat16(), dropout_p=self.attn_drop_rate) + # x = v + x = x.reshape(B, N, C) + # import ipdb; ipdb.set_trace() + x = self.proj(x) + x = self.proj_drop(x) + return x + + +################################################### +# Block +################################################### +class Block(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ln_in_attn=False, + use_rope=False, + ): + super().__init__() + if not ln_in_attn: + self.norm1 = norm_layer(dim) + else: + self.norm1 = nn.Identity() + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + self.drop_path = nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, feat_shape=None): + x = x + self.drop_path(self.attn(self.norm1(x), feat_shape=feat_shape)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +################################################### +# PatchEmbed +################################################### +class PatchEmbed(nn.Module): + """Image to Patch Embedding""" + + def __init__(self, video_size=224, video_length=16, patch_size=16, patch_length=1, in_chans=3, embed_dim=768): + super().__init__() + video_size = to_2tuple(video_size) + patch_size = to_2tuple(patch_size) + + num_patches = (video_length // patch_length) * (video_size[1] // patch_size[1]) * (video_size[0] // patch_size[0]) + + self.video_size = video_size + self.patch_size = patch_size + + self.video_length = video_length + self.patch_length = patch_length + + self.num_patches = num_patches + + self.proj = nn.Conv3d( + in_chans, + embed_dim, + kernel_size=(patch_length, patch_size[0], patch_size[1]), + stride=(patch_length, patch_size[0], patch_size[1]), + ) + + def forward(self, x): + """ + Forward pass of the PatchEmbed module. + + Args: + x (torch.Tensor): Input tensor of shape (B, C, T, H, W), where + B is the batch size, C is the number of channels, T is the + number of frames, H is the height, and W is the width. + + Returns: + torch.Tensor: Output tensor of shape (B, L, C'), where B is the + batch size, L is the number of tokens, and C' is the number + of output channels after flattening and transposing. + """ + B, C, T, H, W = x.shape + + x = self.proj(x) + return x + + +################################################### +# ViTEncoder +################################################### +def resize_pos_embed(posemb, src_shape, target_shape): + posemb = posemb.reshape(1, src_shape[0], src_shape[1], src_shape[2], -1) + posemb = posemb.permute(0, 4, 1, 2, 3) + posemb = nn.functional.interpolate(posemb, size=target_shape, mode='trilinear', align_corners=False) + posemb = posemb.permute(0, 2, 3, 4, 1) + posemb = posemb.reshape(1, target_shape[0] * target_shape[1] * target_shape[2], -1) + return posemb + + +class ViTEncoder(nn.Module): + """Vision Transformer with support for patch or hybrid CNN input stage""" + + def __init__( + self, + video_size=256, + video_length=16, + patch_size=8, + patch_length=4, + in_chans=3, + z_chans=4, + double_z=True, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + with_cls_token=True, + norm_code=False, + ln_in_attn=False, + conv_last_layer=False, + use_rope=False, + use_final_proj=False, + ): + super().__init__() + + conv_last_layer = False # duplicate argument + + # self.num_classes = num_classes + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.latent_size = video_size // patch_size + self.latent_length = video_length // patch_length + + self.patch_embed = PatchEmbed( + video_size=video_size, + video_length=video_length, + patch_size=patch_size, + patch_length=patch_length, + in_chans=in_chans, + embed_dim=embed_dim, + ) + + num_patches = self.patch_embed.num_patches + self.with_cls_token = with_cls_token + if with_cls_token: + self.cls_token_nums = 1 + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + else: + self.cls_token_nums = 0 + self.cls_token = None + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.cls_token_nums, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + for i in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + + self.norm_code = norm_code + + self.out_channels = z_chans * 2 if double_z else z_chans + self.last_layer = nn.Linear(embed_dim, self.out_channels, bias=True) + + trunc_normal_(self.pos_embed, std=0.02) + + if self.with_cls_token: + trunc_normal_(self.cls_token, std=0.02) + + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def forward(self, x): + B = x.shape[0] + # B C T H W -> B C T/pT H/pH W//pW + x = self.patch_embed(x) + latentT, latentH, latentW = x.shape[2], x.shape[3], x.shape[4] + # B C T/pT H/pH W//pW -> B (T/pT H/pH W//pW) C + x = x.flatten(2).transpose(1, 2) + + if self.with_cls_token: + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + if latentT != self.latent_length or latentH != self.latent_size or latentW != self.latent_size: + pos_embed = resize_pos_embed( + self.pos_embed[:, 1:, :], + src_shape=(self.latent_length, self.latent_size, self.latent_size), + target_shape=(latentT, latentH, latentW), + ) + pos_embed = torch.cat((self.pos_embed[:, 0:1, :], pos_embed), dim=1) + else: + pos_embed = self.pos_embed + + x = x + pos_embed + x = self.pos_drop(x) + + for idx, blk in enumerate(self.blocks): + x = blk(x, feat_shape=(latentT, latentH, latentW)) + + x = self.norm(x) + x = self.last_layer(x) + + if self.with_cls_token: + x = x[:, 1:] # remove cls_token + + # B L C - > B , lT, lH, lW, zC + x = x.reshape(B, latentT, latentH, latentW, self.out_channels) + + # B , lT, lH, lW, zC -> B, zC, lT, lH, lW + x = x.permute(0, 4, 1, 2, 3) + if self.norm_code: + prev_dtype = x.dtype + x = x.float() + x = x / torch.norm(x, dim=1, keepdim=True) + x = x.to(prev_dtype) + return x + + def freeze_pretrain(self): + # Freeze all parameters + for param in self.parameters(): + param.requires_grad = False + + +################################################### +# ViTDecoder +################################################### +class ViTDecoder(nn.Module): + """Vision Transformer with support for patch or hybrid CNN input stage""" + + def __init__( + self, + video_size=256, + video_length=16, + patch_size=8, + patch_length=4, + in_chans=3, + z_chans=4, + double_z=True, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + with_cls_token=True, + norm_code=False, + ln_in_attn=False, + conv_last_layer=False, + use_rope=False, + use_final_proj=False, + ): + super().__init__() + + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.latent_size = video_size // patch_size + self.latent_length = video_length // patch_length + self.patch_size = patch_size + self.patch_length = patch_length + + self.proj_in = nn.Linear(z_chans, embed_dim) + + num_patches = self.latent_size * self.latent_size * self.latent_length + + self.with_cls_token = with_cls_token + if with_cls_token: + self.cls_token_nums = 1 + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + else: + self.cls_token_nums = 0 + self.cls_token = None + + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.cls_token_nums, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ln_in_attn=ln_in_attn, + use_rope=use_rope, + ) + for i in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + + assert conv_last_layer == True, "Only support conv_last_layer=True" + + self.unpatch_channels = embed_dim // (patch_size * patch_size * patch_length) + self.final_proj = nn.Identity() + self.final_norm = nn.Identity() + + self.use_final_proj = use_final_proj + if self.use_final_proj: + self.unpatch_channels = 4 + self.final_proj = nn.Linear(embed_dim, self.unpatch_channels * (patch_size * patch_size * patch_length), bias=True) + self.final_norm = norm_layer(self.unpatch_channels * (patch_size * patch_size * patch_length)) + + self.last_layer = nn.Conv3d(in_channels=self.unpatch_channels, out_channels=3, kernel_size=3, stride=1, padding=1) + + trunc_normal_(self.pos_embed, std=0.02) + + if self.with_cls_token: + trunc_normal_(self.cls_token, std=0.02) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay(self): + return {'pos_embed', 'cls_token'} + + def forward(self, x): + B, C, latentT, latentH, latentW = x.shape # x: (B, C, latentT, latentH, latenW) + x = x.permute(0, 2, 3, 4, 1) # x: (B, latentT, latentH, latenW, C) + + x = x.reshape(B, -1, C) + + x = self.proj_in(x) + + if self.with_cls_token: + cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + if latentT != self.latent_length or latentH != self.latent_size or latentW != self.latent_size: + pos_embed = resize_pos_embed( + self.pos_embed[:, 1:, :], + src_shape=(self.latent_length, self.latent_size, self.latent_size), + target_shape=(latentT, latentH, latentW), + ) + pos_embed = torch.cat((self.pos_embed[:, 0:1, :], pos_embed), dim=1) + else: + pos_embed = self.pos_embed + + x = x + pos_embed + x = self.pos_drop(x) + + for idx, blk in enumerate(self.blocks): + x = blk(x, feat_shape=(latentT, latentH, latentW)) + + x = self.norm(x) + + if self.with_cls_token: + x = x[:, 1:] # remove cls_token + # B L C - > B, lT, lH, lW, pT, pH, pW, C + if self.use_final_proj: + x = self.final_proj(x) + x = self.final_norm(x) + x = x.reshape(B, latentT, latentH, latentW, self.patch_length, self.patch_size, self.patch_size, self.unpatch_channels) + x = rearrange(x, 'B lT lH lW pT pH pW C -> B C (lT pT) (lH pH) (lW pW)', C=self.unpatch_channels) + + x = self.last_layer(x) + return x + + +################################################### +# DiagonalGaussianDistribution +################################################### +class DiagonalGaussianDistribution(object): + def __init__(self, parameters, deterministic=False): + self.parameters = parameters + self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) + self.logvar = torch.clamp(self.logvar, -30.0, 20.0) + self.deterministic = deterministic + self.std = torch.exp(0.5 * self.logvar) + self.var = torch.exp(self.logvar) + if self.deterministic: + self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device) + + def sample(self): + x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device) + return x + + def kl(self, other=None): + if self.deterministic: + return torch.Tensor([0.0]) + else: + if other is None: + return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 2, 3]) + else: + return 0.5 * torch.sum( + torch.pow(self.mean - other.mean, 2) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar, + dim=[1, 2, 3], + ) + + def nll(self, sample, dims=[1, 2, 3]): + if self.deterministic: + return torch.Tensor([0.0]) + logtwopi = np.log(2.0 * np.pi) + return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, dim=dims) + + def mode(self): + return self.mean diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b727dccf0a68d5bcbb9b32e5004d24f7df5599a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .pipeline import MagiPipeline +from .video_generate import SampleTransport, find_dit_model + +__all__ = ["MagiPipeline", "SampleTransport", "find_dit_model"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..360835c62317947057d308e6244554040023f9a1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a92a06e8fb08d70fd01d0dc84a0084164b27e4b4 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/__init__.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a026094c0672c118fa6343bf862288a128b1146f Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83dad5e7b0ee9febdc195faeb570495b4e85aee6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/motioncache.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afdc6a78ba072e0c687dfec6b75257c1a96dad77 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..546cbf64ecd3ad138a2221533abe8b1f21999064 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/pipeline.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7e4f04df60ba30c59d4f6afa1dc04aafa61358 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/prompt_process.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_generate.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_generate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf248a1b4a24e0bb6e5e0753e4f9afb3eb1170a6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_generate.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_process.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_process.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0fd52895275b2a3002b6b372b5a80d01f73bded Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/__pycache__/video_process.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..411dd04e8f699c9feb63ad34893ca5202b645299 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__init__.py @@ -0,0 +1,39 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Cache management module for MAGI inference. + +This module provides optimized implementations for: +- TeaCache: Full output reuse (all chunks together) +- ChunkWiseCache: Per-chunk output reuse (used in FlowCache) +- MotionWiseCache: Motion-aware token-wise reuse (used in MotionCache) +- KVCacheCompressor: Dynamic KV cache compression +""" + +from .base import CacheStrategy, OutputCache, KVCompressor +from .cachereuse import TeaCache, ChunkWiseCache +from .motioncache import MotionWiseCache +from .kv_compressor import KVCacheCompressor +from .utils import generate_dynamic_kv_range + +__all__ = [ + "CacheStrategy", + "OutputCache", + "KVCompressor", + "TeaCache", + "ChunkWiseCache", + "MotionWiseCache", + "generate_dynamic_kv_range", +] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..934e73b7935cfa294faf8bfdb752802fefc43c29 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/base.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..634f2e695fdf22ad865e0066a4dcea431d2a4c36 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/base.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..190a08c1d18ac4223d3c6fb7ed57d576b851380a Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/cachereuse.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20ca7f314cfa47b028bd2392f9207874e7273a16 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/kv_compressor.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5f478d16a18b78573b20fe5f0379f3ef6effca6 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..801ad1b7d6cbec1736d9686321914804c6c5dec1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/motioncache.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..325fba922959175e9e97ff077b1531b9b3f09ad1 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-312.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1e3012bc28336f684f86a06a0d6243e1760d684 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/sparse_utils.cpython-312.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a07bdc01fa7f9cadb533d06b0c92a2e61a3b1ff5 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/__pycache__/utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/base.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f78ea8006b97acd54c5face1f47fb79d560a499d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/base.py @@ -0,0 +1,171 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Base classes for cache management strategies. +""" + +from abc import ABC, abstractmethod +from typing import Dict, Optional, Tuple +import torch + + +class CacheStrategy(ABC): + """ + Abstract base class for cache management strategies. + + All cache implementations should inherit from this class and implement + the required methods. + """ + + def __init__(self, enabled: bool = True): + """ + Initialize the cache strategy. + + Args: + enabled: Whether this cache strategy is enabled + """ + self.enabled = enabled + + @abstractmethod + def reset(self): + """ + Reset the cache state. + + This method should clear all internal state and prepare the cache + for a new inference run. + """ + pass + + def reset_if_enabled(self): + """Reset the cache if it is enabled.""" + if self.enabled: + self.reset() + + +class OutputCache(CacheStrategy): + """ + Abstract base class for output reuse strategies. + + Output caching strategies determine when model outputs can be reused + based on input similarity metrics. + """ + + @abstractmethod + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + **kwargs + ) -> bool: + """ + Determine whether the output for a chunk should be reused. + + Args: + chunk_id: The ID of the current chunk + step: The current denoising step + current_features: Feature tensor for the current input + **kwargs: Additional arguments specific to the implementation + + Returns: + True if the output should be reused, False otherwise + """ + pass + + @abstractmethod + def update_residual( + self, + chunk_id: int, + residual: torch.Tensor + ): + """ + Update the residual for a chunk. + + When outputs are reused, the residual from the previous step is + applied to the current input. + + Args: + chunk_id: The ID of the chunk + residual: The residual tensor to store + """ + pass + + @abstractmethod + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """ + Get the stored residual for a chunk. + + Args: + chunk_id: The ID of the chunk + + Returns: + The residual tensor if available, None otherwise + """ + pass + + +class KVCompressor(CacheStrategy): + """ + Abstract base class for KV cache compression strategies. + + KV cache compression manages memory usage by selectively compressing + KV caches from completed chunks. + """ + + @abstractmethod + def should_compress( + self, + current_chunk_id: int, + cache_used: int, + cache_capacity: int, + **kwargs + ) -> bool: + """ + Determine whether KV cache compression should be triggered. + + Args: + current_chunk_id: The ID of the most recently completed chunk + cache_used: Current KV cache usage in tokens + cache_capacity: Total KV cache capacity in tokens + **kwargs: Additional arguments specific to the implementation + + Returns: + True if compression should be performed, False otherwise + """ + pass + + @abstractmethod + def compress( + self, + inference_params, + chunk_tracker, + clean_chunk_ids: list, + active_chunk_ids: list, + **kwargs + ) -> Dict[int, Tuple[int, int]]: + """ + Compress KV caches for specified chunks. + + Args: + inference_params: Inference parameters containing KV cache + chunk_tracker: Tracker managing chunk ranges + clean_chunk_ids: List of chunk IDs to compress + active_chunk_ids: List of chunk IDs to keep uncompressed + **kwargs: Additional arguments + + Returns: + Dictionary mapping chunk_id to (start, end) ranges after compression + """ + pass diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/cachereuse.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/cachereuse.py new file mode 100644 index 0000000000000000000000000000000000000000..64e20873ab8321e3aa0f5502fcaea33b904cfaf0 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/cachereuse.py @@ -0,0 +1,603 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Cache reuse implementations for output optimization. + +This module provides two caching strategies: +- TeaCache: Full output reuse (all chunks together) +- ChunkWiseCache: Per-chunk output reuse (for FlowCache) +""" + +import json +import os + +from einops import rearrange +import torch +from typing import Dict, List, Optional, Tuple +from .base import OutputCache + + +class TeaCache(OutputCache): + """ + TeaCache implementation with full output reuse. + + This cache computes the relative L1 distance between current and previous + modulated inputs. When the accumulated distance is below threshold, the + output is reused and only the residual is applied. + + All chunks are treated as a single unit for reuse decisions. + + Attributes: + rel_l1_thresh: Threshold for relative L1 distance + warmup_steps: Number of warmup steps before reuse can happen + log: Whether to log reuse decisions + accumulated_rel_l1_distance: Accumulated relative L1 distance + previous_modulated_input: Previous input features + previous_residual: Previous residual for reuse + reuse_times: Number of times output was reused + previous_output: Output from previous stage + cnt: Current step counter + num_steps: Total number of steps + """ + + def __init__( + self, + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + log: bool = False + ): + super().__init__(enabled=True) + self.rel_l1_thresh = rel_l1_thresh + self.warmup_steps = warmup_steps + self.log = log + + # State variables + self.accumulated_rel_l1_distance = 0.0 + self.previous_modulated_input = None + self.previous_residual = None + self.reuse_times = 0 + self.previous_output = None + self.cnt = 0 + self.num_steps = 0 + self.should_calc = True + + def reset(self): + """Reset all cache state.""" + self.accumulated_rel_l1_distance = 0.0 + self.previous_modulated_input = None + self.previous_residual = None + self.reuse_times = 0 + self.previous_output = None + self.cnt = 0 + self.should_calc = True + + def compute_feature_metric( + self, + x: torch.Tensor, + x_embedder, + x_rescale_factor: float, + half_channel_vae: bool, + params_dtype: torch.dtype + ) -> torch.Tensor: + """ + Compute feature metric from input tensor. + + Args: + x: Input tensor [N, C, T, H, W] + x_embedder: Model's x_embedder module + x_rescale_factor: Rescale factor for x + half_channel_vae: Whether VAE uses half channels + params_dtype: Model's parameter dtype for final conversion + + Returns: + Feature tensor of shape [(T*H*W), N, C] + """ + metric_x = x.clone() + metric_x = metric_x * x_rescale_factor + + if half_channel_vae: + assert metric_x.shape[1] == 16, "Expected 16 channels for half-channel VAE" + metric_x = torch.cat([metric_x, metric_x], dim=1) + + metric_x = metric_x.float() + metric_x = x_embedder(metric_x) + metric_x = metric_x.to(params_dtype) + metric_x = rearrange(metric_x, "N C T H W -> (T H W) N C").contiguous() + + return metric_x + + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + denoise_step_per_stage: int, + num_chunks_current: int, + num_chunks_previous: int, + **kwargs + ) -> bool: + """ + Determine whether to reuse output based on feature similarity. + + Args: + chunk_id: Current chunk ID (not used in simple mode) + step: Current denoising step + current_features: Current input features + denoise_step_per_stage: Steps per denoising stage + num_chunks_current: Number of chunks in current stage + num_chunks_previous: Number of chunks in previous stage + + Returns: + True if output should be reused, False if should calculate + """ + # Always calculate first and last steps, and during warmup + if self.cnt == 0 or self.cnt == self.num_steps - 1 or self.cnt < self.warmup_steps: + self.should_calc = True + self.accumulated_rel_l1_distance = 0 + if self.log: + print(f"Calculate output at step {self.cnt}") + return False + + # Compute feature difference + a1 = current_features.clone() + a2 = self.previous_modulated_input.clone() + + # Handle chunk count changes across stages + if self.cnt % denoise_step_per_stage == 0: + dim1 = a1.shape[0] + dim2 = a2.shape[0] + + if dim1 > dim2: + # Next stage has more chunks, truncate to match + a1 = a1[:dim2] + elif dim1 < dim2: + # Next stage has fewer chunks, take tail part + a2 = a2[-dim1:] + + # Compute relative L1 distance + rel_l1 = ((a1 - a2).abs().mean() / a2.abs().mean()).cpu().item() + self.accumulated_rel_l1_distance += rel_l1 + + # Decide whether to reuse + if self.accumulated_rel_l1_distance < self.rel_l1_thresh: + if self.cnt % denoise_step_per_stage == 0 and dim1 > dim2: + # Only calculate new chunk when crossing stage + self.should_calc = True + if self.log: + print(f"Partly reuse output at step {self.cnt}, only calculate new chunk") + return False + else: + # Full reuse + self.reuse_times += 1 + if self.log: + print(f"Reuse output at step {self.cnt}") + self.should_calc = False + return True + else: + # Threshold exceeded, recalculate + if self.log: + print(f"Calculate output at step {self.cnt}") + self.should_calc = True + self.accumulated_rel_l1_distance = 0 + return False + + def update_residual(self, chunk_id: int, residual: torch.Tensor): + """ + Update the residual for reuse. + + Args: + chunk_id: Chunk ID (not used in simple mode, residual applies to all) + residual: Residual tensor to store + """ + self.previous_residual = residual + + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """ + Get the stored residual. + + Args: + chunk_id: Chunk ID (not used in simple mode) + + Returns: + The residual tensor or None + """ + return self.previous_residual + + def increment_step(self): + """Increment step counter and print statistics if done.""" + self.cnt += 1 + if self.cnt == self.num_steps: + print(f"Reuse output account for {self.reuse_times} / {self.num_steps} steps, " + f"ratio: {self.reuse_times / self.num_steps:.2%}") + self.cnt = 0 + + def store_previous_features(self, features: torch.Tensor): + """Store current features as previous for next step.""" + self.previous_modulated_input = features.clone() + + def get_previous_features(self) -> Optional[torch.Tensor]: + """Get the stored previous features.""" + return self.previous_modulated_input + + def prepare_for_next_stage(self): + """Store output for use in next stage.""" + pass # Handled in integrate_velocity + + +class ChunkWiseCache(OutputCache): + """ + Chunk-wise output cache implementation for FlowCache. + + This cache tracks reuse decisions separately for each chunk, allowing + finer-grained control over which chunks to skip. + + Attributes: + rel_l1_thresh: Threshold for relative L1 distance + warmup_steps: Number of warmup steps per chunk before reuse can happen + discard_nearly_clean_chunk: Whether to skip nearly-clean chunk + log: Whether to log reuse decisions + chunk_accumulated_rel_l1: Per-chunk accumulated L1 distance + chunk_reuse_flags: Per-chunk reuse flags for current step + prev_metric_chunks: Previous features per chunk + previous_residual: Per-chunk residuals + """ + + def __init__( + self, + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + metric_stats_path: Optional[str] = None, + ): + super().__init__(enabled=True) + self.rel_l1_thresh = rel_l1_thresh + self.warmup_steps = warmup_steps + self.discard_nearly_clean_chunk = discard_nearly_clean_chunk + self.log = log + self.metric_stats_path = metric_stats_path + self.metric_records = [] + self.execution_records = [] + self.chunk_execution_counts: Dict[int, Dict[str, int]] = {} + + # State variables + self.chunk_accumulated_rel_l1: Dict[int, float] = {} + self.chunk_reuse_flags: Dict[int, bool] = {} + self.prev_metric_chunks: Dict[int, torch.Tensor] = {} + self.previous_residual: Dict[int, torch.Tensor] = {} + + self.cnt = 0 + self.num_steps = 0 + + def reset(self): + """Reset all cache state.""" + self.chunk_accumulated_rel_l1.clear() + self.chunk_reuse_flags.clear() + self.prev_metric_chunks.clear() + self.previous_residual.clear() + self.metric_records.clear() + self.execution_records.clear() + self.chunk_execution_counts.clear() + self.cnt = 0 + + def initialize_chunk_state(self, chunk_num: int): + """Initialize state for all chunks.""" + if len(self.chunk_accumulated_rel_l1) != chunk_num: + self.chunk_accumulated_rel_l1 = {i: 0.0 for i in range(chunk_num)} + self.previous_residual = {i: None for i in range(chunk_num)} + + # Reset reuse flags for each step + self.chunk_reuse_flags = {i: False for i in range(chunk_num)} + self.chunk_sparse_flags = {} + + def compute_feature_metric( + self, + x: torch.Tensor, + x_embedder, + x_rescale_factor: float, + half_channel_vae: bool, + chunk_token_nums: int, + params_dtype: torch.dtype, + offset: int = 0, + fwd_extra_1st_chunk: bool = False, + distill_nearly_clean_chunk: bool = False + ) -> Tuple[Dict[int, torch.Tensor], int]: + """ + Compute feature metric for each chunk. + + Following source code logic: + 1. Compute metric_x from input x + 2. Handle fwd_extra_1st_chunk: slice off first chunk if needed + 3. Handle distill_nearly_clean_chunk: slice off last chunk if needed + 4. Split into chunks + + Args: + x: Input tensor [N, C, T, H, W] + x_embedder: Model's x_embedder module + x_rescale_factor: Rescale factor for x + half_channel_vae: Whether VAE uses half channels + chunk_token_nums: Number of tokens per chunk + params_dtype: Model's parameter dtype for final conversion + offset: Offset for chunk_id (to match x_chunks indexing) + fwd_extra_1st_chunk: Whether to slice off first chunk (always False) + distill_nearly_clean_chunk: Whether to slice off last chunk + + Returns: + Tuple of (metric_chunks dict, num_chunks_for_x) + """ + from einops import rearrange + + # 1. Compute metric_x from input x + metric_x = x.clone() + metric_x = metric_x * x_rescale_factor + + if half_channel_vae: + assert metric_x.shape[1] == 16 + metric_x = torch.cat([metric_x, metric_x], dim=1) + + metric_x = metric_x.float() + metric_x = x_embedder(metric_x) + metric_x = metric_x.to(params_dtype) + metric_x = rearrange(metric_x, "N C T H W -> (T H W) N C").contiguous() + + # 2. Handle fwd_extra_1st_chunk: slice off first chunk if needed + # Note: fwd_extra_1st_chunk is always False in current implementation + if fwd_extra_1st_chunk: + metric_x = metric_x[chunk_token_nums:, :, :] + + # 3. Handle distill_nearly_clean_chunk: slice off last chunk if needed + if distill_nearly_clean_chunk: + metric_x = metric_x[:-chunk_token_nums, :, :] + + # 4. Split into chunks + assert metric_x.shape[0] % chunk_token_nums == 0 + num_chunks = metric_x.shape[0] // chunk_token_nums + + metric_chunks = {} + for i in range(num_chunks): + start = i * chunk_token_nums + end = start + chunk_token_nums + metric_chunks[offset + i] = metric_x[start:end] + + # Return num_chunks for x_chunks iteration (matching source code) + return metric_chunks, num_chunks + + def should_reuse( + self, + chunk_id: int, + step: int, + current_features: torch.Tensor, + chunk_denoise_count: Dict[int, int], + current_num_chunks: int, + previous_num_chunks: int, + **kwargs + ) -> bool: + """ + Determine whether to reuse output for a specific chunk. + + Args: + chunk_id: The chunk ID to check + step: Current denoising step + current_features: Current features for all chunks + chunk_denoise_count: Denoising steps completed per chunk + current_num_chunks: Number of chunks in current stage + previous_num_chunks: Number of chunks in previous stage + + Returns: + True if output should be reused, False otherwise + """ + # First and last steps always calculate + if self.cnt == 0 or self.cnt == self.num_steps - 1: + self.record_metric_decision(chunk_id, step, None, None, False, "first_or_last_step", **kwargs) + return False + + # Check if chunk exists in both current and previous + if chunk_id not in current_features or chunk_id not in self.prev_metric_chunks: + self.record_metric_decision(chunk_id, step, None, None, False, "missing_previous_features", **kwargs) + return False + + # Apply warmup: skip reuse during warmup period + if self._should_skip_reuse(chunk_id, chunk_denoise_count): + self.chunk_accumulated_rel_l1[chunk_id] = 0.0 + self.record_metric_decision(chunk_id, step, None, 0.0, False, "warmup", **kwargs) + return False + + # Compute relative L1 distance + curr_feat = current_features[chunk_id] + prev_feat = self.prev_metric_chunks[chunk_id] + + diff = (curr_feat - prev_feat).abs().mean() + denom = prev_feat.abs().mean() + 1e-8 + rel_l1 = (diff / denom).item() + delta_l1_norm = (curr_feat - prev_feat).abs().sum().item() + prev_feat_l1_norm = prev_feat.abs().sum().item() + rel_l1_ratio = delta_l1_norm / max(prev_feat_l1_norm, 1e-8) + + # Accumulate and check threshold + accumulated = self.chunk_accumulated_rel_l1[chunk_id] + rel_l1 + + if accumulated < self.rel_l1_thresh: + self.chunk_accumulated_rel_l1[chunk_id] = accumulated + self.chunk_reuse_flags[chunk_id] = True + self.record_metric_decision( + chunk_id, step, rel_l1, accumulated, True, "below_threshold", + delta_l1_norm=delta_l1_norm, + prev_feat_l1_norm=prev_feat_l1_norm, + rel_l1_ratio=rel_l1_ratio, + **kwargs, + ) + return True + else: + self.chunk_accumulated_rel_l1[chunk_id] = 0.0 + self.chunk_reuse_flags[chunk_id] = False + self.record_metric_decision( + chunk_id, step, rel_l1, accumulated, False, "threshold_exceeded", + delta_l1_norm=delta_l1_norm, + prev_feat_l1_norm=prev_feat_l1_norm, + rel_l1_ratio=rel_l1_ratio, + **kwargs, + ) + return False + + def record_metric_decision( + self, + chunk_id: int, + step: int, + rel_l1: Optional[float], + accumulated_rel_l1: Optional[float], + reused: bool, + decision_reason: str, + **kwargs + ): + if not self.metric_stats_path: + return + + chunk_offset = kwargs.get("chunk_offset", 0) + record = { + "infer_idx": kwargs.get("infer_idx"), + "cur_denoise_step": kwargs.get("cur_denoise_step", step), + "denoise_stage": kwargs.get("denoise_stage"), + "denoise_idx": kwargs.get("denoise_idx"), + "chunk_idx": chunk_id, + "generated_chunk_idx": chunk_id - chunk_offset, + "chunk_denoise_count": kwargs.get("chunk_denoise_count_value"), + "flowcache_rel_l1": rel_l1, + "flowcache_rel_l1_ratio": kwargs.get("rel_l1_ratio"), + "flowcache_delta_l1_norm": kwargs.get("delta_l1_norm"), + "flowcache_prev_feat_l1_norm": kwargs.get("prev_feat_l1_norm"), + "flowcache_accumulated_rel_l1": accumulated_rel_l1, + "rel_l1_thresh": self.rel_l1_thresh, + "reused": bool(reused), + "decision_reason": decision_reason, + } + self.metric_records.append(record) + + def record_actual_execution( + self, + chunk_id: int, + reused: bool, + **kwargs + ): + stats = self.chunk_execution_counts.setdefault( + chunk_id, + {"reuse_steps": 0, "compute_steps": 0, "total_steps": 0}, + ) + if reused: + stats["reuse_steps"] += 1 + else: + stats["compute_steps"] += 1 + stats["total_steps"] += 1 + + if not self.metric_stats_path: + return + + chunk_offset = kwargs.get("chunk_offset", 0) + self.execution_records.append({ + "infer_idx": kwargs.get("infer_idx"), + "cur_denoise_step": kwargs.get("cur_denoise_step"), + "denoise_stage": kwargs.get("denoise_stage"), + "denoise_idx": kwargs.get("denoise_idx"), + "chunk_idx": chunk_id, + "generated_chunk_idx": chunk_id - chunk_offset, + "reused": bool(reused), + "execution": "reuse" if reused else "compute", + }) + + def get_execution_summary(self): + summary = {} + for chunk_id, stats in sorted(self.chunk_execution_counts.items()): + total_steps = stats["total_steps"] + reuse_steps = stats["reuse_steps"] + compute_steps = stats["compute_steps"] + summary[str(chunk_id)] = { + "chunk_idx": chunk_id, + "reuse_steps": reuse_steps, + "compute_steps": compute_steps, + "total_steps": total_steps, + "reuse_rate": reuse_steps / total_steps if total_steps else 0.0, + "compute_rate": compute_steps / total_steps if total_steps else 0.0, + } + return summary + + def _should_skip_reuse( + self, + chunk_id: int, + chunk_denoise_count: Dict[int, int] + ) -> bool: + """ + Check if reuse should be skipped for this chunk. + + During warmup period, chunks are always recalculated. + + Args: + chunk_id: Chunk to check + chunk_denoise_count: Steps completed per chunk + + Returns: + True if should skip reuse (i.e., in warmup period) + """ + return chunk_denoise_count[chunk_id] < self.warmup_steps + + def update_residual(self, chunk_id: int, residual: torch.Tensor): + """Update the residual for a specific chunk.""" + self.previous_residual[chunk_id] = residual + + def get_residual(self, chunk_id: int) -> Optional[torch.Tensor]: + """Get the stored residual for a chunk.""" + return self.previous_residual.get(chunk_id) + + def store_previous_features(self, metric_chunks: Dict[int, torch.Tensor]): + """Store current features as previous for next step.""" + self.prev_metric_chunks = { + i: f.clone().detach() for i, f in metric_chunks.items() + } + + def increment_step(self): + """Increment step counter.""" + self.cnt += 1 + if self.cnt == self.num_steps: + self.cnt = 0 + + def set_total_steps(self, num_steps: int): + """Set total number of steps.""" + self.num_steps = num_steps + + def save_metric_stats(self): + if not self.metric_stats_path: + return + save_dir = os.path.dirname(self.metric_stats_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "FlowCache original per-chunk reuse metric. flowcache_rel_l1 = " + "mean(abs(x_embedder(X_t_current) - x_embedder(X_t_previous))) / " + "(mean(abs(x_embedder(X_t_previous))) + 1e-8). " + "flowcache_rel_l1_ratio = sum(abs(delta)) / sum(abs(previous_feature)); " + "flowcache_accumulated_rel_l1 is the accumulated value compared with rel_l1_thresh. " + "chunk_execution_summary is counted at the actual integrate step and includes every " + "per-chunk reuse or compute execution." + ), + "chunk_execution_summary": self.get_execution_summary(), + "execution_records": self.execution_records, + "records": self.metric_records, + } + if self.metric_stats_path.endswith((".pt", ".pth")): + torch.save(payload, self.metric_stats_path) + else: + with open(self.metric_stats_path, "w") as f: + json.dump(payload, f, indent=2) + print(f"Saved FlowCache metric stats to {self.metric_stats_path}") diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/kv_compressor.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/kv_compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd43d2b864f1f1f478542525bd2014c8c572772 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/kv_compressor.py @@ -0,0 +1,390 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +KV Cache Compression module. +""" + +import torch +from typing import Dict, List, Optional, Tuple, Any +from .base import KVCompressor +from .utils import ( + identify_compressible_chunks, + check_compress_condition, + get_latent_spatial_dims, +) + + +class KVCacheCompressor(KVCompressor): + """ + Manages KV cache compression for memory-efficient inference. + + This compressor identifies clean chunks (completed denoising) and compresses + their KV caches using the configured compression strategy (e.g., R1KV). + + Attributes: + total_cache_len: Total cache capacity in tokens + tokens_per_chunk: Number of tokens per chunk + budget_cache_len: Target cache size after compression + compression_config: Configuration for compression strategy + kv_compressed: Whether compression has been performed + chunk_query_states: Query states for each layer (used for compression) + """ + + def __init__( + self, + total_cache_len: int, + tokens_per_chunk: int, + budget_chunk_nums: int, + window_size: int = 4, + compression_config: Optional[Dict[str, Any]] = None + ): + """ + Initialize the KV cache compressor. + + Args: + total_cache_len: Total cache capacity in tokens + tokens_per_chunk: Number of tokens per chunk + budget_chunk_nums: Target number of chunks after compression + window_size: Window size for denoising stages + compression_config: Configuration for compression strategy + """ + super().__init__(enabled=True) + self.total_cache_len = total_cache_len + self.tokens_per_chunk = tokens_per_chunk + self.budget_cache_len = (budget_chunk_nums - 1) * tokens_per_chunk + self.window_size = window_size + self.compression_config = compression_config or {} + + self.kv_compressed = False + self.chunk_query_states: Dict[int, torch.Tensor] = {} + + def reset(self): + """Reset compression state.""" + self.kv_compressed = False + self.chunk_query_states.clear() + + def should_compress( + self, + tracker, + chunk_num: int, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + **kwargs + ) -> bool: + """ + Check if compression should be triggered. + + Args: + tracker: ChunkKVRangeTracker instance + chunk_num: Total number of chunks + chunk_start: Current chunk being processed + transport_input: Transport input + chunk_denoise_count: Denoising steps per chunk + + Returns: + True if compression should be performed + """ + return check_compress_condition( + tracker=tracker, + total_cache_len=self.total_cache_len, + chunk_num=chunk_num, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=chunk_denoise_count, + window_size=self.window_size + ) + + def compress( + self, + model, + inference_params, + tracker, + transport_input, + chunk_start: int, + chunk_denoise_count: Dict[int, int], + query_states_dict: Optional[Dict[int, torch.Tensor]] = None, + **kwargs + ) -> Dict[int, Tuple[int, int]]: + """ + Perform KV cache compression. + + Args: + model: DiT model with videodit_blocks + inference_params: Inference parameters containing KV cache + tracker: ChunkKVRangeTracker instance + transport_input: Transport input + chunk_start: Current chunk being processed + chunk_denoise_count: Denoising steps per chunk + + Returns: + Dictionary mapping chunk_id to (start, end) ranges after compression + """ + # Identify chunks to compress + chunk_offset = self._get_chunk_offset(transport_input) + clean_chunk_ids, active_chunk_ids = identify_compressible_chunks( + tracker=tracker, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=chunk_denoise_count, + chunk_offset=chunk_offset + ) + + if len(clean_chunk_ids) < 2: + # Need at least 2 chunks to compress + return {} + + # Compress for each layer + final_chunk_ids = [] + final_lengths = [] + + for layer in model.videodit_blocks.layers: + if not hasattr(layer.self_attention, 'kv_cluster'): + continue + + # import pdb; pdb.set_trace() + layer_result = self._compress_layer( + layer=layer, + inference_params=inference_params, + tracker=tracker, + clean_chunk_ids=clean_chunk_ids, + active_chunk_ids=active_chunk_ids, + transport_input=transport_input, + query_states_dict=query_states_dict + ) + + # Store result from first layer for chunk metadata + if layer.self_attention.layer_number == 0: + final_chunk_ids = layer_result['chunk_ids'] + final_lengths = layer_result['lengths'] + + # Update tracker ranges (shared across layers) + new_ranges = self._compute_new_ranges( + final_chunk_ids, final_lengths + ) + tracker.update_ranges_after_compression(new_ranges) + + # Mark as compressed + self.kv_compressed = True + + return new_ranges + + def _compress_layer( + self, + layer, + inference_params, + tracker, + clean_chunk_ids: List[int], + active_chunk_ids: List[int], + transport_input, + query_states_dict: Optional[Dict[int, torch.Tensor]] = None + ) -> Dict[str, Any]: + """ + Compress KV cache for a single layer. + + Args: + layer: Transformer layer + inference_params: Inference parameters + tracker: ChunkKVRangeTracker + clean_chunk_ids: Chunks to compress + active_chunk_ids: Chunks to keep uncompressed + transport_input: Transport input + query_states_dict: Query states for each layer (from transport) + + Returns: + Dictionary with compression results + """ + kv_cluster = layer.self_attention.kv_cluster + layer_num = layer.self_attention.layer_number + + # Extract KV caches for clean chunks + clean_kv_list = [] + clean_lengths = [] + for cid in clean_chunk_ids: + s, e = tracker.get_range(cid) + chunk_kv = inference_params.key_value_memory_dict[layer_num][s:e, ...] + clean_kv_list.append(chunk_kv) + clean_lengths.append(e - s) + + # Concatenate and split into key and value + clean_kv = torch.cat(clean_kv_list, dim=0) + key_clean, value_clean = torch.chunk(clean_kv, 2, dim=-1) + + # Extract KV caches for active chunks + active_kv_list = [] + active_lengths = [] + for cid in active_chunk_ids: + s, e = tracker.get_range(cid) + chunk_kv = inference_params.key_value_memory_dict[layer_num][s:e, ...] + active_kv_list.append(chunk_kv) + active_lengths.append(e - s) + + # Get query states for compression + query_states = query_states_dict.get(layer_num) if query_states_dict else None + if query_states is None: + raise RuntimeError(f"Query states not available for layer {layer_num}") + + # Set compression budget + total_clean_tokens = sum(clean_lengths) + kv_cluster.budget = max( + total_clean_tokens - self.tokens_per_chunk, + self.tokens_per_chunk + ) + + # Get latent dimensions + H, W = get_latent_spatial_dims(transport_input, layer.model_config) + T = self.tokens_per_chunk // (H * W) + + # Perform compression + key_compressed, value_compressed, indices = kv_cluster.update_kv( + key_states=key_clean, + query_states=query_states, + value_states=value_clean, + clean_chunk_tokens=total_clean_tokens, + latent_size_t=T, + latent_size_h=H, + latent_size_w=W, + ) + + # Reassemble KV cache + final_kv_parts = [] + final_chunk_ids = [] + final_lengths = [] + + # Add compressed part + compressed_kv = torch.cat([key_compressed, value_compressed], dim=-1) + final_kv_parts.append(compressed_kv) + + # Compute compressed lengths per chunk + all_lengths_after_compress = self._compute_compressed_lengths( + indices, clean_chunk_ids, clean_lengths, total_clean_tokens + ) + final_chunk_ids.extend(clean_chunk_ids) + final_lengths.extend(all_lengths_after_compress) + + # Add active (uncompressed) chunks + for i, chunk_kv in enumerate(active_kv_list): + final_kv_parts.append(chunk_kv) + final_chunk_ids.append(active_chunk_ids[i]) + final_lengths.append(active_lengths[i]) + + # Concatenate and update KV cache + final_kv = torch.cat(final_kv_parts, dim=0) + total_kv_len = final_kv.size(0) + + inference_params.key_value_memory_dict[layer_num][:total_kv_len, ...] = final_kv + inference_params.key_value_memory_dict[layer_num][total_kv_len:, ...] = 0.0 + + return { + 'chunk_ids': final_chunk_ids, + 'lengths': final_lengths + } + + def _compute_compressed_lengths( + self, + indices: torch.Tensor, + clean_chunk_ids: List[int], + clean_lengths: List[int], + total_clean_tokens: int + ) -> List[int]: + """ + Compute the compressed length for each chunk. + + Args: + indices: Selected token indices [num_to_keep, num_kv_heads, head_dim] + clean_chunk_ids: IDs of chunks that were compressed + clean_lengths: Original lengths of compressed chunks + total_clean_tokens: Total tokens before compression + + Returns: + List of compressed lengths per chunk + """ + # TODO: This has an issue - different heads keep different ranges + # But it's fine since we attend to all previous chunks' KV cache + indices_1d = indices[:, 0, 0] # shape: (num_to_keep,) + + all_lengths_after_compress = [] + start_idx = 0 + + for chunk_len in clean_lengths: + end_idx = start_idx + chunk_len + # Count selected tokens in this chunk's range + mask = (indices_1d >= start_idx) & (indices_1d < min(end_idx, total_clean_tokens)) + kept_in_chunk = mask.sum().item() + all_lengths_after_compress.append(kept_in_chunk) + start_idx = end_idx + + return all_lengths_after_compress + + def _compute_new_ranges( + self, + chunk_ids: List[int], + lengths: List[int] + ) -> Dict[int, Tuple[int, int]]: + """ + Compute new chunk ranges after compression. + + Args: + chunk_ids: List of chunk IDs in order + lengths: Compressed lengths for each chunk + + Returns: + Dictionary mapping chunk_id to (start, end) range + """ + new_ranges = {} + current_start = 0 + + for cid, length in zip(chunk_ids, lengths): + new_end = current_start + length + new_ranges[cid] = (current_start, new_end) + current_start = new_end + + return new_ranges + + def _get_chunk_offset(self, transport_input) -> int: + """ + Get the number of prefix video chunks. + + Args: + transport_input: Transport input + + Returns: + Number of prefix video chunks + """ + if transport_input.prefix_video is not None: + return transport_input.prefix_video.size(2) // transport_input.chunk_width + return 0 + + def store_query_states(self, layer_num: int, query_states: torch.Tensor): + """ + Store query states for later compression. + + Args: + layer_num: Layer number + query_states: Query tensor to store + """ + self.chunk_query_states[layer_num] = query_states + + def get_query_states(self, layer_num: int) -> Optional[torch.Tensor]: + """ + Get stored query states for a layer. + + Args: + layer_num: Layer number + + Returns: + Query tensor or None if not available + """ + return self.chunk_query_states.get(layer_num) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/motioncache.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/motioncache.py new file mode 100644 index 0000000000000000000000000000000000000000..1492eaad4d11479232ebccf108a3591d1ce12279 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/motioncache.py @@ -0,0 +1,308 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +MotionCache: motion-aware token-wise cache reuse for autoregressive video generation. + +Implements the coarse-to-fine schedule from Xu et al. (2026): +- Phase 1 (first K steps after warmup): chunk-wise binary reuse (FlowCache-style) +- Phase 2: motion-weighted per-token accumulation and selective reuse +""" + +import json +import os +from typing import Dict, Optional, Tuple + +import torch +from einops import rearrange + +from .cachereuse import ChunkWiseCache + + +class MotionWiseCache(ChunkWiseCache): + """ + Motion-aware cache extending chunk-wise FlowCache with token-level reuse. + + Hyperparameters (paper Appendix C for MAGI-1): + alpha: soft-mapping floor for static tokens (default 0.5) + phase1_steps (K): chunk-wise phase duration before token-wise mode (default 9) + rel_l1_thresh (tau): accumulator threshold for token activation + warmup_steps (m): global steps with reuse disabled (default 5) + """ + + def __init__( + self, + rel_l1_thresh: float = 0.015, + warmup_steps: int = 5, + phase1_steps: int = 9, + alpha: float = 0.5, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + metric_stats_path: Optional[str] = None, + eps: float = 1e-8, + ): + super().__init__( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + discard_nearly_clean_chunk=discard_nearly_clean_chunk, + log=log, + metric_stats_path=metric_stats_path, + ) + self.phase1_steps = phase1_steps + self.alpha = alpha + self.eps = eps + + self.token_accumulator: Dict[int, torch.Tensor] = {} + self.token_active_mask: Dict[int, torch.Tensor] = {} + self.token_motion_weights: Dict[int, torch.Tensor] = {} + self.prev_latent_chunks: Dict[int, torch.Tensor] = {} + self.prev_chunk_last_frame: Dict[int, torch.Tensor] = {} + self.previous_velocity: Dict[int, torch.Tensor] = {} + self.chunk_sparse_flags: Dict[int, bool] = {} + + def reset(self): + super().reset() + self.token_accumulator.clear() + self.token_active_mask.clear() + self.token_motion_weights.clear() + self.prev_latent_chunks.clear() + self.prev_chunk_last_frame.clear() + self.previous_velocity.clear() + self.chunk_sparse_flags.clear() + + @staticmethod + def expand_token_mask_to_output( + token_mask: torch.Tensor, + output: torch.Tensor, + ) -> torch.Tensor: + """Expand [N, T, H, W] latent mask to match velocity/output [N, C, T, H, W].""" + return token_mask.unsqueeze(1).expand_as(output).to(dtype=output.dtype) + + def in_phase1(self, chunk_id: int, chunk_denoise_count: Dict[int, int]) -> bool: + """Return True while chunk i is still in coarse chunk-wise phase (denoise step < K).""" + return chunk_denoise_count.get(chunk_id, 0) < self.phase1_steps + + def compute_motion_weights( + self, + x_chunk: torch.Tensor, + chunk_id: int, + chunk_offset: int, + ) -> torch.Tensor: + """ + Compute motion-aware importance weights W in [alpha, 1] per latent frame. + + Args: + x_chunk: Latent tensor [N, C, T, H, W] at current denoising step + chunk_id: Global chunk index + chunk_offset: Index of first generated chunk + + Returns: + Weights tensor [N, T, H, W] + """ + _, _, num_frames, _, _ = x_chunk.shape + device = x_chunk.device + dtype = x_chunk.dtype + importance = torch.zeros( + x_chunk.size(0), num_frames, x_chunk.size(3), x_chunk.size(4), + device=device, dtype=dtype, + ) + + for frame_idx in range(num_frames): + if frame_idx > 0: + diff = (x_chunk[:, :, frame_idx] - x_chunk[:, :, frame_idx - 1]).abs().sum(dim=1) + elif chunk_id > chunk_offset: + prev_frame = self.prev_chunk_last_frame.get(chunk_id - 1) + if prev_frame is not None: + diff = (x_chunk[:, :, 0] - prev_frame).abs().sum(dim=1) + else: + diff = torch.zeros( + x_chunk.size(0), x_chunk.size(3), x_chunk.size(4), + device=device, dtype=dtype, + ) + else: + continue + importance[:, frame_idx] = diff + + if chunk_id == chunk_offset and num_frames > 1: + importance[:, 0] = importance[:, 1] + + weights = torch.zeros_like(importance) + for frame_idx in range(num_frames): + frame_importance = importance[:, frame_idx] + min_val = frame_importance.amin(dim=(1, 2), keepdim=True) + max_val = frame_importance.amax(dim=(1, 2), keepdim=True) + normalized = (frame_importance - min_val) / (max_val - min_val + self.eps) + weights[:, frame_idx] = self.alpha + (1.0 - self.alpha) * normalized + + return weights + + def compute_chunk_delta_l1( + self, + current_features: torch.Tensor, + prev_features: torch.Tensor, + ) -> float: + """Relative L1 distance between consecutive embedded features (Eq. 11).""" + diff = (current_features - prev_features).abs().mean() + denom = prev_features.abs().mean() + self.eps + return (diff / denom).item() + + def update_token_policy( + self, + chunk_id: int, + x_chunk: torch.Tensor, + current_features: torch.Tensor, + chunk_offset: int, + chunk_denoise_count: Optional[Dict[int, int]] = None, + ) -> torch.Tensor: + """ + Phase-2 token policy: update accumulators and return active mask. + + Returns: + Boolean mask [N, T, H, W], True = compute, False = reuse cache + """ + if ( + chunk_denoise_count is not None + and chunk_denoise_count.get(chunk_id, 0) == self.phase1_steps + ): + mask = torch.ones( + x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4), + device=x_chunk.device, dtype=torch.bool, + ) + self.token_active_mask[chunk_id] = mask + self.token_accumulator[chunk_id] = torch.zeros( + x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4), + device=x_chunk.device, + dtype=x_chunk.dtype, + ) + return mask + + prev_features = self.prev_metric_chunks.get(chunk_id) + if prev_features is None: + mask = torch.ones( + x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4), + device=x_chunk.device, dtype=torch.bool, + ) + self.token_active_mask[chunk_id] = mask + return mask + + delta_chunk = self.compute_chunk_delta_l1(current_features, prev_features) + weights = self.compute_motion_weights(x_chunk, chunk_id, chunk_offset) + self.token_motion_weights[chunk_id] = weights + + if chunk_id not in self.token_accumulator: + self.token_accumulator[chunk_id] = torch.zeros_like(weights) + + self.token_accumulator[chunk_id] = ( + self.token_accumulator[chunk_id] + weights * delta_chunk + ) + mask = self.token_accumulator[chunk_id] > self.rel_l1_thresh + self.token_active_mask[chunk_id] = mask + return mask + + def reset_token_accumulator(self, chunk_id: int, mask: torch.Tensor): + """Reset accumulator for tokens selected for computation.""" + if chunk_id in self.token_accumulator: + self.token_accumulator[chunk_id] = torch.where( + mask, torch.zeros_like(self.token_accumulator[chunk_id]), + self.token_accumulator[chunk_id], + ) + + def should_skip_chunk_forward( + self, + chunk_id: int, + chunk_denoise_count: Dict[int, int], + ) -> bool: + """Return True if the entire chunk can skip the DiT forward pass.""" + if self.in_phase1(chunk_id, chunk_denoise_count): + return self.chunk_reuse_flags.get(chunk_id, False) + + mask = self.token_active_mask.get(chunk_id) + if mask is None: + return False + return not mask.any() + + def store_latent_chunk(self, chunk_id: int, x_chunk: torch.Tensor): + """Store latent for cross-chunk motion reference.""" + self.prev_latent_chunks[chunk_id] = x_chunk.detach().clone() + self.prev_chunk_last_frame[chunk_id] = x_chunk[:, :, -1].detach().clone() + + def get_token_mask( + self, + chunk_id: int, + chunk_denoise_count: Dict[int, int], + ) -> Optional[torch.Tensor]: + if self.in_phase1(chunk_id, chunk_denoise_count): + return None + return self.token_active_mask.get(chunk_id) + + def record_motion_decision( + self, + chunk_id: int, + reused: bool, + active_ratio: Optional[float] = None, + **kwargs, + ): + if not self.metric_stats_path: + return + record = { + "infer_idx": kwargs.get("infer_idx"), + "cur_denoise_step": kwargs.get("cur_denoise_step"), + "denoise_stage": kwargs.get("denoise_stage"), + "denoise_idx": kwargs.get("denoise_idx"), + "chunk_idx": chunk_id, + "generated_chunk_idx": chunk_id - kwargs.get("chunk_offset", 0), + "chunk_denoise_count": kwargs.get("chunk_denoise_count_value"), + "phase": ( + "phase1_chunk" + if self.in_phase1(chunk_id, kwargs.get("chunk_denoise_count", {})) + else "phase2_token" + ), + "reused": bool(reused), + "execution": "reuse" if reused else "compute", + "active_token_ratio": active_ratio, + "phase1_steps": self.phase1_steps, + "alpha": self.alpha, + "rel_l1_thresh": self.rel_l1_thresh, + } + self.execution_records.append(record) + + def save_metric_stats(self): + if not self.metric_stats_path: + return + save_dir = os.path.dirname(self.metric_stats_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "MotionCache metric stats. Phase 1 uses chunk-wise FlowCache policy for " + f"the first {self.phase1_steps} denoise steps per chunk; Phase 2 uses motion-weighted " + "token accumulation with alpha floor and rel_l1_thresh." + ), + "hyperparameters": { + "alpha": self.alpha, + "phase1_steps": self.phase1_steps, + "warmup_steps": self.warmup_steps, + "rel_l1_thresh": self.rel_l1_thresh, + }, + "chunk_execution_summary": self.get_execution_summary(), + "execution_records": self.execution_records, + "records": self.metric_records, + } + if self.metric_stats_path.endswith((".pt", ".pth")): + torch.save(payload, self.metric_stats_path) + else: + with open(self.metric_stats_path, "w") as f: + json.dump(payload, f, indent=2) + print(f"Saved MotionCache metric stats to {self.metric_stats_path}") diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/sparse_utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/sparse_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bd74bade11aff1261e88c12a48ac2a0d772620c3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/sparse_utils.py @@ -0,0 +1,110 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Sparse token gather/scatter utilities for MotionCache Phase 2.""" + +from dataclasses import replace +from typing import Optional, Tuple + +import torch +import torch.nn.functional as F + +from inference.common import ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams + + +def latent_mask_to_patch_mask( + token_mask: torch.Tensor, + patch_size: int = 2, +) -> torch.Tensor: + """ + Downsample latent-space mask [N, T, H, W] to patch token mask [N, T, Hp, Wp]. + + A patch is active if any latent pixel inside the patch is active. + """ + n, t, h, w = token_mask.shape + flat = token_mask.reshape(n * t, 1, h, w).float() + pooled = F.max_pool2d(flat, kernel_size=patch_size, stride=patch_size) + hp, wp = pooled.shape[-2], pooled.shape[-1] + return pooled.reshape(n, t, hp, wp).bool() + + +def patch_mask_to_flat_indices( + patch_mask: torch.Tensor, +) -> torch.Tensor: + """Return flat token indices [num_active] in (T*Hp*Wp) row-major order.""" + flat = patch_mask.reshape(-1) + return torch.nonzero(flat, as_tuple=False).squeeze(-1) + + +def build_sparse_meta_args( + meta_args: ModelMetaArgs, + active_indices: torch.Tensor, + total_tokens: int, +) -> ModelMetaArgs: + """Rebuild attention params for sparse query length (active tokens only).""" + num_active = int(active_indices.numel()) + device = active_indices.device + + q_range = torch.tensor([[0, num_active]], dtype=torch.int32, device=device) + core_attn_params = PackedCoreAttnParams( + q_range=q_range, + k_range=meta_args.core_attn_params.k_range, + np_q_range=q_range.cpu().numpy(), + np_k_range=meta_args.core_attn_params.np_k_range, + max_seqlen_q=num_active, + max_seqlen_k=meta_args.core_attn_params.max_seqlen_k, + ) + + cu_seqlens_q = torch.tensor([0, num_active], dtype=torch.int32, device=device) + cross_attn_params = PackedCrossAttnParams( + q_ranges=torch.tensor([[0, num_active]], dtype=torch.int32, device=device), + kv_ranges=meta_args.cross_attn_params.kv_ranges, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=meta_args.cross_attn_params.cu_seqlens_kv, + max_seqlen_q=num_active, + max_seqlen_kv=meta_args.cross_attn_params.max_seqlen_kv, + ) + + return replace( + meta_args, + core_attn_params=core_attn_params, + cross_attn_params=cross_attn_params, + sparse_active_indices=active_indices, + sparse_total_tokens=total_tokens, + ) + + +def sparse_gather_sequence( + hidden_states: torch.Tensor, + condition_map: torch.Tensor, + rotary_pos_emb: torch.Tensor, + active_indices: torch.Tensor, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Gather [S,...] tensors along the sequence dimension.""" + return ( + hidden_states.index_select(0, active_indices), + condition_map.index_select(0, active_indices), + rotary_pos_emb.index_select(0, active_indices), + ) + + +def sparse_scatter_sequence( + full_hidden: torch.Tensor, + active_hidden: torch.Tensor, + active_indices: torch.Tensor, +) -> torch.Tensor: + """Scatter active transformer outputs back into the full [S,N,D] buffer.""" + scattered = full_hidden.clone() + scattered.index_copy_(0, active_indices, active_hidden.to(dtype=scattered.dtype)) + return scattered diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7a83cf9781d9df9041cc5e225f0cc3d20810bbb2 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/cache/utils.py @@ -0,0 +1,390 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utility functions for cache management. +""" + +import math +import torch +from typing import Dict, List, Tuple, Optional, Any +from inference.common import PackedCrossAttnParams + + +def generate_dynamic_kv_range( + tracker, + current_chunk_id: int, + x_chunks_keys: List[int], + chunk_token_nums: int, + near_clean_chunk_idx: int = -1 +) -> torch.Tensor: + """ + Generate dynamic KV ranges for chunks after compression. + + This function computes the KV range each chunk should attend to, + taking into account the compressed KV cache layout. + + Args: + tracker: ChunkKVRangeTracker instance managing chunk ranges + current_chunk_id: The chunk being processed + x_chunks_keys: List of all chunk keys being processed + chunk_token_nums: Number of tokens per chunk + near_clean_chunk_idx: Index of the nearly-clean chunk (-1 if not present) + + Returns: + Tensor of shape [num_chunks, 2] with KV ranges for each chunk + """ + kv_ranges = [] + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + # Process normal chunks (excluding near_clean_chunk) + normal_chunks = [chunk_id for chunk_id in x_chunks_keys if chunk_id != near_clean_chunk_idx] + + for chunk_id in normal_chunks: + # Normal chunk: needs to see itself and all previous chunks + all_chunk_ids = tracker.get_all_chunk_ids() + list(normal_chunks) + chunks_to_include = [cid for cid in all_chunk_ids if cid <= chunk_id] + + # Calculate based on actual compressed ranges in tracker + total_tokens = 0 + for cid in chunks_to_include: + if cid in tracker.get_all_chunk_ids(): + # Use compressed actual range + s, e = tracker.get_range(cid) + total_tokens = max(total_tokens, e) + else: + # Newly entered chunk not yet registered, but size is known + total_tokens += chunk_token_nums + + range_start = 0 + range_end = total_tokens + kv_ranges.append([range_start, range_end]) + + # Handle near_clean_chunk (always last if present) + if near_clean_chunk_idx != -1: + # Calculate end position of last normal chunk + last_normal_chunk_end = 0 + all_chunk_ids = tracker.get_all_chunk_ids() + normal_chunks + for cid in all_chunk_ids: + if cid in tracker.get_all_chunk_ids(): + s, e = tracker.get_range(cid) + last_normal_chunk_end = max(last_normal_chunk_end, e) + else: + # Newly entered chunk not yet registered + last_normal_chunk_end += chunk_token_nums + + # near_clean_chunk range: (last_normal_chunk_end, last_normal_chunk_end + chunk_token_nums] + range_start = last_normal_chunk_end + range_end = last_normal_chunk_end + chunk_token_nums + kv_ranges.append([range_start, range_end]) + + return torch.tensor(kv_ranges, device=device, dtype=torch.int32) + + +def identify_compressible_chunks( + tracker, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + chunk_offset: int = 0 +) -> Tuple[List[int], List[int]]: + """ + Identify which chunks can be compressed and which should remain active. + + A chunk can be compressed if: + - It's a prefix video chunk (always clean) + - It's a generated chunk that has completed all denoising steps + + Args: + tracker: ChunkKVRangeTracker instance + chunk_start: Current chunk being processed + transport_input: Transport input containing chunk info + chunk_denoise_count: Dictionary mapping chunk_id to denoising steps completed + chunk_offset: Number of prefix video chunks + + Returns: + Tuple of (clean_chunk_ids, active_chunk_ids) + """ + all_chunk_ids = tracker.get_all_chunk_ids() + + clean_chunks = [] + for cid in all_chunk_ids: + if cid < chunk_offset: + # Prefix video chunks are always clean + clean_chunks.append(cid) + elif cid <= chunk_start: + # Generated chunks need to check denoising completion + if chunk_denoise_count[cid] == transport_input.num_steps: + clean_chunks.append(cid) + + active_chunks = [cid for cid in all_chunk_ids if cid not in clean_chunks] + + return clean_chunks, active_chunks + + +def check_compress_condition( + tracker, + total_cache_len: int, + chunk_num: int, + chunk_start: int, + transport_input, + chunk_denoise_count: Dict[int, int], + window_size: int = 4 +) -> bool: + """ + Check if KV cache compression should be triggered. + + Compression is triggered when: + 1. Cache is full (next_free_idx >= total_cache_len) + 2. More chunks are yet to enter (registered_count < chunk_num) + 3. Next chunk is about to enter (last chunk's steps == num_steps/window_size) + + Args: + tracker: ChunkKVRangeTracker instance + total_cache_len: Total cache capacity in tokens + chunk_num: Total number of chunks + chunk_start: Current chunk being processed + transport_input: Transport input containing parameters + chunk_denoise_count: Dictionary mapping chunk_id to denoising steps + window_size: Window size for denoising stages (default: 4) + + Returns: + True if compression should be performed, False otherwise + """ + all_chunk_ids = tracker.get_all_chunk_ids() + if len(all_chunk_ids) == 0: + return False + + registered_chunk_count = len(all_chunk_ids) + cache_full = tracker.next_free_idx >= total_cache_len + has_more_chunks = registered_chunk_count < chunk_num + last_chunk_id = all_chunk_ids[-1] + + # Calculate steps per stage + steps_per_stage = transport_input.num_steps // window_size + next_chunk_will_enter = chunk_denoise_count[last_chunk_id] == steps_per_stage + + should_compress = cache_full and has_more_chunks and next_chunk_will_enter + return should_compress + + +def get_embedding_and_meta_with_chunk_info( + model_self, + x: torch.Tensor, + t: torch.Tensor, + y: torch.Tensor, + caption_dropout_mask, + xattn_mask, + kv_range: torch.Tensor, + **kwargs +) -> tuple: + """ + Compute embeddings and meta information with chunk-aware processing. + + This is a unified version of the get_embedding_and_meta function that + properly handles chunk-based processing with dynamic KV ranges. + + Args: + model_self: The DiT model instance + x: Input tensor [N, C, T, H, W] + t: Timestep tensor [N, range_num] + y: Text conditioning tensor + caption_dropout_mask: Dropout mask for captions + xattn_mask: Cross-attention mask + kv_range: KV range tensor + **kwargs: Additional arguments including: + - range_num: Total number of chunks + - denoising_range_num: Number of chunks being denoised + - slice_point: Starting chunk index + - start_chunk_id: First chunk to process + - end_chunk_id: Last chunk to process (exclusive) + - distill_nearly_clean_chunk: Whether to add nearly-clean chunk + - chunk_token_nums: Tokens per chunk + - chunk_width: Width of each chunk in frames + - num_steps: Total denoising steps + + Returns: + Tuple of (x, condition, condition_map, rope, y_xattn_flat, xattn_mask_cuda, + H, W, ardf_meta, cross_attn_params) + """ + # ========== Part 1: Embed x ========== + x = model_self.x_embedder(x) # [N, C, T, H, W] + batch_size, _, T, H, W = x.shape + + # Prepare necessary variables + range_num = kwargs["range_num"] + denoising_range_num = kwargs["denoising_range_num"] + slice_point = kwargs.get("slice_point", 0) + frame_in_range = T // denoising_range_num + + # distill_nearly_clean_chunk adds one extra chunk + T_total = (range_num + kwargs.get("distill_nearly_clean_chunk", False)) * frame_in_range + + # ========== Part 2: Compute rotary positional embedding ========== + rescale_factor = math.sqrt((H * W) / (16 * 16)) + rope = model_self.rope.get_embed( + shape=[T_total, H, W], + ref_feat_shape=[T_total, H / rescale_factor, W / rescale_factor] + ) + # Rope shape: (T*H*W, head_dim) - cut to current chunk range + rope = rope[ + kwargs["start_chunk_id"] * frame_in_range * H * W : + kwargs["end_chunk_id"] * frame_in_range * H * W + ] + + # ========== Part 3: Embed t ========== + assert t.shape[0] == batch_size, f"Invalid t shape: {t.shape[0]} != {batch_size}" + assert t.shape[1] == denoising_range_num, f"Invalid t shape: {t.shape[1]} != {denoising_range_num}" + + t_flat = t.flatten() # (N * denoising_range_num,) + t = model_self.t_embedder(t_flat) # (N, D) + + if model_self.engine_config.distill: + distill_dt_scalar = 2 + if kwargs["num_steps"] == 12: + base_chunk_step = 4 + distill_dt_factor = base_chunk_step / kwargs["distill_interval"] * distill_dt_scalar + else: + distill_dt_factor = kwargs["num_steps"] / 4 * distill_dt_scalar + + distill_dt = torch.ones_like(t_flat) * distill_dt_factor + distill_dt_embed = model_self.t_embedder(distill_dt) + t = t + distill_dt_embed + + t = t.reshape(batch_size, denoising_range_num, -1) # (N, range_num, D) + + # ========== Part 4: Embed y, prepare condition and y_xattn_flat ========== + y_xattn, y_adaln = model_self.y_embedder(y, model_self.training, caption_dropout_mask) + + assert xattn_mask is not None + xattn_mask = xattn_mask.squeeze(1).squeeze(1) + + # condition: (N, range_num, D) + y_adaln = y_adaln.squeeze(1) # (N, D) + condition = t + y_adaln.unsqueeze(1) + + assert condition.shape[0] == batch_size + assert condition.shape[1] == denoising_range_num + + seqlen_per_chunk = (T * H * W) // denoising_range_num + condition_map = torch.arange(batch_size * denoising_range_num, device=x.device) + condition_map = torch.repeat_interleave(condition_map, seqlen_per_chunk) + condition_map = condition_map.reshape(batch_size, -1).transpose(0, 1).contiguous() + + # y_xattn_flat: (total_token, D) + y_xattn_flat = torch.masked_select( + y_xattn.squeeze(1), + xattn_mask.unsqueeze(-1).bool() + ).reshape(-1, y_xattn.shape[-1]) + + xattn_mask_for_cuda_graph = None + + # ========== Part 5: Prepare cross_attn_params ========== + xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1) + y_index = torch.sum(xattn_mask, dim=-1) + clip_token_nums = H * W * frame_in_range + + cu_seqlens_q = torch.Tensor( + [0] + ([clip_token_nums] * denoising_range_num * batch_size) + ).to(torch.int64).to(x.device) + cu_seqlens_k = torch.cat( + [y_index.new_tensor([0]), y_index] + ).to(torch.int64).to(x.device) + cu_seqlens_q = cu_seqlens_q.cumsum(-1).to(torch.int32) + cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32) + + assert cu_seqlens_q.shape == cu_seqlens_k.shape, \ + f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}" + + xattn_q_ranges = torch.cat( + [cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1 + ) + xattn_k_ranges = torch.cat( + [cu_seqlens_k[:-1].unsqueeze(1), cu_seqlens_k[1:].unsqueeze(1)], dim=1 + ) + assert xattn_q_ranges.shape == xattn_k_ranges.shape, \ + f"xattn_q_ranges.shape: {xattn_q_ranges.shape}, xattn_k_ranges.shape: {xattn_k_ranges.shape}" + + cross_attn_params = PackedCrossAttnParams( + q_ranges=xattn_q_ranges, + kv_ranges=xattn_k_ranges, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_k, + max_seqlen_q=clip_token_nums, + max_seqlen_kv=model_self.caption_max_length, + ) + + # ========== Part 6: Prepare core_attn related q/kv range ========== + q_range = torch.cat( + [cu_seqlens_q[:-1].unsqueeze(1), cu_seqlens_q[1:].unsqueeze(1)], dim=1 + ) + flat_kv = torch.unique(kv_range, sorted=True) + max_seqlen_k = (flat_kv[-1] - flat_kv[0]).cpu().item() + + ardf_meta = dict( + clip_token_nums=clip_token_nums, + slice_point=slice_point, + range_num=range_num, + denoising_range_num=denoising_range_num, + q_range=q_range, + k_range=kv_range, + max_seqlen_q=clip_token_nums, + max_seqlen_k=max_seqlen_k, + ) + + return (x, condition, condition_map, rope, y_xattn_flat, + xattn_mask_for_cuda_graph, H, W, ardf_meta, cross_attn_params) + + +def compute_chunk_token_nums( + transport_input, + model_config, + chunk_width: int +) -> int: + """ + Calculate the number of tokens in one chunk. + + Args: + transport_input: Transport input containing latent dimensions + model_config: Model configuration + chunk_width: Number of frames per chunk + + Returns: + Number of tokens per chunk + """ + patch_size = model_config.patch_size + latent_h = transport_input.latent_size[3] // patch_size + latent_w = transport_input.latent_size[4] // patch_size + + return chunk_width * latent_h * latent_w + + +def get_latent_spatial_dims( + transport_input, + model_config +) -> Tuple[int, int]: + """ + Get the spatial dimensions of latent in patch units. + + Args: + transport_input: Transport input containing latent dimensions + model_config: Model configuration + + Returns: + Tuple of (height_patches, width_patches) + """ + patch_size = model_config.patch_size + h = transport_input.latent_size[3] // patch_size + w = transport_input.latent_size[4] // patch_size + return h, w diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/entry.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/entry.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd00938520790d9317cbaa7f504c01b179a9dba --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/entry.py @@ -0,0 +1,104 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import gc +import sys + +import torch + +from inference.pipeline import MagiPipeline + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Run MagiPipeline with different modes.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument( + '--residual_stats_path', + type=str, + help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--l1_rel_stats_path', + type=str, + help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.', + ) + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage after pipeline completion.') + return parser.parse_args() + + +def main(): + args = parse_arguments() + + if args.print_peak_memory: + # Check if GPU is available and reset memory stats + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB allocated") + else: + print("CUDA not available, running on CPU") + + pipeline = MagiPipeline( + args.config_file, + residual_stats_path=args.residual_stats_path, + l1_rel_stats_path=args.l1_rel_stats_path, + ) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video(prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path) + + if args.print_peak_memory: + # Print peak memory usage after pipeline completion + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "="*50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("="*50) + + # Clear cache and show final memory + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/flowcache.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/flowcache.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4611ce39827d2b75110ba65e9aa1ed53dca5ff --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/flowcache.py @@ -0,0 +1,748 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +FlowCache implementation: Per-chunk output reuse + KV cache compression. + +This module provides FlowCache, which combines: +- ChunkWiseCache: Per-chunk output reuse for fine-grained control +- KVCacheCompressor: Dynamic KV cache compression for memory efficiency +""" + +import argparse +import gc +import os +import sys +import torch +from types import MethodType + +from inference.pipeline import MagiPipeline +from inference.pipeline.video_generate import SampleTransport, find_dit_model +from inference.pipeline.cache import ChunkWiseCache, KVCacheCompressor +from inference.pipeline.cache.utils import ( + generate_dynamic_kv_range, + get_embedding_and_meta_with_chunk_info, +) +from inference.pipeline.kvcompress import replace_magi +from inference.pipeline.kvcompress.utils import ChunkKVRangeTracker + + +def setup_flowcache( + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + total_cache_chunk_nums: int = 5, + compress_kv_cache: bool = True, + metric_stats_path: str = None, +): + """ + Set up FlowCache with per-chunk reuse and KV compression. + + Args: + rel_l1_thresh: Relative L1 distance threshold for reuse + warmup_steps: Number of warmup steps per chunk before reuse can happen + discard_nearly_clean_chunk: Whether to skip nearly-clean chunk + log: Whether to log reuse decisions + total_cache_chunk_nums: Total number of chunks to cache + compress_kv_cache: Whether to enable KV cache compression + """ + # Create cache instance and attach to SampleTransport + SampleTransport.cache_reuse_manager = ChunkWiseCache( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + discard_nearly_clean_chunk=discard_nearly_clean_chunk, + log=log, + metric_stats_path=metric_stats_path, + ) + + # Initialize compressor placeholder (will be created at runtime) + SampleTransport.kv_compress_manager = None + + # Monkey patch the SampleTransport methods + SampleTransport.forward_velocity = flowcache_forward_velocity + SampleTransport.integrate_velocity = flowcache_integrate_velocity + SampleTransport.total_cache_chunk_nums = total_cache_chunk_nums + SampleTransport.compress_kv_cache = compress_kv_cache + + +def flowcache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> dict: + """ + Forward pass with per-chunk TeaCache and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + + Returns: + Dictionary mapping chunk_id to velocity tensor + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + + # 2. Initialize KV cache tracking if needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + if not hasattr(self.inference_params[infer_idx], 'kv_chunk_tracker'): + self.inference_params[infer_idx].kv_chunk_tracker = ChunkKVRangeTracker( + total_cache_len=total_cache_len, + clip_token_nums=chunk_token_nums, + max_batch_size=1 + ) + + if not hasattr(self, 'chunk_query_states'): + self.chunk_query_states = {} + + # 3. Initialize chunk state + cache.initialize_chunk_state(transport_input.chunk_num) + + # 4. Extract denoising status + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + self.current_chunk_offset = chunk_offset + + # 5. Prepare model kwargs + model_kwargs = dict( + chunk_width=self.chunk_width, + fwd_extra_1st_chunk=False, + num_steps=transport_input.num_steps + ) + if hasattr(self, "debug"): + model_kwargs["debug"] = self.debug + model_kwargs.update({ + "denoise_step_per_stage": denoise_step_per_stage, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_num": transport_input.chunk_num + }) + + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + model_kwargs.update({ + "compress_kv": True, + "total_cache_len": total_cache_len + }) + else: + model_kwargs["save_kvcache_every_forward"] = True + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 6. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update({ + "slice_point": chunk_start, + "range_num": chunk_end, + "denoising_range_num": chunk_end - chunk_start + }) + model_kwargs["chunk_token_nums"] = chunk_token_nums + + # 7. Prepare timesteps + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + # 8. Generate KV range + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 9. Pad prefix video if needed + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 10. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + # Initialize step counter + cache.set_total_steps(model_kwargs["total_num_steps"]) + + # Setup monkey-patched model forward + model = find_dit_model(self.model) + model.forward = MethodType(_create_flowcache_model_forward_fn(cache, self, infer_idx), model) + model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model) + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + +def _create_flowcache_model_forward_fn(cache: ChunkWiseCache, transport, infer_idx: int): + """ + Create a model forward function with per-chunk cache and KV compression logic. + + Args: + cache: ChunkWiseCache instance + transport: SampleTransport instance + infer_idx: Inference index + + Returns: + Model forward function + """ + @torch.no_grad() + def model_forward( + model_self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params=None, + **kwargs, + ) -> dict: + raw_x = x.clone() + + # 1. Compute feature metrics per chunk + # Following source code: compute metric_x first, handle slicing, then split + metric_chunks, num_chunks = cache.compute_feature_metric( + x=x, + x_embedder=model_self.x_embedder, + x_rescale_factor=model_self.model_config.x_rescale_factor, + half_channel_vae=model_self.model_config.half_channel_vae, + chunk_token_nums=kwargs["chunk_token_nums"], + params_dtype=model_self.model_config.params_dtype, + offset=kwargs['slice_point'], + fwd_extra_1st_chunk=kwargs.get("fwd_extra_1st_chunk", False), + distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False) + ) + + # 2. Update kwargs + cache.total_num_steps = kwargs['total_num_steps'] + denoise_step_per_stage = kwargs['denoise_step_per_stage'] + kwargs['cur_denoise_step'] = cache.cnt + model_self.cur_denoise_step = cache.cnt + + # 3. Split x into chunks (using num_chunks from metric_x, matching source code) + chunk_width = kwargs["chunk_width"] + offset = kwargs['slice_point'] + x_chunks = {} + # Artifact chunks in x are not included - following source code comment + for i in range(num_chunks): + start_idx = i * chunk_width + end_idx = start_idx + chunk_width + x_chunks[offset + i] = x[:, :, start_idx:end_idx] + + # 4. Handle nearly clean chunk (artifact chunk) - add separately AFTER normal chunks + # Following source code logic + model_self.discard_nearly_clean_chunk = cache.discard_nearly_clean_chunk + near_clean_chunk_idx = -1 + if not cache.discard_nearly_clean_chunk and kwargs.get("distill_nearly_clean_chunk", False): + # Add artifact chunk - following source code comment + near_clean_chunk_idx = max(x_chunks.keys()) + 1 + model_self.near_clean_chunk_idx = near_clean_chunk_idx + x_chunks[near_clean_chunk_idx] = x[:, :, -chunk_width:] + + # 5. Determine which chunks to reuse + if cache.cnt != 0 and cache.cnt != cache.num_steps - 1: + current_num_chunks = len(metric_chunks) + previous_num_chunks = len(cache.prev_metric_chunks) + + common_keys = set(metric_chunks.keys()) & set(cache.prev_metric_chunks.keys()) + for i in sorted(common_keys): + should_reuse = cache.should_reuse( + chunk_id=i, + step=cache.cnt, + current_features=metric_chunks, + chunk_denoise_count=transport.chunk_denoise_count[infer_idx], + current_num_chunks=current_num_chunks, + previous_num_chunks=previous_num_chunks, + infer_idx=infer_idx, + cur_denoise_step=cache.cnt, + denoise_stage=kwargs.get("denoise_stage"), + denoise_idx=kwargs.get("denoise_idx"), + chunk_offset=getattr(transport, "current_chunk_offset", 0), + chunk_denoise_count_value=transport.chunk_denoise_count[infer_idx][i], + ) + cache.chunk_reuse_flags[i] = should_reuse + + # 6. Remove nearly clean chunk if first chunk can be reused + if cache.chunk_reuse_flags.get(kwargs["slice_point"], False) and near_clean_chunk_idx != -1: + x_chunks.pop(near_clean_chunk_idx, None) + + # 7. Store previous features + cache.store_previous_features(metric_chunks) + + # 8. Forward chunks that are not reused + current_infer_outputs = {} + + for i in sorted(x_chunks.keys()): + if i in cache.chunk_reuse_flags and cache.chunk_reuse_flags[i]: + continue + + x_i = x_chunks[i] + # Handle near_clean_chunk_idx: use last chunk of t, y, xattn_mask + if i == near_clean_chunk_idx: + t_i = t[:, -1:] + y_i = y[-1:] + xattn_mask_i = xattn_mask[-1:] + else: + t_i = t[:, i - offset:i - offset + 1] + y_i = y[i - offset:i - offset + 1] + xattn_mask_i = xattn_mask[i - offset:i - offset + 1] + + kwargs["start_chunk_id"] = i + kwargs["end_chunk_id"] = i + 1 + kwargs["denoising_range_num"] = 1 + + if i == near_clean_chunk_idx: + kwargs["distill_nearly_clean_chunk"] = True + else: + kwargs["distill_nearly_clean_chunk"] = False + + # Update KV range if compressed + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + if inference_params.kv_compressed: + kv_range = generate_dynamic_kv_range( + tracker=inference_params.kv_chunk_tracker, + current_chunk_id=i, + x_chunks_keys=list(x_chunks.keys()), + chunk_token_nums=kwargs["chunk_token_nums"], + near_clean_chunk_idx=near_clean_chunk_idx + ) + + kwargs["near_clean_chunk_idx"] = near_clean_chunk_idx + (processed_x, condition, condition_map, y_xattn_flat, rope, meta_args) = \ + model_self.forward_pre_process( + x_i, t_i, y_i, caption_dropout_mask, xattn_mask_i, kv_range, **kwargs + ) + + if not model_self.pre_process: + from inference.pipeline.parallelism import pp_scheduler + processed_x = pp_scheduler().recv_prev_data(processed_x.shape, processed_x.dtype) + model_self.videodit_blocks.set_input_tensor(processed_x) + else: + processed_x = processed_x.clone() + + try: + out = model_self.videodit_blocks.forward( + hidden_states=processed_x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + except Exception as e: + import pdb; pdb.set_trace() + + # Store query states for compression + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + for layer in model_self.videodit_blocks.layers: + layer_num = layer.self_attention.layer_number + if hasattr(layer.self_attention, '_last_query'): + transport.chunk_query_states[layer_num] = layer.self_attention._last_query + + if not model_self.post_process: + from inference.pipeline.parallelism import pp_scheduler + pp_scheduler().isend_next(out) + + out = model_self.forward_post_process(out, meta_args) + current_infer_outputs[i] = out.clone().detach() + + return current_infer_outputs + + return model_forward + + +@torch.no_grad() +def _new_get_embedding_and_meta(model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs): + """Monkey-patched version of get_embedding_and_meta with chunk info.""" + return get_embedding_and_meta_with_chunk_info( + model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + +def flowcache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + """ + Integrate velocity with per-chunk cache residual handling and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + chunk_num = x_chunk.shape[2] // self.chunk_width + offset = chunk_start + ori_x_chunk = x_chunk.clone() + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + next_t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=False + ) + x_embedder_before = None + x_embedder_after = None + x_embedder_chunk_width = None + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(ori_x_chunk) + + # Split into chunks + x_chunks = {} + for i in range(chunk_num): + start_idx = i * self.chunk_width + end_idx = start_idx + self.chunk_width + x_chunks[offset + i] = x_chunk[:, :, start_idx:end_idx] + + # Integrate per chunk + for i in range(chunk_num): + chunk_id = offset + i + reused = cache.chunk_reuse_flags[chunk_id] + cache.record_actual_execution( + chunk_id=chunk_id, + reused=reused, + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + ) + if reused: + # Reuse: add residual + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] += \ + cache.previous_residual[chunk_id] + else: + # Recalculate + assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs" + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] = \ + self.integrate(x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx], + denoise_step_per_stage, t_start, t_end, denoise_idx, i) + # Store residual + cache.previous_residual[chunk_id] = \ + x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] - \ + ori_x_chunk[:, :, i * self.chunk_width:(i + 1) * self.chunk_width] + + applied_residual = x_chunk - ori_x_chunk + self.residual_diff_tracker.update_residuals( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + residual=applied_residual, + timesteps=t, + chunk_width=self.chunk_width, + ) + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk) + self.l1_rel_change_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_before=ori_x_chunk, + x_after=x_chunk, + timesteps=t, + next_timesteps=next_t, + chunk_width=self.chunk_width, + x_embedder_before=x_embedder_before, + x_embedder_after=x_embedder_after, + x_embedder_chunk_width=x_embedder_chunk_width, + ) + + # Increment step counter + cache.increment_step() + + # Update chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # Check if KV compression is needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + + # Return clean chunk if ready + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + return _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset) + + return None, None + + +def _check_and_compress_kv(self, infer_idx: int, chunk_start: int, transport_input): + """Check and perform KV cache compression if needed.""" + inference_params = self.inference_params[infer_idx] + tracker = inference_params.kv_chunk_tracker + + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + # Get or create compressor from class attribute + compressor = SampleTransport.kv_compress_manager + if compressor is None: + chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx)[1] + compressor = KVCacheCompressor( + total_cache_len=total_cache_len, + tokens_per_chunk=chunk_token_nums, + budget_chunk_nums=self.total_cache_chunk_nums - 1, + window_size=self.window_size + ) + SampleTransport.kv_compress_manager = compressor + + # Check if compression needed + if compressor.should_compress( + tracker=tracker, + chunk_num=transport_input.chunk_num, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=self.chunk_denoise_count[infer_idx] + ): + compressor.compress( + model=find_dit_model(self.model), + inference_params=inference_params, + tracker=tracker, + transport_input=transport_input, + chunk_start=chunk_start, + chunk_denoise_count=self.chunk_denoise_count[infer_idx], + query_states_dict=self.chunk_query_states + ) + + +def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset): + """Return the clean chunk if denoising is complete.""" + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + + +def load_config(config_path: str) -> dict: + """Load configuration from JSON or YAML file.""" + _, ext = os.path.splitext(config_path) + with open(config_path, 'r') as f: + if ext == '.json': + import json + return json.load(f) + elif ext in ['.yaml', '.yml']: + import yaml + return yaml.safe_load(f) + else: + raise ValueError(f"Unsupported config file extension: {ext}") + + +def parse_arguments(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Run MagiPipeline with FlowCache.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], + required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument('--additional_config', type=str, help='Path to additional config file.') + parser.add_argument( + '--residual_stats_path', + type=str, + help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--l1_rel_stats_path', + type=str, + help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--flowcache_metric_stats_path', + type=str, + help='Optional path to save FlowCache original reuse metric stats as .json, .pt, or .pth.', + ) + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.') + + return parser.parse_args() + + +def main(): + """Main entry point.""" + args = parse_arguments() + + # Load additional config + if args.additional_config: + additional_config = load_config(args.additional_config) + print(f"Loading additional config: {additional_config}") + + for key, value in additional_config.items(): + setattr(args, key, value) + print(f"Added to args: {key} = {value}") + + # Handle parameter name compatibility + if hasattr(args, 'no_reuse_first_n_steps') and not hasattr(args, 'warmup_steps'): + args.warmup_steps = args.no_reuse_first_n_steps + if hasattr(args, 'no_reuse_mode'): + # no_reuse_mode is deprecated, ignore it + pass + else: + print("No additional config provided.") + + if args.print_peak_memory: + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB") + else: + print("CUDA not available, running on CPU") + + # Setup FlowCache + setup_flowcache( + rel_l1_thresh=args.rel_l1_thresh, + warmup_steps=args.warmup_steps, + discard_nearly_clean_chunk=args.discard_nearly_clean_chunk, + log=args.log, + total_cache_chunk_nums=args.total_cache_chunk_nums, + compress_kv_cache=args.compress_kv_cache, + metric_stats_path=args.flowcache_metric_stats_path, + ) + + # Setup KV compression in model + compression_config = { + "method_config": { + "compress_strategy": getattr(args, 'compress_strategy', 'token'), + "mix_lambda": getattr(args, 'mix_lambda', 0.07), + "query_granularity": getattr(args, 'query_granularity', 'chunk'), + "score_weighting_method": getattr(args, 'score_weighting_method', None) or 'no_weight', + "power": getattr(args, 'power', 3), + }, + } + replace_magi(compression_config) + + # Run pipeline + pipeline = MagiPipeline( + args.config_file, + residual_stats_path=args.residual_stats_path, + l1_rel_stats_path=args.l1_rel_stats_path, + ) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video( + prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path + ) + + if args.print_peak_memory: + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "=" * 50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("=" * 50) + + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/.DS_Store b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..81ddf723ab2ad7484c6b094f87561851f2a00842 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/.DS_Store differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__init__.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..271690aebf11d70f2405296aac31012d08bae88f --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__init__.py @@ -0,0 +1,9 @@ +""" +This package provides efficient decoding-time KV cache compression methods. +""" + +__version__ = "0.1.0" + +from .monkeypatch import replace_magi + +__all__ = ["replace_magi"] diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0c13ad3f33e411fad181e817b19ae87caab3046 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/__init__.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1e789726d1071cefb92b78ac79546965010d97f Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/kv_compressor.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf09b4e776e8aead2ced5ad8e09c43daa690d96 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/modeling.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaaccf3a0083872afbe01397b93b2479ba0d38a5 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/monkeypatch.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0599c24a10a34a1c0c9bd44e1f08f409df3283f2 Binary files /dev/null and b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/__pycache__/utils.cpython-310.pyc differ diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/kv_compressor.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/kv_compressor.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd7a518cde39d1f61e9f83c159662b63c6ed759 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/kv_compressor.py @@ -0,0 +1,314 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import List +import os + +from inference.pipeline.kvcompress.utils import cal_similarity, compute_attention_scores + + +class KVCompressor: + def __init__( + self, + kernel_size=7, + mix_lambda=0.07, + compress_strategy="token", + query_granularity="chunk", + score_weighting_method="default", + power=3, + **kwargs, + ): + self.kernel_size = kernel_size + self.mix_lambda = mix_lambda + assert compress_strategy in ["token", "frame", "chunk"] + assert query_granularity in ["token", "frame", "chunk"] + self.compress_strategy = compress_strategy + self.query_granularity = query_granularity + self.score_weighting_method = score_weighting_method + self.power = power + + def update_kv( + # The passed kv is the kv cache of all chunks + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + latent_size_t, + latent_size_h, + latent_size_w + ): + if self.query_granularity == "token": + # Take 50 tokens + query_states = query_states[- 50 : ] + elif self.query_granularity == "frame": + query_states = query_states[- latent_size_h * latent_size_w : ] + elif self.query_granularity == "chunk": + pass + else: + raise ValueError("Invalid query granularity") + + if self.compress_strategy == "token": + return self.update_kv_token( + key_states, + query_states, + value_states, + clean_chunk_tokens, + each_chunk_tokens=latent_size_t * latent_size_h * latent_size_w, + ) + elif self.compress_strategy == "frame": + return self.update_kv_frame_chunk( + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size=latent_size_h * latent_size_w, + ) + elif self.compress_strategy == "chunk": + return self.update_kv_frame_chunk( + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size=latent_size_t * latent_size_h * latent_size_w, + ) + else: + raise ValueError("Invalid compress strategy") + + def update_kv_token( + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + each_chunk_tokens, + ): + each_chunk_tokens = int(each_chunk_tokens) + head_dim = query_states.shape[-1] + kv_cache_len = key_states.shape[0] + + attn_weights = compute_attention_scores(query_states, key_states[:clean_chunk_tokens]) + attn_weights_sum = ( + nn.functional.softmax( + attn_weights[:, :, : clean_chunk_tokens], + dim=-1, + dtype=torch.float32, + ) + .mean(dim=-2) + .to(query_states.dtype) + ) + + attn_cache = F.max_pool1d( + attn_weights_sum, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + stride=1, + ).to('cpu') + + similarity_cos = cal_similarity(key_states[:clean_chunk_tokens, :, :]).to('cpu') + + final_score = attn_cache * self.mix_lambda - similarity_cos * (1 - self.mix_lambda) + + # Ensure final score is non-negative for weighting + min_scores_per_head = final_score.min(dim=-1, keepdim=True).values # (num_kv_heads, 1) + final_score = final_score - min_scores_per_head + + # Note that final_score contains negative numbers + # Apply different weighting methods to final_score, relatively making tokens at later positions more likely to be selected + if self.score_weighting_method == "no_weight": + print("Using no weighting method") + pass + + elif self.score_weighting_method == "hard_code": + print("Using hard code weighting method") + final_score[:, :each_chunk_tokens] -= 1e6 + + elif self.score_weighting_method == "exponential": + print("Using exponential weighting method") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + decay_rate = 2.0 + # Normalize to [0.1, 1.0] range + exponential_values = 1 - torch.exp(-decay_rate * positions) + max_value = 1 - torch.exp(torch.tensor(-decay_rate, device=final_score.device)) # Value when positions=1 + weights = 0.1 + 0.9 * (exponential_values / max_value) + final_score = final_score * weights.unsqueeze(0) + + elif self.score_weighting_method == "polynomial": + print(f"Using polynomial weighting method, power={self.power}") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + # Normalize to [0.1, 1.0] range + weights = 0.1 + 0.9 * (positions ** self.power) + final_score = final_score * weights.unsqueeze(0) + elif self.score_weighting_method == "upper_convex_polynomial": + print(f"Using upper convex polynomial weighting method, power={self.power}") + seq_len = final_score.shape[1] + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) / (seq_len - 1) if seq_len > 1 else torch.zeros(1) + max_value = 2.0 + # Construct upper convex n-th degree polynomial: w(x) = max_value * (1 - (1-x)^n) + weights = max_value * (1 - (1 - positions) ** self.power) + final_score = final_score * weights.unsqueeze(0) + + elif self.score_weighting_method == "gaussian": + print("Using gaussian weighting method") + # Emphasize previous information more + seq_len = final_score.shape[1] + + positions = torch.arange(seq_len, dtype=torch.float32, device=final_score.device) + sigma = seq_len / 4.0 # ← Adjustable! Smaller values emphasize the beginning more + + gaussian_decay = torch.exp(-0.5 * (positions / sigma) ** 2) + min_decay = torch.exp(torch.tensor(-0.5 * ((seq_len - 1) / sigma) ** 2, device=final_score.device)) + + # Map [min_decay, 1.0] → [0.1, 1.0] + weights = 0.1 + 0.9 * ((gaussian_decay - min_decay) / (1.0 - min_decay)) + final_score = final_score * weights.unsqueeze(0) + else: + raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}") + + # Calculate number of tokens to keep + num_to_keep = self.budget + + # Select top-k tokens + try: + indices = final_score.topk(num_to_keep, dim=-1).indices # shape: (num_kv_heads, num_to_keep) + del final_score + except RuntimeError: + import pdb; pdb.set_trace() + indices = indices.unsqueeze(-1).expand(-1, -1, head_dim).permute(1, 0, 2) # shape: (num_to_keep, num_kv_heads, head_dim) + + indices = indices.to(key_states.device) + + # Compress non-recent parts + k_past_compress = key_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices) + v_past_compress = value_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices) + k_cur = key_states[clean_chunk_tokens :, :, :] + v_cur = value_states[clean_chunk_tokens :, :, :] + + key_compress = torch.cat([k_past_compress, k_cur], dim=0) + value_compress = torch.cat([v_past_compress, v_cur], dim=0) + + return key_compress, value_compress, indices + + def update_kv_frame_chunk( + self, + key_states, + query_states, + value_states, + clean_chunk_tokens, + together_size, + ): + head_dim = query_states.shape[-1] + kv_cache_len = key_states.shape[0] + + # ========== Compression Logic ========== + + # Step 1: Compute attention weights + attn_weights = compute_attention_scores(query_states, key_states) + attn_weights_sum = ( + nn.functional.softmax( + attn_weights[:, :, : clean_chunk_tokens], + dim=-1, + dtype=torch.float32, + ) + .mean(dim=-2) # shape: (num_kv_heads, clean_chunk_tokens) + .to(query_states.dtype) + ) + + # Step 2: Pooling to get "importance" of each token + attn_cache = F.max_pool1d( + attn_weights_sum, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + stride=1, + ).to('cpu') # shape: (num_kv_heads, clean_chunk_tokens) + + # Step 3: Compute similarity between tokens + similarity_cos = cal_similarity(key_states[:clean_chunk_tokens, :, :]).to('cpu') + + # Step 4: Compute final score for each token + final_score_per_token = attn_cache * self.mix_lambda - similarity_cos * (1 - self.mix_lambda) + # shape: (num_kv_heads, clean_chunk_tokens) + + # ========== Frame-wise or Chunk-wise Aggregation ========== + # In the code below, chunk is also referred to as frame; they are conceptually consistent, just differing in how many tokens are aggregated into one frame/chunk + + assert clean_chunk_tokens % together_size == 0 + num_frames = clean_chunk_tokens // together_size + + # Reshape to (num_kv_heads, num_frames, together_size) + score_frames = final_score_per_token.view( + key_states.shape[1], num_frames, together_size + ) + + # Aggregate scores for each frame + frame_scores = score_frames.mean(dim=-1) # shape: (num_kv_heads, num_frames) + + # Calculate number of frames to keep + assert self.budget % together_size == 0 + num_frames_to_keep = self.budget // together_size + + # Select top-k frames for each head + frame_indices = frame_scores.topk(num_frames_to_keep, dim=-1).indices + # shape: (num_kv_heads, num_frames_to_keep) + + + # Convert frame_indices to token indices + # frame_indices: frame id selected by each head + + # offset: [0, 1, ..., together_size-1] + token_offsets = torch.arange(together_size, device=key_states.device) + frame_indices_expanded = frame_indices.unsqueeze(-1) * together_size + token_indices_per_head = frame_indices_expanded + token_offsets # shape: (num_heads, num_frames_to_keep, together_size) + token_indices_flat = token_indices_per_head.view(key_states.shape[1], -1) # (num_heads, K * together_size) + indices_gather = token_indices_flat.permute(1, 0).unsqueeze(-1).expand(-1, -1, head_dim) # shape: (kept_tokens, num_kv_heads, head_dim) + + # Gather from key/value + k_past_compress = key_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices_gather) + v_past_compress = value_states[:clean_chunk_tokens, :, :].gather(dim=0, index=indices_gather) + + # ========== Concatenate Recent Parts ========== + k_cur = key_states[clean_chunk_tokens:, :, :] + v_cur = value_states[clean_chunk_tokens:, :, :] + + key_compress = torch.cat([k_past_compress, k_cur], dim=0) + value_compress = torch.cat([v_past_compress, v_cur], dim=0) + + return key_compress, value_compress, indices_gather # token indices + + +def plot_tensor_values(tensor_1d: torch.Tensor, title: str = "Tensor Values", save_path: str = None, + xlabel: str = "Position", ylabel: str = "Value", figsize: tuple = (10, 6)): + try: + import matplotlib.pyplot as plt + import numpy as np + except ImportError: + print("Warning: matplotlib not available, skipping plot") + return + + # Ensure input is a 1D tensor + if tensor_1d.dim() != 1: + raise ValueError(f"Input tensor must be 1D, got {tensor_1d.dim()}D") + + # Convert to numpy array + values = tensor_1d.detach().cpu().float().numpy() + positions = np.arange(len(values)) + + # Create plot + plt.figure(figsize=figsize) + plt.plot(positions, values, 'b-', linewidth=2, markersize=4, alpha=0.8) + plt.xlabel(xlabel, fontsize=12) + plt.ylabel(ylabel, fontsize=12) + plt.title(title, fontsize=14) + + # Adjust layout + plt.tight_layout() + + # Save plot + if save_path is not None: + os.makedirs(os.path.dirname(save_path), exist_ok=True) + plt.savefig(save_path, dpi=100, bbox_inches='tight') + print(f"Plot saved to: {save_path}") + + plt.close() \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/modeling.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebec5d78478d33f86036559fd7c6f66b733ef65 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/modeling.py @@ -0,0 +1,54 @@ +import torch +from .kv_compressor import KVCompressor +from inference.model.dit.dit_module import CustomLayerNormLinear, FusedLayerNorm, PerChannelQuantizedFp8Linear, Attention +from inference.common import EngineConfig, InferenceParams, ModelConfig, ModelMetaArgs + +def MagiAttention_init( + self, model_config: ModelConfig, engine_config: EngineConfig, layer_number: int, compression_config: dict +): + Attention.__init__(self, model_config, engine_config, layer_number) + # super().__init__(model_config=model_config, engine_config=engine_config, layer_number=layer_number) + + # output 2x query, one for self-attn, one for cross-attn with condition + self.linear_qkv = CustomLayerNormLinear( + input_size=self.model_config.hidden_size, + output_size_q=self.query_projection_size, + output_size_kv=self.kv_projection_size, + layer_number=self.layer_number, + model_config=self.model_config, + engine_config=self.engine_config, + ) + + # kv from condition, e.g., caption + self.linear_kv_xattn = torch.nn.Linear( + int(self.model_config.hidden_size * self.model_config.xattn_cond_hidden_ratio), # 6144 + 2 * self.kv_projection_size, # 2048 + dtype=self.model_config.params_dtype, + bias=False, + ) + + # Output. + self.adapt_linear_quant = ( + self.engine_config.fp8_quant and self.layer_number != 0 and self.layer_number != model_config.num_layers - 1 + ) + submodules_linear_proj = PerChannelQuantizedFp8Linear if self.adapt_linear_quant else torch.nn.Linear + self.linear_proj = submodules_linear_proj( + 2 * self.query_projection_size, self.model_config.hidden_size, dtype=self.model_config.params_dtype, bias=False + ) + + self.q_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.q_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + self.k_layernorm = FusedLayerNorm(model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head) + self.k_layernorm_xattn = FusedLayerNorm( + model_config=self.model_config, hidden_size=self.hidden_size_per_attention_head + ) + + self.attn_weights_history = [] + + # =============== New logic start =============== + self.kv_cluster = KVCompressor( + **compression_config["method_config"] + ) + # =============== New logic end ================= \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/monkeypatch.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/monkeypatch.py new file mode 100644 index 0000000000000000000000000000000000000000..154d59435406156a93909fd3d015334e47b76dd3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/monkeypatch.py @@ -0,0 +1,8 @@ +from .modeling import MagiAttention_init + +def replace_magi(compression_config): + from inference.model.dit import VideoDiTModel, FullyParallelAttention + def init_wrapper(self, model_config, engine_config, layer_number): + MagiAttention_init(self, model_config, engine_config, layer_number, compression_config) + + FullyParallelAttention.__init__ = init_wrapper \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c5748d277836e2deb6bc4aaa503ccef829f58ee8 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/kvcompress/utils.py @@ -0,0 +1,208 @@ +import math +import torch +import time +import matplotlib.pyplot as plt +import numpy as np +from typing import List, Tuple, Dict + +################################################################# +###################### kv cache utilities ####################### +################################################################# + +def compute_attention_scores(query_states, key_states_cpu, pooling="max"): + """ + query_states: [q_len, q_heads, head_dim] on GPU + key_states_cpu: [kv_len, kv_heads, head_dim] on CPU + """ + + q_len, q_heads, head_dim = query_states.shape + kv_len, kv_heads, _ = key_states_cpu.shape + query_group_size = q_heads // kv_heads + + device = query_states.device # GPU + + # print(f"Before computing attention scores, GPU memory usage: {torch.cuda.memory_allocated() / 1024 ** 3:.1f} GB") + + if query_group_size == 1: + chunk_size = 12150 + + attn_weights = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) + + for i in range(0, kv_len, chunk_size): + end_i = min(i + chunk_size, kv_len) + k_chunk = key_states_cpu[i:end_i].to(device) # Transfer small chunk to GPU + + attn_chunk = torch.bmm( + query_states.transpose(0, 1), # [kv_heads, q_len, head_dim] + k_chunk.transpose(1, 2) # [kv_heads, head_dim, chunk_size] + ) / math.sqrt(head_dim) # [kv_heads, q_len, chunk_size] + + attn_weights[:, :, i:end_i] = attn_chunk + del k_chunk, attn_chunk + + return attn_weights + + else: + # query_states: [q_len, q_heads, head_dim] -> reshape to group + # We group by query_group, but still compute key in chunks + query_states = query_states.view(q_len, kv_heads, query_group_size, head_dim) + # [q_len, kv_heads, g, head_dim] -> permute to [kv_heads, g, q_len, head_dim] + query_states = query_states.permute(1, 2, 0, 3).contiguous() # [kv_heads, g, q_len, head_dim] + + if pooling == "mean": + attn_weights_sum = None + count = 0 + elif pooling == "max": + attn_weights_max = None + else: + raise ValueError("Pooling method not supported") + + for g in range(query_group_size): + q_group = query_states[:, g, :, :] # [kv_heads, q_len, head_dim] + + chunk_size = 12150 + group_attn = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) + + for i in range(0, kv_len, chunk_size): + end_i = min(i + chunk_size, kv_len) + k_chunk = key_states_cpu[i:end_i].to(device) # [chunk_size, kv_heads, head_dim] + k_chunk = k_chunk.permute(1, 2, 0) # [kv_heads, head_dim, chunk_size] + attn_chunk = torch.bmm(q_group, k_chunk) / math.sqrt(head_dim) + group_attn[:, :, i:end_i] = attn_chunk + del k_chunk, attn_chunk + + # Apply pooling over query_group_size dimension + if pooling == "mean": + if attn_weights_sum is None: + attn_weights_sum = group_attn + else: + attn_weights_sum += group_attn + count += 1 + elif pooling == "max": + if attn_weights_max is None: + attn_weights_max = group_attn + else: + attn_weights_max = torch.max(attn_weights_max, group_attn) + + del group_attn + + if pooling == "mean": + attn_weights = attn_weights_sum / count + del attn_weights_sum + elif pooling == "max": + attn_weights = attn_weights_max + del attn_weights_max + + return attn_weights + + +# def cal_similarity( +# key_states, +# ): +# # key_states shape: [kv_len, kv_heads, head_dim] +# start = time.time() +# k = key_states.permute(1, 0, 2).to('cuda') # shape: [kv_heads, kv_len, head_dim] +# num_heads = k.shape[0] + +# k_norm = k / (k.norm(dim=-1, keepdim=True) + 1e-8) +# similarity_cos = torch.matmul(k_norm, k_norm.transpose(-1, -2)).to('cpu') + +# for h in range(num_heads): +# similarity_cos[h].fill_diagonal_(0.0) + +# end = time.time() +# return similarity_cos.mean(dim=1).softmax(dim=-1) + + +def cal_similarity( + key_states, +): + # [kv_len, H, D] → [H, kv_len, D] + k = key_states.permute(1, 0, 2).to('cuda') + H, L, D = k.shape + + # L2 normalize each key vector per head + k_norm = k / (k.norm(dim=-1, keepdim=True) + 1e-8) # [H, L, D] + + # Step 1: Compute sum of all keys per head → [H, D] + k_sum = k_norm.sum(dim=1) # Σ_j k_j + + # Step 2: For each key i, compute k_i ⋅ (Σ_j k_j) → [H, L] + # That is: (k_norm @ k_sum.T) → use bmm for batch + # k_norm: [H, L, D], k_sum.unsqueeze(-1): [H, D, 1] → bmm → [H, L, 1] + dot_with_sum = torch.bmm(k_norm, k_sum.unsqueeze(-1)).squeeze(-1) # [H, L] + + # Step 3: Apply correction for diagonal (since cos(k_i, k_i) = 1 was included in sum) + # Original: fill_diagonal_(0) then mean(dim=1) ⇒ (total_sum - 1) / L + if L == 1: + mean_sim = torch.zeros(H, 1, device=k.device) # or handle specially + else: + mean_sim = (dot_with_sum - 1.0) / L # [H, L] ← strictly equivalent to original + + avg_sim = mean_sim + + # Step 5: Softmax → final importance-like distribution + result = avg_sim.softmax(dim=-1).to('cpu') # move small result to CPU + + return result + + +class ChunkKVRangeTracker: + def __init__(self, total_cache_len: int, clip_token_nums: int, max_batch_size: int): + self.total_cache_len = total_cache_len + self.clip_token_nums = clip_token_nums + self.max_batch_size = max_batch_size + self.tokens_per_chunk = clip_token_nums * max_batch_size + self.chunk_ranges: Dict[int, Tuple[int, int]] = {} # chunk_id -> (start, end) + self.next_free_idx = 0 # For sequential allocation when not compressed + self.registered_chunks_ordered: List[int] = [] # Maintain registration order for compression and concatenation + + def register_chunks(self, chunk_ids: List[int]): + """Batch register multiple chunks and allocate original space""" + for cid in chunk_ids: + if cid in self.chunk_ranges: + continue + start = self.next_free_idx + end = start + self.tokens_per_chunk + if end > self.total_cache_len: + import pdb; pdb.set_trace() + raise ValueError("KV cache is full") + self.chunk_ranges[cid] = (start, end) + self.registered_chunks_ordered.append(cid) + self.next_free_idx = end + + def get_range(self, chunk_id: int) -> Tuple[int, int]: + if chunk_id not in self.chunk_ranges: + raise KeyError(f"Chunk {chunk_id} not registered. Call register_chunks first.") + return self.chunk_ranges[chunk_id] + + def get_all_ranges_previous(self, current_chunk_ids: List[int]) -> List[Tuple[int, int]]: + # Get KV ranges of all previous chunks + ranges = [] + if len(current_chunk_ids) > 0: + min_chunk_id = min(current_chunk_ids) + for cid in self.registered_chunks_ordered: + if cid >= min_chunk_id: + continue + ranges.append(self.chunk_ranges[cid]) + else: + # To adapt to MAGI-1's original logic, should return ranges of all registered chunks + for cid in self.registered_chunks_ordered: + ranges.append(self.chunk_ranges[cid]) + return ranges + + def get_all_chunk_ids(self) -> List[int]: + return self.registered_chunks_ordered.copy() + + def update_ranges_after_compression(self, new_ranges: Dict[int, Tuple[int, int]]): + """Update each chunk's range based on actual compressed length""" + # Update chunk_ranges + for cid, (start, end) in new_ranges.items(): + if cid in self.chunk_ranges: + self.chunk_ranges[cid] = (start, end) + + # Update next_free_idx to maximum end + if new_ranges: + self.next_free_idx = max(end for start, end in new_ranges.values()) + else: + self.next_free_idx = 0 \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/memory_monitor.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/memory_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..9683d610e823b035b65281e81fdbdb1d1203833c --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/memory_monitor.py @@ -0,0 +1,195 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import time +from typing import List, Optional, Dict, Any +import logging + +class MemoryMonitor: + """ + Enhanced memory monitor for tracking tensor memory usage + """ + + def __init__(self, log_file: Optional[str] = None, enable_logging: bool = True): + self.log_file = log_file + self.enable_logging = enable_logging + self.peak_memory_usage = 0.0 + self.memory_history = [] + + # Setup logging + if self.enable_logging: + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file) if log_file else logging.StreamHandler(), + logging.StreamHandler() + ] + ) + self.logger = logging.getLogger(__name__) + + def get_tensor_memory_info(self, tensor_list: List[Any], unit: str = 'MB') -> Dict[str, Any]: + """ + Get detailed memory information for a list of tensors + """ + total_bytes = 0 + non_null_tensors = 0 + tensor_shapes = [] + tensor_devices = [] + + for i, t in enumerate(tensor_list): + if isinstance(t, torch.Tensor): + non_null_tensors += 1 + tensor_shapes.append(t.shape) + tensor_devices.append(str(t.device)) + + if t.is_cuda: + total_bytes += t.element_size() * t.numel() + else: + tensor_shapes.append(None) + tensor_devices.append(None) + + # Convert to requested unit + unit = unit.upper() + scale_dict = { + 'B': 1, + 'KB': 1024, + 'MB': 1024 ** 2, + 'GB': 1024 ** 3, + } + scale = scale_dict[unit] + + return { + 'total_memory_mb': total_bytes / scale, + 'total_memory_gb': total_bytes / (scale_dict['GB']), + 'total_elements': sum(t.numel() for t in tensor_list if isinstance(t, torch.Tensor) and t.is_cuda), + 'non_null_count': non_null_tensors, + 'total_count': len(tensor_list), + 'tensor_shapes': tensor_shapes, + 'tensor_devices': tensor_devices, + 'utilization_rate': non_null_tensors / len(tensor_list) if tensor_list else 0 + } + + def monitor_residual_memory(self, previous_residual: List[Any], + step: int, chunk_info: Optional[Dict] = None, + log_immediately: bool = True) -> Dict[str, Any]: + """ + Monitor memory usage of previous_residual specifically + """ + memory_info = self.get_tensor_memory_info(previous_residual, unit='MB') + memory_info['step'] = step + memory_info['timestamp'] = time.time() + + if chunk_info: + memory_info.update(chunk_info) + + # Track peak memory + if memory_info['total_memory_mb'] > self.peak_memory_usage: + self.peak_memory_usage = memory_info['total_memory_mb'] + memory_info['is_peak'] = True + else: + memory_info['is_peak'] = False + + # Store history + self.memory_history.append(memory_info) + + # Log if requested + if log_immediately and self.enable_logging: + self._log_memory_info(memory_info) + + return memory_info + + def _log_memory_info(self, memory_info: Dict[str, Any]): + """ + Log memory information in a formatted way + """ + msg = ( + f"Step {memory_info['step']:3d} | " + f"Residual Memory: {memory_info['total_memory_mb']:6.2f} MB | " + f"Tensors: {memory_info['non_null_count']:2d}/{memory_info['total_count']:2d} | " + f"Utilization: {memory_info['utilization_rate']*100:5.1f}%" + ) + + if memory_info['is_peak']: + msg += " | [NEW PEAK]" + + self.logger.info(msg) + + # Log detailed tensor shapes for debugging + if memory_info['non_null_count'] > 0: + shapes_str = ", ".join([str(s) for s in memory_info['tensor_shapes'] if s is not None]) + self.logger.debug(f" Tensor shapes: {shapes_str}") + + def get_memory_summary(self) -> Dict[str, Any]: + """ + Get summary of memory usage over time + """ + if not self.memory_history: + return {'error': 'No memory history available'} + + memory_values = [h['total_memory_mb'] for h in self.memory_history] + + return { + 'peak_memory_mb': max(memory_values), + 'average_memory_mb': sum(memory_values) / len(memory_values), + 'min_memory_mb': min(memory_values), + 'total_steps': len(self.memory_history), + 'peak_step': max(self.memory_history, key=lambda x: x['total_memory_mb'])['step'], + 'final_memory_mb': memory_values[-1] if memory_values else 0, + 'memory_growth': memory_values[-1] - memory_values[0] if len(memory_values) > 1 else 0 + } + + def save_memory_report(self, filename: str): + """ + Save detailed memory report to file + """ + import json + + summary = self.get_memory_summary() + report = { + 'summary': summary, + 'detailed_history': self.memory_history, + 'peak_memory_gb': self.peak_memory_usage / 1024 + } + + with open(filename, 'w') as f: + json.dump(report, f, indent=2, default=str) + + print(f"Memory report saved to: {filename}") + + def reset(self): + """ + Reset monitor state + """ + self.peak_memory_usage = 0.0 + self.memory_history = [] + +# Global monitor instance +_global_monitor = None + +def get_memory_monitor() -> MemoryMonitor: + """Get or create global memory monitor""" + global _global_monitor + if _global_monitor is None: + _global_monitor = MemoryMonitor() + return _global_monitor + +def monitor_residual_memory_step(previous_residual: List[Any], step: int, + chunk_info: Optional[Dict] = None) -> Dict[str, Any]: + """ + Convenience function to monitor a single step + """ + monitor = get_memory_monitor() + return monitor.monitor_residual_memory(previous_residual, step, chunk_info) \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/motioncache.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/motioncache.py new file mode 100644 index 0000000000000000000000000000000000000000..0f7ab16951913aa54d5e3bf19846351c03e3524a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/motioncache.py @@ -0,0 +1,848 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +MotionCache implementation: Motion-aware token-wise cache reuse + KV compression. + +This module provides MotionCache (Xu et al., 2026), which extends FlowCache with: +- Phase 1: chunk-wise binary reuse for structural warm-up (K steps) +- Phase 2: motion-weighted token accumulation and selective residual reuse +- KVCacheCompressor: Dynamic KV cache compression for memory efficiency +""" + +import argparse +import gc +import os +import sys +import torch +from types import MethodType + +from inference.pipeline import MagiPipeline +from inference.pipeline.video_generate import SampleTransport, find_dit_model +from inference.pipeline.cache import KVCacheCompressor +from inference.pipeline.cache.motioncache import MotionWiseCache +from inference.pipeline.cache.sparse_utils import ( + build_sparse_meta_args, + latent_mask_to_patch_mask, + patch_mask_to_flat_indices, + sparse_gather_sequence, + sparse_scatter_sequence, +) +from inference.pipeline.cache.utils import ( + generate_dynamic_kv_range, + get_embedding_and_meta_with_chunk_info, +) +from inference.pipeline.kvcompress import replace_magi +from inference.pipeline.kvcompress.utils import ChunkKVRangeTracker + + +def setup_motioncache( + rel_l1_thresh: float = 0.015, + warmup_steps: int = 5, + phase1_steps: int = 9, + alpha: float = 0.5, + discard_nearly_clean_chunk: bool = False, + log: bool = False, + total_cache_chunk_nums: int = 5, + compress_kv_cache: bool = True, + metric_stats_path: str = None, +): + """ + Set up MotionCache with coarse-to-fine reuse and KV compression. + + Args: + rel_l1_thresh: Token accumulator threshold (tau) + warmup_steps: Global warm-up steps with reuse disabled (m) + phase1_steps: Chunk-wise phase duration (K) + alpha: Soft-mapping floor for static tokens + discard_nearly_clean_chunk: Whether to skip nearly-clean chunk + log: Whether to log reuse decisions + total_cache_chunk_nums: Total number of chunks to cache + compress_kv_cache: Whether to enable KV cache compression + """ + SampleTransport.cache_reuse_manager = MotionWiseCache( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + phase1_steps=phase1_steps, + alpha=alpha, + discard_nearly_clean_chunk=discard_nearly_clean_chunk, + log=log, + metric_stats_path=metric_stats_path, + ) + + SampleTransport.kv_compress_manager = None + + SampleTransport.forward_velocity = motioncache_forward_velocity + SampleTransport.integrate_velocity = motioncache_integrate_velocity + SampleTransport.total_cache_chunk_nums = total_cache_chunk_nums + SampleTransport.compress_kv_cache = compress_kv_cache + + +def motioncache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> dict: + """ + Forward pass with per-chunk TeaCache and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + + Returns: + Dictionary mapping chunk_id to velocity tensor + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + + # 2. Initialize KV cache tracking if needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + if not hasattr(self.inference_params[infer_idx], 'kv_chunk_tracker'): + self.inference_params[infer_idx].kv_chunk_tracker = ChunkKVRangeTracker( + total_cache_len=total_cache_len, + clip_token_nums=chunk_token_nums, + max_batch_size=1 + ) + + if not hasattr(self, 'chunk_query_states'): + self.chunk_query_states = {} + + # 3. Initialize chunk state + cache.initialize_chunk_state(transport_input.chunk_num) + + # 4. Extract denoising status + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + self.current_chunk_offset = chunk_offset + + # 5. Prepare model kwargs + model_kwargs = dict( + chunk_width=self.chunk_width, + fwd_extra_1st_chunk=False, + num_steps=transport_input.num_steps + ) + if hasattr(self, "debug"): + model_kwargs["debug"] = self.debug + model_kwargs.update({ + "denoise_step_per_stage": denoise_step_per_stage, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_num": transport_input.chunk_num + }) + + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + model_kwargs.update({ + "compress_kv": True, + "total_cache_len": total_cache_len + }) + else: + model_kwargs["save_kvcache_every_forward"] = True + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 6. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update({ + "slice_point": chunk_start, + "range_num": chunk_end, + "denoising_range_num": chunk_end - chunk_start + }) + model_kwargs["chunk_token_nums"] = chunk_token_nums + + # 7. Prepare timesteps + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + # 8. Generate KV range + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 9. Pad prefix video if needed + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 10. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + # Initialize step counter + cache.set_total_steps(model_kwargs["total_num_steps"]) + + # Setup monkey-patched model forward + model = find_dit_model(self.model) + model.forward = MethodType(_create_motioncache_model_forward_fn(cache, self, infer_idx), model) + model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model) + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + +def _create_motioncache_model_forward_fn(cache: MotionWiseCache, transport, infer_idx: int): + """ + Create a model forward function with MotionCache chunk/token reuse logic. + """ + @torch.no_grad() + def model_forward( + model_self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params=None, + **kwargs, + ) -> dict: + raw_x = x.clone() + + # 1. Compute feature metrics per chunk + # Following source code: compute metric_x first, handle slicing, then split + metric_chunks, num_chunks = cache.compute_feature_metric( + x=x, + x_embedder=model_self.x_embedder, + x_rescale_factor=model_self.model_config.x_rescale_factor, + half_channel_vae=model_self.model_config.half_channel_vae, + chunk_token_nums=kwargs["chunk_token_nums"], + params_dtype=model_self.model_config.params_dtype, + offset=kwargs['slice_point'], + fwd_extra_1st_chunk=kwargs.get("fwd_extra_1st_chunk", False), + distill_nearly_clean_chunk=kwargs.get("distill_nearly_clean_chunk", False) + ) + + # 2. Update kwargs + cache.total_num_steps = kwargs['total_num_steps'] + denoise_step_per_stage = kwargs['denoise_step_per_stage'] + kwargs['cur_denoise_step'] = cache.cnt + model_self.cur_denoise_step = cache.cnt + + # 3. Split x into chunks (using num_chunks from metric_x, matching source code) + chunk_width = kwargs["chunk_width"] + offset = kwargs['slice_point'] + x_chunks = {} + # Artifact chunks in x are not included - following source code comment + for i in range(num_chunks): + start_idx = i * chunk_width + end_idx = start_idx + chunk_width + x_chunks[offset + i] = x[:, :, start_idx:end_idx] + + # 4. Handle nearly clean chunk (artifact chunk) - add separately AFTER normal chunks + # Following source code logic + model_self.discard_nearly_clean_chunk = cache.discard_nearly_clean_chunk + near_clean_chunk_idx = -1 + if not cache.discard_nearly_clean_chunk and kwargs.get("distill_nearly_clean_chunk", False): + # Add artifact chunk - following source code comment + near_clean_chunk_idx = max(x_chunks.keys()) + 1 + model_self.near_clean_chunk_idx = near_clean_chunk_idx + x_chunks[near_clean_chunk_idx] = x[:, :, -chunk_width:] + + # 5. Determine which chunks to reuse (Phase 1: chunk-wise; Phase 2: token-wise) + chunk_offset = getattr(transport, "current_chunk_offset", 0) + chunk_denoise_count = transport.chunk_denoise_count[infer_idx] + if cache.cnt != 0 and cache.cnt != cache.num_steps - 1: + current_num_chunks = len(metric_chunks) + previous_num_chunks = len(cache.prev_metric_chunks) + common_keys = set(metric_chunks.keys()) & set(cache.prev_metric_chunks.keys()) + + for i in sorted(common_keys): + if cache.in_phase1(i, chunk_denoise_count): + should_reuse = cache.should_reuse( + chunk_id=i, + step=cache.cnt, + current_features=metric_chunks, + chunk_denoise_count=transport.chunk_denoise_count[infer_idx], + current_num_chunks=current_num_chunks, + previous_num_chunks=previous_num_chunks, + infer_idx=infer_idx, + cur_denoise_step=cache.cnt, + denoise_stage=kwargs.get("denoise_stage"), + denoise_idx=kwargs.get("denoise_idx"), + chunk_offset=chunk_offset, + chunk_denoise_count_value=transport.chunk_denoise_count[infer_idx][i], + ) + cache.chunk_reuse_flags[i] = should_reuse + else: + token_mask = cache.update_token_policy( + chunk_id=i, + x_chunk=x_chunks[i], + current_features=metric_chunks[i], + chunk_offset=chunk_offset, + chunk_denoise_count=chunk_denoise_count, + ) + skip_forward = not token_mask.any() + cache.chunk_reuse_flags[i] = skip_forward + cache.chunk_sparse_flags[i] = ( + not skip_forward and not token_mask.all() + ) + if cache.log: + active_ratio = token_mask.float().mean().item() + phase = "phase1" if cache.in_phase1(i, chunk_denoise_count) else "phase2" + print( + f"MotionCache {phase} step {cache.cnt} chunk {i} " + f"(denoise={chunk_denoise_count[i]}): " + f"active_ratio={active_ratio:.2%}, skip_forward={skip_forward}" + ) + + for i in sorted(x_chunks.keys()): + cache.store_latent_chunk(i, x_chunks[i]) + + # 6. Remove nearly clean chunk if first chunk can be reused + if cache.chunk_reuse_flags.get(kwargs["slice_point"], False) and near_clean_chunk_idx != -1: + x_chunks.pop(near_clean_chunk_idx, None) + + # 7. Store previous features + cache.store_previous_features(metric_chunks) + + # 8. Forward chunks that are not reused + current_infer_outputs = {} + + for i in sorted(x_chunks.keys()): + if i in cache.chunk_reuse_flags and cache.chunk_reuse_flags[i]: + continue + + x_i = x_chunks[i] + # Handle near_clean_chunk_idx: use last chunk of t, y, xattn_mask + if i == near_clean_chunk_idx: + t_i = t[:, -1:] + y_i = y[-1:] + xattn_mask_i = xattn_mask[-1:] + else: + t_i = t[:, i - offset:i - offset + 1] + y_i = y[i - offset:i - offset + 1] + xattn_mask_i = xattn_mask[i - offset:i - offset + 1] + + kwargs["start_chunk_id"] = i + kwargs["end_chunk_id"] = i + 1 + kwargs["denoising_range_num"] = 1 + + if i == near_clean_chunk_idx: + kwargs["distill_nearly_clean_chunk"] = True + else: + kwargs["distill_nearly_clean_chunk"] = False + + # Update KV range if compressed + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + if inference_params.kv_compressed: + kv_range = generate_dynamic_kv_range( + tracker=inference_params.kv_chunk_tracker, + current_chunk_id=i, + x_chunks_keys=list(x_chunks.keys()), + chunk_token_nums=kwargs["chunk_token_nums"], + near_clean_chunk_idx=near_clean_chunk_idx + ) + + kwargs["near_clean_chunk_idx"] = near_clean_chunk_idx + (processed_x, condition, condition_map, y_xattn_flat, rope, meta_args) = \ + model_self.forward_pre_process( + x_i, t_i, y_i, caption_dropout_mask, xattn_mask_i, kv_range, **kwargs + ) + + if not model_self.pre_process: + from inference.pipeline.parallelism import pp_scheduler + processed_x = pp_scheduler().recv_prev_data(processed_x.shape, processed_x.dtype) + model_self.videodit_blocks.set_input_tensor(processed_x) + else: + processed_x = processed_x.clone() + + use_sparse = cache.chunk_sparse_flags.get(i, False) + token_mask_i = cache.get_token_mask(i, chunk_denoise_count) + embed_hidden = processed_x + + try: + if use_sparse and token_mask_i is not None: + patch_mask = latent_mask_to_patch_mask( + token_mask_i, + patch_size=model_self.model_config.patch_size, + ) + active_indices = patch_mask_to_flat_indices(patch_mask[0]) + if active_indices.numel() == 0: + raise RuntimeError(f"Sparse flag set but no active tokens for chunk {i}") + + sparse_meta = build_sparse_meta_args( + meta_args, + active_indices=active_indices, + total_tokens=processed_x.size(0), + ) + hidden_active, cond_map_active, rope_active = sparse_gather_sequence( + processed_x, condition_map, rope, active_indices + ) + out_active = model_self.videodit_blocks.forward( + hidden_states=hidden_active, + condition=condition, + condition_map=cond_map_active, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope_active, + inference_params=inference_params, + meta_args=sparse_meta, + ) + out = sparse_scatter_sequence(embed_hidden, out_active, active_indices) + else: + out = model_self.videodit_blocks.forward( + hidden_states=processed_x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + except Exception: + raise + + # Store query states for compression + if hasattr(transport, 'compress_kv_cache') and transport.compress_kv_cache: + for layer in model_self.videodit_blocks.layers: + layer_num = layer.self_attention.layer_number + if hasattr(layer.self_attention, '_last_query'): + transport.chunk_query_states[layer_num] = layer.self_attention._last_query + + if not model_self.post_process: + from inference.pipeline.parallelism import pp_scheduler + pp_scheduler().isend_next(out) + + out = model_self.forward_post_process(out, meta_args) + cache.previous_velocity[i] = out.clone().detach() + current_infer_outputs[i] = out.clone().detach() + + return current_infer_outputs + + return model_forward + + +@torch.no_grad() +def _new_get_embedding_and_meta(model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs): + """Monkey-patched version of get_embedding_and_meta with chunk info.""" + return get_embedding_and_meta_with_chunk_info( + model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + +def motioncache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + """ + Integrate velocity with per-chunk cache residual handling and KV compression. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + """ + # Get cache from class attribute + cache = SampleTransport.cache_reuse_manager + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + chunk_num = x_chunk.shape[2] // self.chunk_width + offset = chunk_start + ori_x_chunk = x_chunk.clone() + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + next_t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=False + ) + x_embedder_before = None + x_embedder_after = None + x_embedder_chunk_width = None + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(ori_x_chunk) + + # Split into chunks + x_chunks = {} + for i in range(chunk_num): + start_idx = i * self.chunk_width + end_idx = start_idx + self.chunk_width + x_chunks[offset + i] = x_chunk[:, :, start_idx:end_idx] + + # Integrate per chunk + for i in range(chunk_num): + chunk_id = offset + i + reused = cache.chunk_reuse_flags.get(chunk_id, False) + token_mask = cache.get_token_mask(chunk_id, chunk_denoise_count) + active_ratio = None + if token_mask is not None: + active_ratio = token_mask.float().mean().item() + + cache.record_motion_decision( + chunk_id=chunk_id, + reused=reused, + active_ratio=active_ratio, + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_denoise_count=chunk_denoise_count, + chunk_denoise_count_value=chunk_denoise_count[chunk_id], + ) + cache.record_actual_execution( + chunk_id=chunk_id, + reused=reused, + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + ) + + slice_start = i * self.chunk_width + slice_end = (i + 1) * self.chunk_width + ori_slice = ori_x_chunk[:, :, slice_start:slice_end] + + if reused: + x_chunk[:, :, slice_start:slice_end] += cache.previous_residual[chunk_id] + elif token_mask is not None and cache.previous_residual.get(chunk_id) is not None: + assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs" + integrated = self.integrate( + x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx], + denoise_step_per_stage, t_start, t_end, denoise_idx, i, + ) + prev_residual = cache.previous_residual[chunk_id] + mask = token_mask.unsqueeze(1).to(dtype=ori_slice.dtype) + updated = ori_slice + mask * (integrated - ori_slice) + (1.0 - mask) * prev_residual + x_chunk[:, :, slice_start:slice_end] = updated + new_residual = updated - ori_slice + cache.previous_residual[chunk_id] = ( + mask * new_residual + (1.0 - mask) * prev_residual + ) + cache.reset_token_accumulator(chunk_id, token_mask) + else: + assert chunk_id in velocity, f"Chunk {chunk_id} not in velocity outputs" + x_chunk[:, :, slice_start:slice_end] = \ + self.integrate(x_chunks[chunk_id], velocity[chunk_id], self.ts[infer_idx], + denoise_step_per_stage, t_start, t_end, denoise_idx, i) + cache.previous_residual[chunk_id] = \ + x_chunk[:, :, slice_start:slice_end] - ori_slice + if token_mask is not None: + cache.reset_token_accumulator(chunk_id, token_mask) + + applied_residual = x_chunk - ori_x_chunk + self.residual_diff_tracker.update_residuals( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + residual=applied_residual, + timesteps=t, + chunk_width=self.chunk_width, + ) + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk) + self.l1_rel_change_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_before=ori_x_chunk, + x_after=x_chunk, + timesteps=t, + next_timesteps=next_t, + chunk_width=self.chunk_width, + x_embedder_before=x_embedder_before, + x_embedder_after=x_embedder_after, + x_embedder_chunk_width=x_embedder_chunk_width, + ) + + # Increment step counter + cache.increment_step() + + # Update chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # Check if KV compression is needed + if hasattr(self, 'compress_kv_cache') and self.compress_kv_cache: + _check_and_compress_kv(self, infer_idx, chunk_start, transport_input) + + # Return clean chunk if ready + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + return _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset) + + return None, None + + +def _check_and_compress_kv(self, infer_idx: int, chunk_start: int, transport_input): + """Check and perform KV cache compression if needed.""" + inference_params = self.inference_params[infer_idx] + tracker = inference_params.kv_chunk_tracker + + total_cache_len = self.total_cache_chunk_nums * ( + self.chunk_width * + (transport_input.latent_size[3] // self.model_config.patch_size) * + (transport_input.latent_size[4] // self.model_config.patch_size) + ) + + # Get or create compressor from class attribute + compressor = SampleTransport.kv_compress_manager + if compressor is None: + chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx)[1] + compressor = KVCacheCompressor( + total_cache_len=total_cache_len, + tokens_per_chunk=chunk_token_nums, + budget_chunk_nums=self.total_cache_chunk_nums - 1, + window_size=self.window_size + ) + SampleTransport.kv_compress_manager = compressor + + # Check if compression needed + if compressor.should_compress( + tracker=tracker, + chunk_num=transport_input.chunk_num, + chunk_start=chunk_start, + transport_input=transport_input, + chunk_denoise_count=self.chunk_denoise_count[infer_idx] + ): + compressor.compress( + model=find_dit_model(self.model), + inference_params=inference_params, + tracker=tracker, + transport_input=transport_input, + chunk_start=chunk_start, + chunk_denoise_count=self.chunk_denoise_count[infer_idx], + query_states_dict=self.chunk_query_states + ) + + +def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset): + """Return the clean chunk if denoising is complete.""" + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + + +def load_config(config_path: str) -> dict: + """Load configuration from JSON or YAML file.""" + _, ext = os.path.splitext(config_path) + with open(config_path, 'r') as f: + if ext == '.json': + import json + return json.load(f) + elif ext in ['.yaml', '.yml']: + import yaml + return yaml.safe_load(f) + else: + raise ValueError(f"Unsupported config file extension: {ext}") + + +def parse_arguments(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Run MagiPipeline with MotionCache.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], + required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument('--additional_config', type=str, help='Path to additional config file.') + parser.add_argument( + '--residual_stats_path', + type=str, + help='Optional path to save per-chunk residual-difference norm stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--l1_rel_stats_path', + type=str, + help='Optional path to save per-chunk relative L1 change stats as .json, .pt, or .pth.', + ) + parser.add_argument( + '--motioncache_metric_stats_path', + type=str, + help='Optional path to save MotionCache reuse metric stats as .json, .pt, or .pth.', + ) + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.') + + return parser.parse_args() + + +def main(): + """Main entry point.""" + args = parse_arguments() + + # Load additional config + if args.additional_config: + additional_config = load_config(args.additional_config) + print(f"Loading additional config: {additional_config}") + + for key, value in additional_config.items(): + setattr(args, key, value) + print(f"Added to args: {key} = {value}") + + # Handle parameter name compatibility + if hasattr(args, 'no_reuse_first_n_steps') and not hasattr(args, 'warmup_steps'): + args.warmup_steps = args.no_reuse_first_n_steps + if hasattr(args, 'no_reuse_mode'): + # no_reuse_mode is deprecated, ignore it + pass + else: + print("No additional config provided.") + + if args.print_peak_memory: + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB") + else: + print("CUDA not available, running on CPU") + + # Setup MotionCache + setup_motioncache( + rel_l1_thresh=args.rel_l1_thresh, + warmup_steps=args.warmup_steps, + phase1_steps=getattr(args, 'phase1_steps', 9), + alpha=getattr(args, 'alpha', 0.5), + discard_nearly_clean_chunk=args.discard_nearly_clean_chunk, + log=args.log, + total_cache_chunk_nums=args.total_cache_chunk_nums, + compress_kv_cache=args.compress_kv_cache, + metric_stats_path=args.motioncache_metric_stats_path, + ) + + # Setup KV compression in model + compression_config = { + "method_config": { + "compress_strategy": getattr(args, 'compress_strategy', 'token'), + "mix_lambda": getattr(args, 'mix_lambda', 0.07), + "query_granularity": getattr(args, 'query_granularity', 'chunk'), + "score_weighting_method": getattr(args, 'score_weighting_method', None) or 'no_weight', + "power": getattr(args, 'power', 3), + }, + } + replace_magi(compression_config) + + # Run pipeline + pipeline = MagiPipeline( + args.config_file, + residual_stats_path=args.residual_stats_path, + l1_rel_stats_path=args.l1_rel_stats_path, + ) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video( + prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path + ) + + if args.print_peak_memory: + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "=" * 50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("=" * 50) + + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/pipeline.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8e57a06894507ec482078c6b924d566b6c21cc37 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/pipeline.py @@ -0,0 +1,71 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch +from typing import Optional + +from inference.common import MagiConfig, print_rank_0, set_random_seed +from inference.infra.distributed import dist_init +from inference.model.dit import get_dit + +from .prompt_process import get_txt_embeddings +from .video_generate import generate_per_chunk +from .video_process import post_chunk_process, process_image, process_prefix_video, save_video_to_disk + + +class MagiPipeline: + def __init__(self, config_path, residual_stats_path: Optional[str] = None, l1_rel_stats_path: Optional[str] = None): + self.config = MagiConfig.from_json(config_path) + self.residual_stats_path = residual_stats_path + self.l1_rel_stats_path = l1_rel_stats_path + set_random_seed(self.config.runtime_config.seed) + dist_init(self.config) + print_rank_0(self.config) + + def run_text_to_video(self, prompt: str, output_path: str): + self._run(prompt, None, output_path) + + def run_image_to_video(self, prompt: str, image_path: str, output_path: str): + prefix_video = process_image(image_path, self.config) + self._run(prompt, prefix_video, output_path) + + def run_video_to_video(self, prompt: str, prefix_video_path: str, output_path: str): + prefix_video = process_prefix_video(prefix_video_path, self.config) + self._run(prompt, prefix_video, output_path) + + def _run(self, prompt: str, prefix_video: torch.Tensor, output_path: str): + caption_embs, emb_masks = get_txt_embeddings(prompt, self.config) # caption_embs: [1, 1, 800, 4096], emb_masks: [1, 800] + dit = get_dit(self.config) + videos = torch.cat( + [ + post_chunk_process(chunk, self.config) + for chunk in generate_per_chunk( + model=dit, + prefix_video=prefix_video, + caption_embs=caption_embs, + emb_masks=emb_masks, + residual_stats_path=self.residual_stats_path, + l1_rel_stats_path=self.l1_rel_stats_path, + ) + ], + dim=0, + ) + save_video_to_disk(videos, output_path, fps=self.config.runtime_config.fps) + + mem_allocated_gb = torch.cuda.max_memory_allocated() / 1024**3 + mem_reserved_gb = torch.cuda.max_memory_reserved() / 1024**3 + print_rank_0( + f"Finish MagiPipeline, max memory allocated: {mem_allocated_gb:.2f} GB, max memory reserved: {mem_reserved_gb:.2f} GB" + ) diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/prompt_process.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/prompt_process.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae9e712d6eee5616f13f29ee2711acb706d9ea3 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/prompt_process.py @@ -0,0 +1,209 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import gc +import os +from typing import List + +import numpy as np +import torch + +from inference.common import MagiConfig, env_is_true, magi_logger +from inference.infra.distributed import is_last_tp_cp_rank +from inference.infra.distributed import parallel_state as mpu +from inference.model.t5 import T5Embedder + +SPECIAL_TOKEN_PATH = os.getenv("SPECIAL_TOKEN_PATH", "example/assets/special_tokens.npz") +SPECIAL_TOKEN = np.load(SPECIAL_TOKEN_PATH) +CAPTION_TOKEN = torch.tensor(SPECIAL_TOKEN["caption_token"].astype(np.float16)) +LOGO_TOKEN = torch.tensor(SPECIAL_TOKEN["logo_token"].astype(np.float16)) +TRANS_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][:1].astype(np.float16)) +HQ_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][1:2].astype(np.float16)) +STATIC_FIRST_FRAMES_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][2:3].astype(np.float16)) # static first frames +DYNAMIC_FIRST_FRAMES_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][3:4].astype(np.float16)) # dynamic first frames +BORDERNESS_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][4:5].astype(np.float16)) +DURATION_TOKEN_LIST = [torch.tensor(SPECIAL_TOKEN["other_tokens"][i : i + 1].astype(np.float16)) for i in range(0 + 7, 8 + 7)] +THREE_D_MODEL_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][15:16].astype(np.float16)) +TWO_D_ANIME_TOKEN = torch.tensor(SPECIAL_TOKEN["other_tokens"][16:17].astype(np.float16)) + +SPECIAL_TOKEN_DICT = { + "CAPTION_TOKEN": CAPTION_TOKEN, + "LOGO_TOKEN": LOGO_TOKEN, + "TRANS_TOKEN": TRANS_TOKEN, + "HQ_TOKEN": HQ_TOKEN, + "STATIC_FIRST_FRAMES_TOKEN": STATIC_FIRST_FRAMES_TOKEN, + "DYNAMIC_FIRST_FRAMES_TOKEN": DYNAMIC_FIRST_FRAMES_TOKEN, + "BORDERNESS_TOKEN": BORDERNESS_TOKEN, + "THREE_D_MODEL_TOKEN": THREE_D_MODEL_TOKEN, + "TWO_D_ANIME_TOKEN": TWO_D_ANIME_TOKEN, +} + +for i, token in enumerate(DURATION_TOKEN_LIST): + # DURATION_TOKEN_N represents N chunk(s) remain in the future + SPECIAL_TOKEN_DICT[f"DURATION_TOKEN_{i+1}"] = token + + +def pad_duration_token_keys(special_token_keys: List[str]) -> List[str]: + if "DURATION_TOKEN" in set(special_token_keys): + return special_token_keys + + if env_is_true("PAD_DURATION"): + return special_token_keys + ["DURATION_TOKEN"] + return special_token_keys + + +def get_special_token_keys() -> List[str]: + special_token_keys = [] + if env_is_true("PAD_STATIC"): + special_token_keys.append("STATIC_FIRST_FRAMES_TOKEN") + if env_is_true("PAD_DYNAMIC"): + special_token_keys.append("DYNAMIC_FIRST_FRAMES_TOKEN") + if env_is_true("PAD_BORDERNESS"): + special_token_keys.append("BORDERNESS_TOKEN") + if env_is_true("PAD_HQ"): + special_token_keys.append("HQ_TOKEN") + if env_is_true("PAD_THREE_D_MODEL"): + special_token_keys.append("THREE_D_MODEL_TOKEN") + if env_is_true("PAD_TWO_D_ANIME"): + special_token_keys.append("TWO_D_ANIME_TOKEN") + + special_token_keys = pad_duration_token_keys(special_token_keys) + return special_token_keys + + +def get_negative_special_token_keys() -> List[str]: + if env_is_true("NEG_PROMPT"): + return ["CAPTION_TOKEN", "LOGO_TOKEN", "TRANS_TOKEN", "BORDERNESS_TOKEN"] + return None + + +def _pad_special_token(special_token: torch.Tensor, txt_feat: torch.Tensor, attn_mask: torch.Tensor = None): + _device = txt_feat.device + _dtype = txt_feat.dtype + N, C, _, D = txt_feat.size() + txt_feat = torch.cat( + [special_token.unsqueeze(0).unsqueeze(0).to(_device).to(_dtype).expand(N, C, -1, D), txt_feat], dim=2 + )[:, :, :800, :] + if attn_mask is not None: + attn_mask = torch.cat([torch.ones(N, C, 1, dtype=_dtype, device=_device), attn_mask], dim=-1)[:, :, :800] + return txt_feat, attn_mask + + +def pad_special_token(special_token_keys: List[str], caption_embs: torch.Tensor, emb_masks: torch.Tensor): + device = f"cuda:{torch.cuda.current_device()}" + if not special_token_keys: + return caption_embs, emb_masks + for special_token_key in special_token_keys: + if special_token_key == "DURATION_TOKEN": + new_caption_embs, new_emb_masks = [], [] + num_chunks = caption_embs.size(1) + for i in range(num_chunks): + chunk_caption_embs, chunk_emb_masks = _pad_special_token( + DURATION_TOKEN_LIST[min(num_chunks - i - 1, 7)].to(device), + caption_embs[:, i : i + 1], + emb_masks[:, i : i + 1], + ) + new_caption_embs.append(chunk_caption_embs) + new_emb_masks.append(chunk_emb_masks) + caption_embs = torch.cat(new_caption_embs, dim=1) + emb_masks = torch.cat(new_emb_masks, dim=1) + else: + special_token = SPECIAL_TOKEN_DICT.get(special_token_key) + if special_token is not None: + caption_embs, emb_masks = _pad_special_token(special_token.to(device), caption_embs, emb_masks) + return caption_embs, emb_masks + + +_t5_cache = None + + +def _t5(model_cache_dir, model_device, model_max_length) -> T5Embedder: + global _t5_cache + if _t5_cache is None: + _t5_model = T5Embedder( + device=model_device, + local_cache=True, + cache_dir=model_cache_dir, + torch_dtype=torch.float, + model_max_length=model_max_length, + ) + if os.environ.get("OFFLOAD_T5_CACHE") == "true": + return _t5_model + _t5_cache = _t5_model + return _t5_cache + + +def prepare_prompt_embeddings(prompts: List[str], model_cache_dir, model_device, model_max_length): + magi_logger.info("Precompute validation prompt embeddings") + cur_rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0 + magi_logger.debug( + f"rank {cur_rank} memory allocated before precompute validation prompt embeddings: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {cur_rank} memory reserved before precompute validation prompt embeddings: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + txt_embs = [] + for prompt in prompts: + with torch.no_grad(): + caption_embs, emb_masks = _t5(model_cache_dir, model_device, model_max_length).get_text_embeddings([prompt]) + caption_embs = caption_embs.float()[:, None] + txt_embs.append([caption_embs, emb_masks]) + magi_logger.debug(f"caption_embs.shape = {caption_embs.shape}") + magi_logger.debug(f"emb_masks.shape = {emb_masks.shape}") + + # put everything to CPU for future broadcast + txt_embs = [[x[0].cpu(), x[1].cpu()] for x in txt_embs] + + magi_logger.debug( + f"rank {cur_rank} memory allocated after precompute validation prompt embeddings: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {cur_rank} memory reserved after precompute validation prompt embeddings: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + gc.collect() + torch.cuda.empty_cache() + return txt_embs + + +def get_txt_embeddings(prompt: str, config: MagiConfig): + prompts = [prompt] + if not torch.distributed.is_initialized(): + txt_embs = prepare_prompt_embeddings( + prompts, + config.runtime_config.t5_pretrained, + config.runtime_config.t5_device, + config.model_config.caption_max_length, + ) + else: + if is_last_tp_cp_rank(): + txt_embs = prepare_prompt_embeddings( + prompts, + config.runtime_config.t5_pretrained, + config.runtime_config.t5_device, + config.model_config.caption_max_length, + ) + else: + txt_embs = [None] + src = mpu.get_tensor_model_parallel_last_rank(with_context_parallel=True) + group = mpu.get_tp_group(with_context_parallel=True) + torch.distributed.broadcast_object_list(txt_embs, src=src, group=group) + + # Only process one prompt + assert len(txt_embs) == 1 + caption_embs, emb_masks = txt_embs[0] + device = f"cuda:{torch.cuda.current_device()}" + caption_embs, emb_masks = caption_embs.to(device), emb_masks.to(device) + return caption_embs, emb_masks diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/teacache.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/teacache.py new file mode 100644 index 0000000000000000000000000000000000000000..fa45885f0b62ede240aee06417376f49eeb4e30d --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/teacache.py @@ -0,0 +1,519 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +TeaCache implementation for full output reuse. + +This module provides TeaCache, which reuses all model outputs together when +the accumulated relative L1 distance is below threshold. +""" + +import argparse +import gc +import sys +import torch +from types import MethodType + +from inference.pipeline import MagiPipeline +from inference.pipeline.video_generate import SampleTransport, find_dit_model +from inference.pipeline.cache import TeaCache +from inference.pipeline.cache.utils import get_embedding_and_meta_with_chunk_info + + +def setup_teacache( + rel_l1_thresh: float = 0.01, + warmup_steps: int = 0, + log: bool = False +): + """ + Set up TeaCache for SampleTransport. + + Args: + rel_l1_thresh: Relative L1 distance threshold for reuse + warmup_steps: Number of warmup steps before reuse can happen + log: Whether to log reuse decisions + """ + # Create cache instance and attach to SampleTransport + SampleTransport.cache_reuse_manager = TeaCache( + rel_l1_thresh=rel_l1_thresh, + warmup_steps=warmup_steps, + log=log + ) + + # Monkey patch the SampleTransport methods + SampleTransport.forward_velocity = teacache_forward_velocity + SampleTransport.integrate_velocity = teacache_integrate_velocity + + +def teacache_forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> torch.Tensor: + """ + Forward pass with TeaCache output reuse. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + + Returns: + Velocity tensor + """ + # Get cache from class attribute + teacache = SampleTransport.cache_reuse_manager + + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + + # 2. Extract denoising status + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + # 3. Prepare model kwargs + model_kwargs = dict( + chunk_width=self.chunk_width, + fwd_extra_1st_chunk=False, + num_steps=transport_input.num_steps + ) + model_kwargs.update({ + "denoise_step_per_stage": denoise_step_per_stage, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx + }) + + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + model_kwargs["chunk_token_nums"] = chunk_token_nums + model_kwargs["chunk_num"] = transport_input.chunk_num + model_kwargs["chunk_offset"] = chunk_offset + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 4. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update({ + "slice_point": chunk_start, + "range_num": chunk_end, + "denoising_range_num": chunk_end - chunk_start + }) + + # 5. Prepare timesteps + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=False + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + # 6. Generate KV range + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 7. Pad prefix video if needed + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 8. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + # Initialize TeaCache step counter + if teacache.cnt == 0 and teacache.num_steps == 0: + teacache.num_steps = model_kwargs["total_num_steps"] + + # Setup monkey-patched model forward + model = find_dit_model(self.model) + model.forward = MethodType(_create_model_forward_fn(teacache), model) + model.get_embedding_and_meta = MethodType(_new_get_embedding_and_meta, model) + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + mask=mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1), + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + +def _create_model_forward_fn(teacache: TeaCache): + """ + Create a model forward function with TeaCache logic. + + Args: + teacache: TeaCache instance + + Returns: + Model forward function + """ + @torch.no_grad() + def model_forward( + model_self, + x, + t, + y, + caption_dropout_mask=None, + xattn_mask=None, + kv_range=None, + inference_params=None, + **kwargs, + ) -> torch.Tensor: + raw_x = x.clone() + + # 1. Compute feature metric + metric_x = teacache.compute_feature_metric( + x=x, + x_embedder=model_self.x_embedder, + x_rescale_factor=model_self.model_config.x_rescale_factor, + half_channel_vae=model_self.model_config.half_channel_vae, + params_dtype=model_self.model_config.params_dtype + ) + + # 2. Update kwargs with TeaCache state + teacache.total_num_steps = kwargs['total_num_steps'] + denoise_step_per_stage = kwargs['denoise_step_per_stage'] + kwargs["start_chunk_id"] = kwargs['slice_point'] + kwargs["end_chunk_id"] = kwargs['range_num'] + kwargs['cur_denoise_step'] = teacache.cnt + model_self.cur_denoise_step = teacache.cnt + + if kwargs.get("distill_nearly_clean_chunk", False): + kwargs["end_chunk_id"] += 1 + + # Handle nearly clean chunk (not used in TeaCache) + if kwargs.get("fwd_extra_1st_chunk", False): + metric_x = metric_x[kwargs["chunk_token_nums"]:, :, :] + if kwargs.get("distill_nearly_clean_chunk", False): + metric_x = metric_x[:-kwargs["chunk_token_nums"], :, :] + + # 3. Check if should reuse or calculate + current_num_chunks = metric_x.shape[0] // kwargs["chunk_token_nums"] + previous_num_chunks = ( + teacache.previous_modulated_input.shape[0] // kwargs["chunk_token_nums"] + if teacache.previous_modulated_input is not None else 0 + ) + + should_reuse = teacache.should_reuse( + chunk_id=0, # Not used in TeaCache + step=teacache.cnt, + current_features=metric_x, + denoise_step_per_stage=denoise_step_per_stage, + num_chunks_current=current_num_chunks, + num_chunks_previous=previous_num_chunks + ) + + # 4. Handle partial reuse at stage boundary + if (not should_reuse and + teacache.cnt % denoise_step_per_stage == 0 and + current_num_chunks > previous_num_chunks and + teacache.accumulated_rel_l1_distance < teacache.rel_l1_thresh): + + # Only calculate new chunk + range_num = kwargs['range_num'] - kwargs['chunk_offset'] + if kwargs.get("distill_nearly_clean_chunk", False): + x = x[:, :, (range_num - 2) * kwargs['chunk_width']:(range_num - 1) * kwargs['chunk_width']] + y = y[range_num - 2:range_num - 1] + t = t[:, range_num - 2:range_num - 1] + xattn_mask = xattn_mask[range_num - 2:range_num - 1] + kwargs["start_chunk_id"] = kwargs['range_num'] - 2 + kwargs["end_chunk_id"] = kwargs['range_num'] - 1 + kwargs["denoising_range_num"] = 1 + model_self.discard_nearly_clean_chunk = True + else: + x = x[:, :, (range_num - 1) * kwargs['chunk_width']:range_num * kwargs['chunk_width']] + y = y[range_num - 1:range_num] + t = t[:, range_num - 1:range_num] + xattn_mask = xattn_mask[range_num - 1:range_num] + kwargs["start_chunk_id"] = kwargs['range_num'] - 1 + kwargs["denoising_range_num"] = 1 + + model_self.single_chunk_inference = True + model_self.denoising_range_num = kwargs["denoising_range_num"] + + # Store features for next step + teacache.store_previous_features(metric_x) + + # 5. Forward or reuse + if teacache.should_calc: + (x, condition, condition_map, y_xattn_flat, rope, meta_args) = model_self.forward_pre_process( + x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + if not model_self.pre_process: + from inference.pipeline.parallelism import pp_scheduler + x = pp_scheduler().recv_prev_data(x.shape, x.dtype) + model_self.videodit_blocks.set_input_tensor(x) + else: + x = x.clone() + + x = model_self.videodit_blocks.forward( + hidden_states=x, + condition=condition, + condition_map=condition_map, + y_xattn_flat=y_xattn_flat, + rotary_pos_emb=rope, + inference_params=inference_params, + meta_args=meta_args, + ) + + if not model_self.post_process: + from inference.pipeline.parallelism import pp_scheduler + pp_scheduler().isend_next(x) + + return model_self.forward_post_process(x, meta_args) + else: + # Reuse: return zeros (output not used) + return torch.zeros_like(raw_x) + + return model_forward + + +@torch.no_grad() +def _new_get_embedding_and_meta( + model_self, + x, + t, + y, + caption_dropout_mask, + xattn_mask, + kv_range, + **kwargs +): + """Monkey-patched version of get_embedding_and_meta with chunk info.""" + return get_embedding_and_meta_with_chunk_info( + model_self, x, t, y, caption_dropout_mask, xattn_mask, kv_range, **kwargs + ) + + +def teacache_integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + """ + Integrate velocity with TeaCache residual handling. + + Args: + self: SampleTransport instance + infer_idx: Inference index + cur_denoise_step: Current denoising step + """ + # Get cache from class attribute + teacache = SampleTransport.cache_reuse_manager + + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + # Integrate with residual handling + ori_x_chunk = x_chunk.clone() + + if teacache.should_calc: + if velocity.shape[2] < x_chunk.shape[2]: + # Partial reuse: only last chunk was computed + t_num = x_chunk.shape[2] // self.chunk_width + x_chunk = x_chunk[:, :, -self.chunk_width:] + x_chunk = self.integrate( + x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, + t_start, t_end, denoise_idx, delta_t_index=t_num - 1 + ) + # Concatenate with reused chunks + x_chunk = torch.cat([teacache.previous_output, x_chunk], dim=2) + else: + # Full calculation + x_chunk = self.integrate( + x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, + t_start, t_end, denoise_idx + ) + + # Store residual for next step + teacache.update_residual(0, x_chunk - ori_x_chunk) + + # Store output for potential next stage reuse + if (teacache.cnt + 1) % denoise_step_per_stage == 0: + teacache.previous_output = x_chunk + else: + # Reuse: add residual to input + x_chunk = x_chunk + teacache.previous_residual[:, :, -x_chunk.shape[2]:] + + # Increment step counter + teacache.increment_step() + + # Update chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # Return clean chunk if ready + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + return _return_clean_chunk( + self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset + ) + + return None, None + + +def _return_clean_chunk(self, infer_idx, transport_input, chunk_start, chunk_end, chunk_offset): + """ + Return the clean chunk if denoising is complete. + + Args: + self: SampleTransport instance + infer_idx: Inference index + transport_input: Transport input + chunk_start: Start chunk ID + chunk_end: End chunk ID + chunk_offset: Prefix video offset + + Returns: + Tuple of (clean_chunk, relative_chunk_id) or (None, None) + """ + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + # Keep the first 4-frames only for I2V Job + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start:(chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width:(chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + + +def parse_arguments(): + """Parse command line arguments.""" + parser = argparse.ArgumentParser(description="Run MagiPipeline with TeaCache.") + parser.add_argument('--config_file', type=str, help='Path to the configuration file.') + parser.add_argument( + '--mode', type=str, choices=['t2v', 'i2v', 'v2v'], + required=True, help='Mode to run: t2v, i2v, or v2v.' + ) + parser.add_argument('--prompt', type=str, required=True, help='Prompt for the pipeline.') + parser.add_argument('--image_path', type=str, help='Path to the image file (for i2v mode).') + parser.add_argument('--prefix_video_path', type=str, help='Path to the prefix video file (for v2v mode).') + parser.add_argument('--output_path', type=str, required=True, help='Path to save the output video.') + parser.add_argument('--use_teacache', action='store_true', help='Whether to use TeaCache.') + parser.add_argument('--rel_l1_thresh', type=float, default=0.01, help='Relative L1 distance threshold.') + parser.add_argument('--warmup_steps', type=int, default=0, help='Number of warmup steps before reuse.') + parser.add_argument('--log', action='store_true', help='Whether to log TeaCache information.') + parser.add_argument('--print_peak_memory', action='store_true', help='Print peak memory usage.') + + return parser.parse_args() + + +def main(): + """Main entry point.""" + args = parse_arguments() + + if args.print_peak_memory: + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + device = torch.cuda.current_device() + print(f"Running on GPU: {torch.cuda.get_device_name(device)}") + print(f"GPU Memory before pipeline: {torch.cuda.memory_allocated(device) / 1024**3:.2f} GB") + else: + print("CUDA not available, running on CPU") + + print(f"TeaCache config: rel_l1_thresh={args.rel_l1_thresh}, " + f"warmup_steps={args.warmup_steps}") + + # Setup TeaCache + setup_teacache( + rel_l1_thresh=args.rel_l1_thresh, + warmup_steps=args.warmup_steps, + log=args.log + ) + + # Run pipeline + pipeline = MagiPipeline(args.config_file) + + if args.mode == 't2v': + pipeline.run_text_to_video(prompt=args.prompt, output_path=args.output_path) + elif args.mode == 'i2v': + if not args.image_path: + print("Error: --image_path is required for i2v mode.") + sys.exit(1) + pipeline.run_image_to_video(prompt=args.prompt, image_path=args.image_path, output_path=args.output_path) + elif args.mode == 'v2v': + if not args.prefix_video_path: + print("Error: --prefix_video_path is required for v2v mode.") + sys.exit(1) + pipeline.run_video_to_video( + prompt=args.prompt, prefix_video_path=args.prefix_video_path, output_path=args.output_path + ) + + if args.print_peak_memory: + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated(device) / 1024**3 + current_memory = torch.cuda.memory_allocated(device) / 1024**3 + cached_memory = torch.cuda.memory_reserved(device) / 1024**3 + total_memory = torch.cuda.get_device_properties(device).total_memory / 1024**3 + + print("\n" + "=" * 50) + print("GPU Memory Usage Summary:") + print(f"Peak memory allocated: {peak_memory:.2f} GB") + print(f"Current memory allocated: {current_memory:.2f} GB") + print(f"Cached memory reserved: {cached_memory:.2f} GB") + print(f"Total GPU memory: {total_memory:.2f} GB") + print(f"Peak memory usage: {(peak_memory/total_memory)*100:.1f}%") + print("=" * 50) + + gc.collect() + torch.cuda.empty_cache() + final_memory = torch.cuda.memory_allocated(device) / 1024**3 + print(f"Memory after cache cleanup: {final_memory:.2f} GB") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/utils.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8bdcdc2227c22edf09514a25ac73f4f392b559 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/utils.py @@ -0,0 +1,21 @@ +import torch + +def get_tensors_memory_usage(tensor_list, unit='MB'): + total_bytes = 0 + for t in tensor_list: + if isinstance(t, torch.Tensor) and t.is_cuda: + total_bytes += t.element_size() * t.numel() + + unit = unit.upper() + scale_dict = { + 'B': 1, + 'KB': 1024, + 'MB': 1024 ** 2, + 'GB': 1024 ** 3, + } + + if unit not in scale_dict: + raise ValueError(f"Unsupported unit: {unit}. Use 'B', 'KB', 'MB', or 'GB'.") + + scale = scale_dict[unit] + return total_bytes / scale \ No newline at end of file diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_generate.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..28c330dde8d3d567efd7de35ae4fdb416c634123 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_generate.py @@ -0,0 +1,1138 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import json +import math +import os +from collections import Counter +from dataclasses import dataclass, field +from queue import Queue +from typing import Dict, Generator, List, Optional, Tuple, Union +from types import MethodType + +import torch +import torch.distributed as dist +from tqdm import tqdm + +import inference.infra.distributed.parallel_state as mpu +from inference.common import InferenceParams, event_path_timer, print_rank_0 +from inference.infra.parallelism import pp_scheduler + +from .prompt_process import get_negative_special_token_keys, get_special_token_keys, pad_special_token + + +@dataclass(frozen=True) +class InferenceInput: + caption_embs: torch.Tensor + emb_masks: torch.Tensor + y: torch.Tensor + prefix_video: Union[torch.Tensor, None] + latent_size: Tuple[int] + t_schedule_config: Dict = field(default_factory=dict) + num_steps: int = None + vae_ckpt: str = None + task_idx_list: List[int] = None + report_chunk_num_list: List[int] = None + chunk_num: int = None + + +def _process_txt_embeddings( + caption_embs: torch.Tensor, emb_masks: torch.Tensor, null_emb: torch.Tensor, infer_chunk_num: int, clean_chunk_num: int +) -> Tuple[torch.Tensor, torch.Tensor]: + special_token_keys = get_special_token_keys() + print_rank_0(f"special_token = {list(special_token_keys)}") + + # denoise chunk with caption_embs + caption_embs = caption_embs.repeat(1, infer_chunk_num - clean_chunk_num, 1, 1) + emb_masks = emb_masks.unsqueeze(1).repeat(1, infer_chunk_num - clean_chunk_num, 1) + caption_embs, emb_masks = pad_special_token(special_token_keys, caption_embs, emb_masks) + + # clean chunk with null_emb + caption_embs = torch.cat([null_emb.repeat(1, clean_chunk_num, 1, 1), caption_embs], dim=1) + emb_masks = torch.cat( + [torch.zeros(1, clean_chunk_num, emb_masks.size(2), dtype=emb_masks.dtype, device=emb_masks.device), emb_masks], dim=1 + ) + return caption_embs, emb_masks + + +def _process_null_embeddings( + null_caption_embedding: torch.Tensor, null_emb_masks: torch.Tensor, infer_chunk_num: int +) -> Tuple[torch.Tensor, torch.Tensor]: + null_embs = null_caption_embedding.repeat(1, infer_chunk_num, 1, 1) + negative_special_token_keys = get_negative_special_token_keys() + if negative_special_token_keys: + null_embs, _ = pad_special_token(negative_special_token_keys, null_embs, None) + + null_token_length = 50 + null_emb_masks[:, :, :null_token_length] = 1 + null_emb_masks[:, :, null_token_length:] = 0 + + return null_embs, null_emb_masks + + +@torch.inference_mode() +def extract_feature_for_inference( + model: torch.nn.Module, prefix_video: torch.Tensor, caption_embs: torch.Tensor, emb_masks: torch.Tensor +) -> InferenceInput: + model_config = model.model_config + runtime_config = model.runtime_config + ### Prepare prefix video feature + clean_chunk_num = 0 + if prefix_video is not None: + clean_chunk_num = prefix_video.size(2) // runtime_config.chunk_width + infer_chunk_num = math.ceil( + (runtime_config.num_frames // runtime_config.temporal_downsample_factor * 1.0 + prefix_video.size(2)) + / runtime_config.chunk_width + ) + else: + infer_chunk_num = math.ceil( + (runtime_config.num_frames // runtime_config.temporal_downsample_factor * 1.0) / runtime_config.chunk_width + ) + + ### Prepare text feature + # [1, caption_max_length (800), hidden_size(4096)] + null_caption_embedding = model.y_embedder.null_caption_embedding.unsqueeze(0) + caption_embs, caption_emb_masks = _process_txt_embeddings( + caption_embs, emb_masks, null_caption_embedding, infer_chunk_num, clean_chunk_num + ) + null_emb_masks = torch.zeros_like(caption_emb_masks) + null_embs, null_emb_masks = _process_null_embeddings(null_caption_embedding, null_emb_masks, infer_chunk_num) + + if emb_masks.sum() == 0: + emb_masks = torch.cat([null_emb_masks, null_emb_masks], dim=0) + y = torch.cat([null_embs, null_embs]) + else: + emb_masks = torch.cat([caption_emb_masks, null_emb_masks], dim=0) + y = torch.cat([caption_embs, null_embs]) + + ### Prepare latent feature dims + in_channels = model_config.in_channels + if model_config.half_channel_vae: + in_channels = 16 + latent_size_t = infer_chunk_num * runtime_config.chunk_width + latent_size_h = runtime_config.video_size_h // 8 + latent_size_w = runtime_config.video_size_w // 8 + + return InferenceInput( + caption_embs=caption_embs, # [1, 4, 800, 4096] + emb_masks=emb_masks, # [2, 4, 800] + y=y, # [2, 4, 800, 4096] + prefix_video=prefix_video, + latent_size=(1, in_channels, latent_size_t, latent_size_h, latent_size_w), # NCTHW + t_schedule_config={}, + num_steps=runtime_config.num_steps, + task_idx_list=[0], + report_chunk_num_list=[infer_chunk_num - clean_chunk_num], + chunk_num=latent_size_t // runtime_config.chunk_width, + ) + + +# Example1: when chunk_num=8, window_size=8 +# clip_start: [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# t_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8] + +# Example2: when chunk_num=8, window_size=4 +# clip_start: [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3] +# t_end : [1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4] + +# Example3: when chunk_num=8, window_size=4, chunk_offset=2 +# clip_start: [2, 2, 2, 2, 3, 4, 5, 6, 7] +# clip_end : [3, 4, 5, 6, 7, 8, 8, 8, 8] +# t_start : [0, 0, 0, 0, 0, 0, 1, 2, 3] +# t_end : [1, 2, 3, 4, 4, 4, 4, 4, 4] + +# Example4: when chunk_num=8, window_size=1 +# clip_start: [0, 1, 2, 3, 4, 5, 6, 7] +# clip_end : [1, 2, 3, 4, 5, 6, 7, 8] +# t_start : [0, 0, 0, 0, 0, 0, 0, 0] +# t_end : [1, 1, 1, 1, 1, 1, 1, 1] + + +def generate_sequences(chunk_num, window_size, chunk_offset): + # Adjust range to include the offset + start_index = chunk_offset + end_index = chunk_num + window_size - 1 + + # Generate clip_start and clip_end + clip_start = [max(chunk_offset, i - window_size + 1) for i in range(start_index, end_index)] + clip_end = [min(chunk_num, i + 1) for i in range(start_index, end_index)] + + # Generate t_start and t_end + t_start = [max(0, i - chunk_num + 1) for i in range(start_index, end_index)] + t_end = [ + min(window_size, i - chunk_offset + 1) if i - chunk_offset < window_size else window_size + for i in range(start_index, end_index) + ] + + return clip_start, clip_end, t_start, t_end + + +def init_t(t_schedule_config: Union[Dict, None], num_steps: int, device: torch.device, shortcut_mode: str = ""): + """Init Timestep and Transform t""" + if num_steps == 12: + base_t = torch.linspace(0, 1, 4 + 1, device=device) / 4 + accu_num = torch.linspace(0, 1, 4 + 1, device=device) + if shortcut_mode == "16,16,8": + base_t = base_t[:3] + else: + base_t = torch.cat([base_t[:1], base_t[2:4]], dim=0) + t = torch.cat([base_t + accu for accu in accu_num], dim=0)[: (num_steps + 1)] + else: + t = torch.linspace(0, 1, num_steps + 1, device=device) + t_schedule_func = t_schedule_config.get("tSchedulerFunc", "sd3") + if t_schedule_func == "sd3": + + def t_resolution_transform(x, shift=3.0): + # sd3: with a **reverse** time-schedule (0: clean, 1: noise) + # ours (0: noise, 1: clean) + # https://github.com/Stability-AI/sd3-ref/blob/master/sd3_impls.py#L33 + assert shift >= 1.0, "shift should >=1" + shift_inv = 1.0 / shift + return shift_inv * x / (1 + (shift_inv - 1) * x) + + t = t**2 + shift = t_schedule_config.get("shift", 3.0) + t = t_resolution_transform(t, shift) + elif t_schedule_func == "square": + t = t**2 + elif t_schedule_func == "piecewise": + + def t_transform(x): + mask = x < 0.875 + x[mask] = x[mask] * (0.5 / 0.875) + x[~mask] = 0.5 + (x[~mask] - 0.875) * (0.5 / (1 - 0.875)) + return x + + t = t_transform(t) + else: # identity + pass + return t + + +def init_intervel(num_steps: int, device: torch.device, shortcut_mode: str = ""): + """Init intervel""" + base_intervel = torch.ones(num_steps, device=device) + if num_steps % 3 == 0: + repeat_times = num_steps // 3 + if shortcut_mode == "16,16,8": + base_intervel = torch.tensor([1, 1, 2] * repeat_times, device=device) + else: + base_intervel = torch.tensor([2, 1, 1] * repeat_times, device=device) + return base_intervel + + +@dataclass +class WorkStatus: + infer_idx: int + cur_denoise_step: int + + +class ResidualDiffTracker: + def __init__(self, save_path: Optional[str]): + self.save_path = save_path + self.prev_residuals = {} + self.prev_timesteps = {} + self.records = [] + + @property + def enabled(self) -> bool: + return bool(self.save_path) + + def is_writer_rank(self) -> bool: + return not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 + + def update( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + x_chunk: torch.Tensor, + velocity: torch.Tensor, + timesteps: torch.Tensor, + chunk_width: int, + ) -> None: + residual = (velocity[0:1] - x_chunk[0:1]).detach() + self.update_residuals( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + residual=residual, + timesteps=timesteps, + chunk_width=chunk_width, + ) + + def update_residuals( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + residual: torch.Tensor, + timesteps: torch.Tensor, + chunk_width: int, + ) -> None: + if not self.enabled or not self.is_writer_rank(): + return + + residual = residual[0:1].detach() + timesteps = timesteps.detach() + assert residual.size(2) % chunk_width == 0 + chunk_num = residual.size(2) // chunk_width + assert timesteps.size(0) == chunk_num + residual = residual.reshape(residual.size(0), residual.size(1), chunk_num, chunk_width, *residual.shape[3:]) + + for local_chunk_idx in range(chunk_num): + chunk_idx = chunk_start + local_chunk_idx + key = (infer_idx, chunk_idx) + cur_residual = residual[:, :, local_chunk_idx].clone() + cur_timestep = float(timesteps[local_chunk_idx].item()) + + if key in self.prev_residuals: + prev_residual = self.prev_residuals[key] + diff_norm = torch.linalg.vector_norm(cur_residual.float() - prev_residual.float()).item() + residual_norm = torch.linalg.vector_norm(cur_residual.float()).item() + self.records.append( + { + "infer_idx": infer_idx, + "cur_denoise_step": cur_denoise_step, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_idx": chunk_idx, + "generated_chunk_idx": chunk_idx - chunk_offset, + "prev_timestep": self.prev_timesteps[key], + "timestep": cur_timestep, + "residual_diff_norm": diff_norm, + "residual_norm": residual_norm, + } + ) + + self.prev_residuals[key] = cur_residual + self.prev_timesteps[key] = cur_timestep + + def save(self) -> None: + if not self.enabled or not self.is_writer_rank(): + return + save_dir = os.path.dirname(self.save_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "Per-chunk norm of residual differences across denoise timesteps. " + "For vanilla MAGI residual = velocity - x; for FlowCache residual = X_next - X_t." + ), + "records": self.records, + } + if self.save_path.endswith((".pt", ".pth")): + torch.save(payload, self.save_path) + else: + with open(self.save_path, "w") as f: + json.dump(payload, f, indent=2) + print_rank_0(f"Saved residual diff stats to {self.save_path}") + + +class L1RelChangeTracker: + def __init__(self, save_path: Optional[str], eps: float = 1e-6): + self.save_path = save_path + self.eps = eps + self.records = [] + + @property + def enabled(self) -> bool: + return bool(self.save_path) + + def is_writer_rank(self) -> bool: + return not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 + + def update( + self, + infer_idx: int, + cur_denoise_step: int, + denoise_stage: int, + denoise_idx: int, + chunk_offset: int, + chunk_start: int, + x_before: torch.Tensor, + x_after: torch.Tensor, + timesteps: torch.Tensor, + next_timesteps: torch.Tensor, + chunk_width: int, + x_embedder_before: Optional[torch.Tensor] = None, + x_embedder_after: Optional[torch.Tensor] = None, + x_embedder_chunk_width: Optional[int] = None, + ) -> None: + if not self.enabled or not self.is_writer_rank(): + return + + x_before = x_before[0:1].detach() + x_after = x_after[0:1].detach() + timesteps = timesteps.detach() + next_timesteps = next_timesteps.detach() + assert x_before.size(2) == x_after.size(2) + assert x_before.size(2) % chunk_width == 0 + chunk_num = x_before.size(2) // chunk_width + assert timesteps.size(0) == chunk_num + assert next_timesteps.size(0) == chunk_num + + x_before = x_before.reshape(x_before.size(0), x_before.size(1), chunk_num, chunk_width, *x_before.shape[3:]) + x_after = x_after.reshape(x_after.size(0), x_after.size(1), chunk_num, chunk_width, *x_after.shape[3:]) + + x_embedder_before_by_chunk = None + x_embedder_after_by_chunk = None + if x_embedder_before is not None and x_embedder_after is not None and x_embedder_chunk_width is not None: + x_embedder_before = x_embedder_before[0:1].detach() + x_embedder_after = x_embedder_after[0:1].detach() + assert x_embedder_before.size(2) == x_embedder_after.size(2) + assert x_embedder_before.size(2) % x_embedder_chunk_width == 0 + assert x_embedder_before.size(2) // x_embedder_chunk_width == chunk_num + x_embedder_before_by_chunk = x_embedder_before.reshape( + x_embedder_before.size(0), + x_embedder_before.size(1), + chunk_num, + x_embedder_chunk_width, + *x_embedder_before.shape[3:], + ) + x_embedder_after_by_chunk = x_embedder_after.reshape( + x_embedder_after.size(0), + x_embedder_after.size(1), + chunk_num, + x_embedder_chunk_width, + *x_embedder_after.shape[3:], + ) + + for local_chunk_idx in range(chunk_num): + chunk_idx = chunk_start + local_chunk_idx + cur_x = x_before[:, :, local_chunk_idx].float() + next_x = x_after[:, :, local_chunk_idx].float() + delta = next_x - cur_x + denom = cur_x.abs().clamp_min(self.eps) + + l1_rel = (delta.abs() / denom).mean().item() + delta_l1_norm = delta.abs().sum().item() + x_l1_norm = cur_x.abs().sum().item() + l1_rel_ratio = delta_l1_norm / max(x_l1_norm, self.eps) + + self.records.append( + { + "infer_idx": infer_idx, + "cur_denoise_step": cur_denoise_step, + "denoise_stage": denoise_stage, + "denoise_idx": denoise_idx, + "chunk_idx": chunk_idx, + "generated_chunk_idx": chunk_idx - chunk_offset, + "timestep": float(timesteps[local_chunk_idx].item()), + "next_timestep": float(next_timesteps[local_chunk_idx].item()), + "l1_rel": l1_rel, + "l1_rel_ratio": l1_rel_ratio, + "delta_l1_norm": delta_l1_norm, + "x_l1_norm": x_l1_norm, + } + ) + + if x_embedder_before_by_chunk is not None and x_embedder_after_by_chunk is not None: + cur_x_embedder = x_embedder_before_by_chunk[:, :, local_chunk_idx].float() + next_x_embedder = x_embedder_after_by_chunk[:, :, local_chunk_idx].float() + x_embedder_delta = next_x_embedder - cur_x_embedder + x_embedder_denom = cur_x_embedder.abs().clamp_min(self.eps) + x_embedder_l1_rel = (x_embedder_delta.abs() / x_embedder_denom).mean().item() + x_embedder_delta_l1_norm = x_embedder_delta.abs().sum().item() + x_embedder_l1_norm = cur_x_embedder.abs().sum().item() + x_embedder_l1_rel_ratio = x_embedder_delta_l1_norm / max(x_embedder_l1_norm, self.eps) + + self.records[-1].update( + { + "x_embedder_l1_rel": x_embedder_l1_rel, + "x_embedder_l1_rel_ratio": x_embedder_l1_rel_ratio, + "x_embedder_delta_l1_norm": x_embedder_delta_l1_norm, + "x_embedder_x_l1_norm": x_embedder_l1_norm, + } + ) + + def save(self) -> None: + if not self.enabled or not self.is_writer_rank(): + return + save_dir = os.path.dirname(self.save_path) + if save_dir: + os.makedirs(save_dir, exist_ok=True) + + payload = { + "description": ( + "Per-chunk relative L1 change across MAGI denoise steps. MAGI timesteps increase from noise " + "to clean, so next_timestep is the cleaner step. l1_rel = mean(abs((X_next - X_t) / " + "(abs(X_t) + eps))). x_embedder_* fields apply the same computation after DiT x_embedder." + ), + "eps": self.eps, + "records": self.records, + } + if self.save_path.endswith((".pt", ".pth")): + torch.save(payload, self.save_path) + else: + with open(self.save_path, "w") as f: + json.dump(payload, f, indent=2) + print_rank_0(f"Saved L1 relative change stats to {self.save_path}") + + +def find_dit_model(model): + if hasattr(model, "y_embedder"): + return model + if hasattr(model, "module"): + return find_dit_model(model.module) + raise ValueError("Cannot find the real model") + + +class SampleTransport: + def __init__( + self, + model: torch.nn.Module, + transport_inputs: List[InferenceInput], + device: torch.device, + residual_stats_path: Optional[str] = None, + l1_rel_stats_path: Optional[str] = None, + ): + # ========= Input Tensor ========= + self.model = model + self.transport_inputs = transport_inputs + self.device = device + + # ========= Init Global Members ========= + self.model_config = model.model_config + self.runtime_config = model.runtime_config + self.engine_config = model.engine_config + self.chunk_width = self.runtime_config.chunk_width + self.window_size = self.runtime_config.window_size + self.residual_diff_tracker = ResidualDiffTracker(residual_stats_path or os.getenv("MAGI_RESIDUAL_STATS_PATH")) + self.l1_rel_change_tracker = L1RelChangeTracker(l1_rel_stats_path or os.getenv("MAGI_L1_REL_STATS_PATH")) + + # ========= Init Batched Inputs and Work Queue ========= + self.work_queue = Queue() + self.chunk_denoise_count: List[Counter] = [] + self.ts: List[torch.Tensor] = [] + self.time_interval: List[torch.Tensor] = [] + self.xs: List[torch.Tensor] = [] + self.x_chunks: List[torch.Tensor] = [] + self.velocities: List[torch.Tensor] = [] + self.time_record: List[tqdm] = [] + self.inference_params: List[InferenceParams] = [] + self.init_work_queue() + + def init_work_queue(self) -> None: + shortcut_mode = self.engine_config.shortcut_mode + if mpu.get_pp_world_size() > 1: + if len(self.transport_inputs) == 1: + print_rank_0("Warning: For better performance, please use multiple inputs for PP>1") + else: + assert len(self.transport_inputs) == 1, "Only support single input for PP=1" + + for idx, tran_input in enumerate(self.transport_inputs): + self.work_queue.put(WorkStatus(infer_idx=idx, cur_denoise_step=0)) + + self.chunk_denoise_count.append(Counter()) + self.ts.append( + init_t(tran_input.t_schedule_config, tran_input.num_steps, self.device, shortcut_mode=shortcut_mode) + ) + self.time_interval.append(init_intervel(tran_input.num_steps, self.device, shortcut_mode=shortcut_mode)) + self.x_chunks.append(None) + self.velocities.append(None) + + if torch.distributed.get_rank() == 0: + report_chunk_num = sum( + dict( + zip(self.transport_inputs[idx].task_idx_list, self.transport_inputs[idx].report_chunk_num_list) + ).values() + ) + + progress_bar = tqdm(total=report_chunk_num, desc=f"InferBatch {idx}") + self.time_record.append(progress_bar) + + print_rank_0(f"transport_inputs len: {len(self.transport_inputs)}") + x = torch.randn(*tran_input.latent_size, device=self.device) # NCTHW + x = torch.cat([x, x], 0) # [2 * N, C, T, H, W] + self.xs.append(x) + + max_sequence_length = ( + x.shape[2] * (x.shape[3] // self.model_config.patch_size) * (x.shape[4] // self.model_config.patch_size) + ) + self.inference_params.append(InferenceParams(max_batch_size=1, max_sequence_length=max_sequence_length)) + + def append_dims(self, x, target_dims): + """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" + dims_to_append = target_dims - x.ndim + if dims_to_append < 0: + raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") + return x[(...,) + (None,) * dims_to_append] + + def embed_x_for_l1_rel_stats(self, x: torch.Tensor) -> Tuple[torch.Tensor, int]: + dit_model = find_dit_model(self.model) + x_embedder_chunk_width = self.chunk_width // dit_model.model_config.t_patch_size + assert self.chunk_width % dit_model.model_config.t_patch_size == 0 + + x = x[0:1] * dit_model.model_config.x_rescale_factor + if dit_model.model_config.half_channel_vae: + assert x.shape[1] == 16 + x = torch.cat([x, x], dim=1) + x = x.float() + with torch.no_grad(): + x = dit_model.x_embedder(x) + return x, x_embedder_chunk_width + + def get_timestep( + self, + t_total: torch.Tensor, + denoise_step_per_stage: int, + start: int, + end: int, + denoise_idx: int, + has_clean_t: bool = False, + ) -> torch.Tensor: + """Const Method""" + t_index = [] + for i in range(start, end): + t_index.append(i * denoise_step_per_stage + denoise_idx) + t_index.reverse() + # t_index is the timestep + timestep = t_total[t_index] + if has_clean_t: + ones = torch.ones(1, device=self.device) * self.runtime_config.clean_t + timestep = torch.cat([ones, timestep], 0) + return timestep + + def get_denoise_step_of_each_chunk( + self, + infer_idx: int, + denoise_step_per_stage: int, + t_start: int, + t_end: int, + denoise_idx: int, + has_clean_t: bool = False, + ): + denoise_step_of_each_chunk = [] + for i in range(t_start, t_end): + denoise_step_of_each_chunk.append(i * denoise_step_per_stage + denoise_idx) + denoise_step_of_each_chunk.reverse() + if has_clean_t: + denoise_step_of_each_chunk = [self.transport_inputs[infer_idx].num_steps] + denoise_step_of_each_chunk + return denoise_step_of_each_chunk + + def get_batch_size_and_chunk_token_nums(self, infer_idx: int): + """Const Method""" + batch_size = 1 + # T H W + chunk_token_nums = ( + self.chunk_width + * (self.transport_inputs[infer_idx].latent_size[3] // self.model_config.patch_size) + * (self.transport_inputs[infer_idx].latent_size[4] // self.model_config.patch_size) + ) + return batch_size, chunk_token_nums + + def generate_kvrange_for_prefix_video(self, infer_idx: int, range_num: int): + """Const Method""" + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + if self.runtime_config.clean_chunk_kvrange != -1: + prev_chunk_num = self.runtime_config.clean_chunk_kvrange + elif len(self.runtime_config.noise2clean_kvrange) > 0: + prev_chunk_num = self.runtime_config.noise2clean_kvrange[-1] + else: + prev_chunk_num = 8 + + k_chunk_end = torch.linspace(1, range_num, steps=range_num).reshape((range_num, 1)) + k_chunk_start = torch.clamp(k_chunk_end - prev_chunk_num, min=0).reshape((range_num, 1)) + k_chunk_range = torch.concat([k_chunk_start, k_chunk_end], dim=1) + k_batch_range = ( + torch.concat([k_chunk_range + i * range_num for i in range(batch_size)], dim=0).to(torch.int32).to(self.device) + ) + return k_batch_range * chunk_token_nums + + def extract_prefix_video_feature( + self, infer_idx: int, prefix_video: torch.Tensor, y: torch.Tensor, chunk_offset: int, model_kwargs: dict + ): + """Non-Const Method""" + print_rank_0(f"extract clean feature for prefix video, chunk_offset: {chunk_offset}") + + x_chunk = prefix_video[:, :, : chunk_offset * self.chunk_width] + x_chunk = torch.cat([x_chunk, x_chunk], 0) # [2 * N, C, T, H, W] + + # clean feature without y embedding + null_y_chunk = self.transport_inputs[infer_idx].y[1:2, :chunk_offset] + null_y_chunk = torch.cat([null_y_chunk, null_y_chunk], 0) + mask_chunk = self.transport_inputs[infer_idx].emb_masks[1:2, :chunk_offset] + mask_chunk = torch.cat([mask_chunk, mask_chunk], 0) + + null_y_chunk_flatten = null_y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + mask_chunk_flatten = mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + + t = torch.ones(chunk_offset, device=self.device) * self.runtime_config.clean_t + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + fwd_model_kwargs = model_kwargs.copy() + fwd_model_kwargs.update( + { + "slice_point": 0, + "range_num": chunk_offset, + "denoising_range_num": chunk_offset, + "fwd_extra_1st_chunk": False, + "extract_prefix_video_feature": True, + } + ) + + # Adapt to chunkwise forward + fwd_model_kwargs["start_chunk_id"] = 0 + fwd_model_kwargs["end_chunk_id"] = chunk_offset + fwd_model_kwargs["chunk_num"] = self.transport_inputs[infer_idx].chunk_num + + kv_range = self.generate_kvrange_for_prefix_video(infer_idx, chunk_offset) + + forward_fn = find_dit_model(self.model).forward_dispatcher + fwd_model_kwargs["distill_interval"] = self.time_interval[infer_idx][0] + forward_fn( + x=x_chunk, + timestep=t, + y=null_y_chunk_flatten, + mask=mask_chunk_flatten, + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **fwd_model_kwargs, + ) # for kv cache + + def try_pad_prefix_video( + self, infer_idx: int, x_chunk: torch.Tensor, t: torch.Tensor, prefix_video_start: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Non-Const Method""" + prefix_length = self.transport_inputs[infer_idx].prefix_video.size(2) + + if prefix_length <= prefix_video_start: + return x_chunk, t + + padding_length = min(prefix_length - prefix_video_start, x_chunk.size(2)) + prefix_video_end = prefix_video_start + padding_length + ret = x_chunk.clone() + ret[:, :, :padding_length] = self.transport_inputs[infer_idx].prefix_video[:, :, prefix_video_start:prefix_video_end] + + num_clean_t = (prefix_length - prefix_video_start) // self.chunk_width + if num_clean_t > 0: + t[:, :num_clean_t] = 1.0 + return ret, t + + def generate_default_kvrange(self, infer_idx: int, slice_point: int, denoising_range_num: int) -> torch.Tensor: + """Const Method""" + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + range_num = slice_point + denoising_range_num + + k_chunk_end = torch.linspace(slice_point + 1, range_num, steps=denoising_range_num).reshape((denoising_range_num, 1)) + k_chunk_start = torch.Tensor([0] * denoising_range_num).reshape((denoising_range_num, 1)) + k_chunk_range = torch.concat([k_chunk_start, k_chunk_end], dim=1) + k_batch_range = ( + torch.concat([k_chunk_range + i * range_num for i in range(batch_size)], dim=0).to(torch.int32).to(self.device) + ) + return k_batch_range * chunk_token_nums + + def generate_noise2clean_kvrange( + self, + infer_idx: int, + slice_point: int, + denoising_range_num: int, + noise2clean_kvrange: List[int], + clean_chunk_kvrange: int, + denoise_step_of_each_chunk: List[int], + ) -> torch.Tensor: + """Const Method""" + assert len(denoise_step_of_each_chunk) == denoising_range_num + assert len(noise2clean_kvrange) > 0 + + if clean_chunk_kvrange == -1: + clean_chunk_kvrange = noise2clean_kvrange[-1] + num_steps = self.transport_inputs[infer_idx].num_steps + assert num_steps % len(noise2clean_kvrange) == 0 + denoise_step_per_stage = num_steps // len(noise2clean_kvrange) + denoise_kv_range = [] + for cur_chunk_denoise_step in denoise_step_of_each_chunk: + if cur_chunk_denoise_step == num_steps: + denoise_kv_range.append(clean_chunk_kvrange) + else: + denoise_kv_range.append(noise2clean_kvrange[cur_chunk_denoise_step // denoise_step_per_stage]) + + range_num = slice_point + denoising_range_num + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + k_ranges = [] + for i in range(batch_size): + k_batch_start = i * range_num + for j in range(denoising_range_num): + k_chunk_end = slice_point + j + 1 + k_chunk_start = max(0, k_chunk_end - denoise_kv_range[j]) + k_ranges.append( + torch.Tensor( + [(k_batch_start + k_chunk_start) * chunk_token_nums, (k_batch_start + k_chunk_end) * chunk_token_nums] + ) + .reshape(1, 2) + .to(self.device) + ) + k_range = torch.concat(k_ranges, dim=0).to(torch.int32).to(self.device) + return k_range + + def generate_kvrange_for_denoising_video( + self, infer_idx: int, slice_point: int, denoising_range_num: int, denoise_step_of_each_chunk: List[int] + ) -> torch.Tensor: + """Const Method""" + noise2clean_kvrange = self.runtime_config.noise2clean_kvrange + clean_chunk_kvrange = self.runtime_config.clean_chunk_kvrange + if len(noise2clean_kvrange) == 0: + k_range = self.generate_default_kvrange(infer_idx, slice_point, denoising_range_num) + else: + k_range = self.generate_noise2clean_kvrange( + infer_idx, + slice_point, + denoising_range_num, + noise2clean_kvrange, + clean_chunk_kvrange, + denoise_step_of_each_chunk, + ) + return k_range + + def integrate( + self, + x_chunk: torch.Tensor, + velocity: torch.Tensor, + t_total: torch.Tensor, + denoise_step_per_stage: int, + t_start: int, + t_end: int, + i: int, + delta_t_index: int = None, + ) -> torch.Tensor: + """Non-Const Method""" + t_before = self.get_timestep(t_total, denoise_step_per_stage, t_start, t_end, i) + t_after = self.get_timestep(t_total, denoise_step_per_stage, t_start, t_end, i + 1) + delta_t = t_after - t_before + N, C, T, H, W = x_chunk.shape + x_chunk = x_chunk.reshape(N, C, -1, self.chunk_width, H, W) + velocity = velocity.reshape(N, C, -1, self.chunk_width, H, W) + + if x_chunk.size(2) < delta_t.size(0) and delta_t_index is not None: + delta_t = delta_t[delta_t_index:delta_t_index+1] + + assert x_chunk.size(2) == delta_t.size(0) + x_chunk = x_chunk + velocity * delta_t.reshape(1, 1, -1, 1, 1, 1) + x_chunk = x_chunk.reshape(N, C, T, H, W) + return x_chunk + + def generate_denoise_status_and_sequences( + self, infer_idx: int, cur_denoise_step: int + ) -> Tuple[Tuple[int, int, int], Tuple[int, int, int, int, int]]: + """Const Method""" + chunk_offset = 0 + if self.transport_inputs[infer_idx].prefix_video is not None: + chunk_offset = self.transport_inputs[infer_idx].prefix_video.size(2) // self.chunk_width + + transport_input = self.transport_inputs[infer_idx] + denoise_step_per_stage = transport_input.num_steps // self.window_size + denoise_stage, denoise_idx = (cur_denoise_step // denoise_step_per_stage, cur_denoise_step % denoise_step_per_stage) + chunk_start_s, chunk_end_s, t_start_s, t_end_s = generate_sequences( + transport_input.chunk_num, self.window_size, chunk_offset + ) + chunk_start, chunk_end, t_start, t_end = ( + chunk_start_s[denoise_stage], + chunk_end_s[denoise_stage], + t_start_s[denoise_stage], + t_end_s[denoise_stage], + ) + return (denoise_step_per_stage, denoise_stage, denoise_idx), (chunk_offset, chunk_start, chunk_end, t_start, t_end) + + def total_forward_step(self, infer_idx: int) -> int: + denoise_step_per_stage = self.transport_inputs[infer_idx].num_steps // self.window_size + + chunk_offset = 0 + if self.transport_inputs[infer_idx].prefix_video is not None: + chunk_offset = self.transport_inputs[infer_idx].prefix_video.size(2) // self.chunk_width + + total_forward_step = denoise_step_per_stage * ( + self.transport_inputs[infer_idx].chunk_num + self.window_size - 1 - chunk_offset + ) + return total_forward_step + + def forward_velocity(self, infer_idx: int, cur_denoise_step: int) -> torch.Tensor: + # 1. Get current work status + x = self.xs[infer_idx] + transport_input = self.transport_inputs[infer_idx] + + # 2. Extract prefix video KV cache + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + + model_kwargs = dict(chunk_width=self.chunk_width, fwd_extra_1st_chunk=False, num_steps=transport_input.num_steps) + model_kwargs.update( + {"denoise_step_per_stage": denoise_step_per_stage, "denoise_stage": denoise_stage, "denoise_idx": denoise_idx + }) + + if chunk_offset > 0 and cur_denoise_step == 0: + self.extract_prefix_video_feature( + infer_idx, transport_input.prefix_video, transport_input.y, chunk_offset, model_kwargs + ) + + # 3. Prepare inputs + x_chunk = x[:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width].clone() + y_chunk = transport_input.y[:, chunk_start:chunk_end] + mask_chunk = transport_input.emb_masks[:, chunk_start:chunk_end] + model_kwargs.update( + {"slice_point": chunk_start, "range_num": chunk_end, "denoising_range_num": chunk_end - chunk_start} + ) + batch_size, chunk_token_nums = self.get_batch_size_and_chunk_token_nums(infer_idx) + model_kwargs["chunk_token_nums"] = chunk_token_nums + model_kwargs["start_chunk_id"] = chunk_start + model_kwargs["end_chunk_id"] = chunk_end + + # 4. Forward clean chunk and get clean kv + fwd_extra_1st_chunk = chunk_start > chunk_offset and denoise_idx == 0 + if fwd_extra_1st_chunk: + clean_x = x[:, :, (chunk_start - 1) * self.chunk_width : chunk_start * self.chunk_width].clone() + x_chunk = torch.cat([clean_x, x_chunk], dim=2) + + # Clean feature without y embedding + y_chunk = torch.cat([transport_input.y[1:2, 0:1].expand(y_chunk.size(0), -1, -1, -1), y_chunk], dim=1) + mask_chunk = torch.cat([transport_input.emb_masks[1:2, 1:2].expand(mask_chunk.size(0), -1, -1), mask_chunk], dim=1) + + model_kwargs["slice_point"] = chunk_start - 1 + model_kwargs["denoising_range_num"] = chunk_end - chunk_start + 1 + model_kwargs["fwd_extra_1st_chunk"] = True + + # 5. Prepare inputs + y_chunk_flatten = y_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + mask_chunk_flatten = mask_chunk.flatten(start_dim=0, end_dim=1).unsqueeze(1) + + denoise_step_of_each_chunk = self.get_denoise_step_of_each_chunk( + infer_idx, denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + t = t.unsqueeze(0).repeat(x_chunk.size(0), 1) + + kv_range = self.generate_kvrange_for_denoising_video( + infer_idx=infer_idx, + slice_point=model_kwargs["slice_point"], + denoising_range_num=model_kwargs["denoising_range_num"], + denoise_step_of_each_chunk=denoise_step_of_each_chunk, + ) + + # 6. Padding prefix video + if transport_input.prefix_video is not None: + x_chunk, t = self.try_pad_prefix_video( + infer_idx, x_chunk, t, prefix_video_start=model_kwargs["slice_point"] * self.chunk_width + ) + + # 7. Model forward + forward_fn = find_dit_model(self.model).forward_dispatcher + nearly_clean_chunk_t = t[0, int(model_kwargs["fwd_extra_1st_chunk"])].item() + model_kwargs["distill_nearly_clean_chunk"] = ( + nearly_clean_chunk_t > self.engine_config.distill_nearly_clean_chunk_threshold + ) + model_kwargs["distill_interval"] = self.time_interval[infer_idx][denoise_idx] + model_kwargs["total_num_steps"] = self.total_forward_step(infer_idx) + + if model_kwargs.get("distill_nearly_clean_chunk", False): + model_kwargs["end_chunk_id"] += 1 + model_kwargs["chunk_num"] = transport_input.chunk_num + + velocity = forward_fn( + x=x_chunk, + timestep=t, + y=y_chunk_flatten, + mask=mask_chunk_flatten, + kv_range=kv_range, + inference_params=self.inference_params[infer_idx], + **model_kwargs, + ) + + self.x_chunks[infer_idx] = x_chunk + self.velocities[infer_idx] = velocity + return velocity + + def integrate_velocity(self, infer_idx: int, cur_denoise_step: int): + transport_input = self.transport_inputs[infer_idx] + x_chunk = self.x_chunks[infer_idx] + velocity = self.velocities[infer_idx] + chunk_denoise_count = self.chunk_denoise_count[infer_idx] + + (denoise_step_per_stage, denoise_stage, denoise_idx), ( + chunk_offset, + chunk_start, + chunk_end, + t_start, + t_end, + ) = self.generate_denoise_status_and_sequences(infer_idx, cur_denoise_step) + fwd_extra_1st_chunk = chunk_start > chunk_offset and denoise_idx == 0 + + # 8. Remove clean chunk + if fwd_extra_1st_chunk: + x_chunk = x_chunk[:, :, self.chunk_width :] + velocity = velocity[:, :, self.chunk_width :] + + t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx, has_clean_t=fwd_extra_1st_chunk + ) + if fwd_extra_1st_chunk: + t = t[1:] + self.residual_diff_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_chunk=x_chunk, + velocity=velocity, + timesteps=t, + chunk_width=self.chunk_width, + ) + next_t = self.get_timestep( + self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx + 1, has_clean_t=fwd_extra_1st_chunk + ) + if fwd_extra_1st_chunk: + next_t = next_t[1:] + x_before_integrate = x_chunk + x_embedder_before = None + x_embedder_after = None + x_embedder_chunk_width = None + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_before, x_embedder_chunk_width = self.embed_x_for_l1_rel_stats(x_before_integrate) + + # 9. Walk and integrate + x_chunk = self.integrate(x_chunk, velocity, self.ts[infer_idx], denoise_step_per_stage, t_start, t_end, denoise_idx) + if self.l1_rel_change_tracker.enabled and self.l1_rel_change_tracker.is_writer_rank(): + x_embedder_after, _ = self.embed_x_for_l1_rel_stats(x_chunk) + self.l1_rel_change_tracker.update( + infer_idx=infer_idx, + cur_denoise_step=cur_denoise_step, + denoise_stage=denoise_stage, + denoise_idx=denoise_idx, + chunk_offset=chunk_offset, + chunk_start=chunk_start, + x_before=x_before_integrate, + x_after=x_chunk, + timesteps=t, + next_timesteps=next_t, + chunk_width=self.chunk_width, + x_embedder_before=x_embedder_before, + x_embedder_after=x_embedder_after, + x_embedder_chunk_width=x_embedder_chunk_width, + ) + + # 10. chunk denoise count + for chunk_index in range(chunk_start, chunk_end): + chunk_denoise_count[chunk_index] += 1 + self.xs[infer_idx][:, :, chunk_start * self.chunk_width : chunk_end * self.chunk_width] = x_chunk + self.chunk_denoise_count[infer_idx] = chunk_denoise_count + + # 11. Return clean chunk + if chunk_denoise_count[chunk_start] == transport_input.num_steps: + if transport_input.prefix_video is not None: + prefix_video_length = transport_input.prefix_video.size(2) + if (chunk_start + 1) * self.chunk_width <= prefix_video_length: + return None, None + + real_start = max(chunk_start * self.chunk_width, prefix_video_length) + + # Keep the first 4-frames only for I2V Job + if chunk_start == 0 and prefix_video_length == 1: + real_start = 0 + + clean_chunk, _ = self.xs[infer_idx][:, :, real_start : (chunk_start + 1) * self.chunk_width].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + else: + clean_chunk, _ = self.xs[infer_idx][ + :, :, chunk_start * self.chunk_width : (chunk_start + 1) * self.chunk_width + ].chunk(2, dim=0) + return clean_chunk, chunk_start - chunk_offset + return None, None + + def walk(self): + event_path_timer().synced_record("begin_walk") + infer_batch_size = len(self.transport_inputs) + for infer_idx in range(infer_batch_size): + velocity = self.forward_velocity(infer_idx, 0) + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + pp_scheduler().queue_irecv_prev(velocity.shape, velocity.dtype) + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_last_stage(): + pp_scheduler().isend_next(velocity) + + while not self.work_queue.empty(): + work_status: WorkStatus = self.work_queue.get() + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + self.velocities[work_status.infer_idx] = pp_scheduler().queue_irecv_prev_data() + + clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step) + if clean_chunk is not None: + if torch.distributed.get_rank() == 0: + self.time_record[work_status.infer_idx].update(1) + yield work_status.infer_idx, chunk_idx, clean_chunk + + if work_status.cur_denoise_step + 1 == self.total_forward_step(work_status.infer_idx): + if torch.distributed.get_rank() == 0: + self.time_record[work_status.infer_idx].close() + continue + self.work_queue.put(WorkStatus(infer_idx=work_status.infer_idx, cur_denoise_step=work_status.cur_denoise_step + 1)) + velocity = self.forward_velocity(work_status.infer_idx, work_status.cur_denoise_step + 1) + + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_first_stage(): + pp_scheduler().queue_irecv_prev(velocity.shape, velocity.dtype) + if mpu.get_pp_world_size() > 1 and mpu.is_pipeline_last_stage(): + pp_scheduler().isend_next(velocity) + + +def generate_per_chunk( + model: torch.nn.Module, + prefix_video: torch.Tensor, + caption_embs: torch.Tensor, + emb_masks: torch.Tensor, + residual_stats_path: Optional[str] = None, + l1_rel_stats_path: Optional[str] = None, +) -> Generator[Tuple[int, int, int, int, int, torch.Tensor], None, None]: + print_rank_0("Begin to generate per chunk") + device = f"cuda:{torch.cuda.current_device()}" + transport_inputs: InferenceInput = extract_feature_for_inference(model, prefix_video, caption_embs, emb_masks) + sample_transport = SampleTransport( + model=model, + transport_inputs=[transport_inputs], + device=device, + residual_stats_path=residual_stats_path, + l1_rel_stats_path=l1_rel_stats_path, + ) + for _, _, chunk in sample_transport.walk(): + yield chunk + sample_transport.residual_diff_tracker.save() + sample_transport.l1_rel_change_tracker.save() + cache_reuse_manager = getattr(SampleTransport, "cache_reuse_manager", None) + if cache_reuse_manager is not None and hasattr(cache_reuse_manager, "save_metric_stats"): + cache_reuse_manager.save_metric_stats() + dist.barrier(device_ids=[torch.cuda.current_device()]) + gc.collect() + torch.cuda.empty_cache() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_process.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_process.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd5b7f9bd7495f83091b6e011c657a7244e1bfa --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/inference/pipeline/video_process.py @@ -0,0 +1,400 @@ +# Copyright (c) 2025 SandAI. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import os +import tempfile + +import ffmpeg +import torch +from einops import rearrange + +import inference.infra.distributed.parallel_state as mpu +from inference.common import MagiConfig, magi_logger +from inference.model.vae import AutoModel, DiagonalGaussianDistribution, VideoTokenizerABC + + +############################################ +# VaeHelper +########################################### +class SingletonMeta(type): + """ + Singleton metaclass + """ + + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super().__call__(*args, **kwargs) + return cls._instances[cls] + + +class VaeHelper(metaclass=SingletonMeta): + def __init__(self): + # Initialize cache dict + if not hasattr(self, "vae_cache_dict"): + self.vae_cache_dict = {} + + @staticmethod + def get_vae(vae_ckpt: str) -> VideoTokenizerABC: + """ + Load a pretrained VAE model. + + Args: + vae_ckpt (str): Path to the pretrained VAE checkpoint. + + Returns: + VideoTokenizerABC: Pretrained VAE model. + """ + vae_helper = VaeHelper() + + if vae_ckpt not in vae_helper.vae_cache_dict: + vae = AutoModel.from_pretrained(vae_ckpt) + vae.encode = vae_helper.patch_vae_encode.__get__(vae) + vae.cuda() + vae.eval() + vae.bfloat16() + if os.environ.get("OFFLOAD_VAE_CACHE") == "true": + return vae + vae_helper.vae_cache_dict[vae_ckpt] = vae + return vae_helper.vae_cache_dict[vae_ckpt] + + @staticmethod + @torch.no_grad() + def patch_vae_encode(vae: callable, x: torch.Tensor) -> torch.Tensor: + """ + Encode the input video. + + Args: + x (torch.Tensor): Input video tensor with shape (N, C, T, H, W). + sample_posterior (bool): Whether to sample from the posterior. + + Returns: + torch.Tensor: Encoded tensor with additional information. + """ + if not isinstance(x, torch.Tensor): + raise TypeError(f"Expected input x to be torch.Tensor, but got {type(x)}.") + if len(x.shape) != 5: + raise ValueError(f"Expected input tensor x to have shape (N, C, T, H, W), but got {x.shape}.") + + if not hasattr(vae, "encoder") or not callable(vae.encoder): + raise AttributeError("Encoder is not defined or callable. Please initialize 'self.encoder'.") + + # for setting vae encoding to deterministic + N, C, T, H, W = x.shape + if T == 1: + x = x.expand(-1, -1, 4, -1, -1) + x = vae.encoder(x) + posterior = DiagonalGaussianDistribution(x) + z = posterior.mode() + + return z[:, :, :1, :, :].type(x.dtype) + else: + x = vae.encoder(x) + posterior = DiagonalGaussianDistribution(x) + z = posterior.mode() + + return z.type(x.dtype) + + @staticmethod + def encode( + video: torch.Tensor, + vae: VideoTokenizerABC, + tile_sample_min_length: int = 16, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + allow_spatial_tiling: bool = True, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Encode the input tensor. + Args: + video (torch.Tensor): Input tensor with shape (N, T, C, H, W). + vae (VideoTokenizerABC): Pretrained VAE model. + tile_sample_min_length (int): Minimum length of the tile sample. + tile_sample_min_height (int): Minimum height of the tile sample. + tile_sample_min_width (int): Minimum width of the tile sample. + spatial_tile_overlap_factor (float): Spatial tile overlap factor. + allow_spatial_tiling (bool): Allow spatial tiling. + parallel_group (ProcessGroup): Distributed encoding group. + Returns: + torch.Tensor: Encoded tensor. + """ + assert video.dim() == 5, f"Expected input tensor to have shape (N, T, C, H, W), but got {video.shape}." + video = video.cuda() + video = (video / 127.5) - 1.0 + video = video.bfloat16() + moments = vae.tiled_encode_3d( + video, + tile_sample_min_length=tile_sample_min_length, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + allow_spatial_tiling=allow_spatial_tiling, + parallel_group=parallel_group, + ) + + return moments + + @staticmethod + def decode( + chunk: torch.Tensor, + vae: VideoTokenizerABC, + tile_sample_min_height: int = 256, + tile_sample_min_width: int = 256, + spatial_tile_overlap_factor: float = 0.25, + temporal_tile_overlap_factor: float = 0, + tile_sample_min_length: int = 16, + allow_spatial_tiling: bool = True, + uint8_output: bool = True, + parallel_group: torch.distributed.ProcessGroup = None, + ) -> torch.Tensor: + """ + Decode the input tensor. + Args: + chunk (torch.Tensor): Input tensor with shape (N, C, T, H, W). + vae (VideoTokenizerABC): Pretrained VAE model. + tile_sample_min_length (int): Minimum length of the tile sample. + tile_sample_min_height (int): Minimum height of the tile sample. + tile_sample_min_width (int): Minimum width of the tile sample. + spatial_tile_overlap_factor (float): Spatial tile overlap factor. + temporal_tile_overlap_factor (float): Temporal tile overlap factor. + allow_spatial_tiling (bool): Allow spatial tiling. + uint8_output (bool): Whether to output uint8 tensor. + parallel_group (ProcessGroup): Distributed decoding group. + Returns: + torch.Tensor: Decoded tensor. + """ + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + chunk = vae.tiled_decode_3d( + chunk, + tile_sample_min_height=tile_sample_min_height, + tile_sample_min_width=tile_sample_min_width, + spatial_tile_overlap_factor=spatial_tile_overlap_factor, + temporal_tile_overlap_factor=temporal_tile_overlap_factor, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=allow_spatial_tiling, + parallel_group=parallel_group, + ) + chunk = rearrange(chunk, "b c t h w -> (b t) c h w") + if uint8_output: + chunk = (chunk * 127.5) + 127.5 + chunk = chunk.clamp(0, 255) + chunk = chunk.type(torch.uint8) + return chunk + + +############################################ +# Process to get prefix video +########################################### + + +def ffmpeg_i2v(image_path, w=384, h=224, aspect_policy="fit"): + r = ffmpeg.input("pipe:0", format="image2pipe") + if aspect_policy == "crop": + r = r.filter("scale", w, h, force_original_aspect_ratio="increase").filter("crop", w, h) + elif aspect_policy == "pad": + r = r.filter("scale", w, h, force_original_aspect_ratio="decrease").filter( + "pad", w, h, "(ow-iw)/2", "(oh-ih)/2", color="black" + ) + elif aspect_policy == "fit": + r = r.filter("scale", w, h) + else: + magi_logger.warning(f"Unknown aspect policy: {aspect_policy}, using fit as fallback") + r = r.filter("scale", w, h) + image_byte = open(image_path, "rb").read() + try: + out, _ = r.output("pipe:", format="rawvideo", pix_fmt="rgb24", vframes=1).run( + input=image_byte, capture_stdout=True, capture_stderr=True + ) + except ffmpeg.Error as e: + print(f"Error occurred: {e.stderr.decode()}") + raise e + + video = torch.frombuffer(out, dtype=torch.uint8).view(1, h, w, 3) + return video + + +def ffmpeg_v2v(video_path, fps, w=384, h=224, prefix_frame=None, prefix_video_max_chunk=5): + if video_path is None: + return None + out, _ = ( + ffmpeg.input(video_path, ss=0, format="mp4") + .filter("fps", fps=fps) + .filter("scale", w, h) + .output("pipe:", format="rawvideo", pix_fmt="rgb24", nostdin=None) + .run(capture_stdout=True, capture_stderr=True) + ) + + video = torch.frombuffer(out, dtype=torch.uint8).view(-1, h, w, 3) + + if prefix_frame is not None: + return video[:prefix_frame] + else: + num_frames_to_read = video.shape[0] + if num_frames_to_read < fps: + clip_length = 1 + else: + PREFIX_VIDEO_MAX_FRAMES = prefix_video_max_chunk * fps + clip_length = min(num_frames_to_read // fps * fps, PREFIX_VIDEO_MAX_FRAMES) + return video[-clip_length:] + + +def save_video_to_disk(video: torch.Tensor, save_path: str, fps: int) -> bytes: + # TCHW -> THWC + video = video.permute(0, 2, 3, 1).cpu().numpy() + _, H, W, _ = video.shape + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_file.write(video.tobytes()) + temp_file.flush() + temp_file_path = temp_file.name + + try: + output, err = ( + ffmpeg + .input(temp_file_path, format="rawvideo", pix_fmt="rgb24", s=f"{W}x{H}", r=fps) + .output(save_path, format='mp4', vcodec='libx264', pix_fmt='yuv420p') + .overwrite_output() + .run(capture_stdout=True, capture_stderr=True) + ) + print("✅ Video saved successfully.") + except ffmpeg.Error as e: + stderr_output = e.stderr.decode('utf8') if e.stderr else "No stderr output" + print("❌ FFmpeg Error:") + print("="*60) + print(stderr_output) + print("="*60) + raise RuntimeError("Failed to encode video with FFmpeg") from e + + os.remove(temp_file_path) + return output + + os.remove(temp_file_path) + return output + + +def encode_prefix_video(prefix_video, fps, vae_ckpt, scale_factor, parallel_group): + if prefix_video is None: + return None + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated before vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved before vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + # THWC -> NCTHW + prefix_video = prefix_video.permute(3, 0, 1, 2).unsqueeze(0) + magi_logger.debug(f"prefix_video.shape: {prefix_video.shape}") + vae_model = VaeHelper.get_vae(vae_ckpt) + tile_sample_min_length = fps // 2 + prefix_video = VaeHelper.encode( + prefix_video, + vae_model, + tile_sample_min_height=256, + tile_sample_min_width=256, + spatial_tile_overlap_factor=0.25, + temporal_tile_overlap_factor=0, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=True, + parallel_group=parallel_group, + ) + prefix_video = prefix_video * scale_factor + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated after vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved after vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + return prefix_video + + +def process_image(image_path: str, config: MagiConfig) -> torch.Tensor: + prefix_video = ffmpeg_i2v(image_path, w=config.runtime_config.video_size_w, h=config.runtime_config.video_size_h) + prefix_video = encode_prefix_video( + prefix_video, + config.runtime_config.fps, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + return prefix_video + + +def process_prefix_video(prefix_video_path: str, config: MagiConfig) -> torch.Tensor: + prefix_video = ffmpeg_v2v( + prefix_video_path, + fps=config.runtime_config.fps, + prefix_frame=None, # Modified + w=config.runtime_config.video_size_w, + h=config.runtime_config.video_size_h, + ) + prefix_video = encode_prefix_video( + prefix_video, + config.runtime_config.fps, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + return prefix_video + + +############################################ +# Process to get final video +############################################ +def decode_chunk(chunk, vae_ckpt, scale_factor, tile_sample_min_length, parallel_group): + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated before vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved before vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + + vae_model = VaeHelper.get_vae(vae_ckpt) + decoded_chunk = VaeHelper.decode( + chunk / scale_factor, + vae_model, + tile_sample_min_height=256, + tile_sample_min_width=256, + spatial_tile_overlap_factor=0.25, + temporal_tile_overlap_factor=0, + tile_sample_min_length=tile_sample_min_length, + allow_spatial_tiling=True, + parallel_group=parallel_group, + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory allocated after vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB" + ) + magi_logger.debug( + f"rank {torch.distributed.get_rank()} memory reserved after vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB" + ) + return decoded_chunk + + +def post_chunk_process(chunk: torch.Tensor, config: MagiConfig): + tile_sample_min_length = config.runtime_config.fps // 2 + chunk = decode_chunk( + chunk, + config.runtime_config.vae_pretrained, + config.runtime_config.scale_factor, + tile_sample_min_length, + parallel_group=mpu.get_tp_group(with_context_parallel=True), + ) + gc.collect() + torch.cuda.empty_cache() + return chunk diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/outputs/dev4_sweep_latest.log b/FlowCache/FlowCache4MAGI-1-dev3-motion/outputs/dev4_sweep_latest.log new file mode 100644 index 0000000000000000000000000000000000000000..0bbf93adb0ce8ee9e9489815871f54de92d5ea8a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/outputs/dev4_sweep_latest.log @@ -0,0 +1,754 @@ +dev4 sweep tau=0.012 frames=120 -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion/outputs/hparam_sweep_20260614_063749 +========== [dev4] tau0.012_max_w3_da0.5_lam0.5 (PYTHONPATH=/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail:/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion) ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W614 08:40:25.888062994 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-06-14 08:40:25,341 - INFO] Initialize torch distribution and model parallel successfully +[2026-06-14 08:40:25,341 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=120, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-06-14 08:40:25,341 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.5, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'max'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = max +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.5, 'detail_window_size': 5, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'max'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 5 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = max +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.4, 'detail_lambda': 0.5, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'max'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.4 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = max +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.6, 'detail_lambda': 0.5, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'max'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.6 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = max +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.3, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'blend'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.3 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = blend +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.5, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'blend'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = blend +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.7, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'blend'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.7 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = blend +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.5, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'product'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = product +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.5, 'detail_window_size': 5, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'product'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.5 +Added to args: detail_window_size = 5 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = product +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'detail_alpha': 0.5, 'detail_lambda': 0.3, 'detail_window_size': 3, 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5, 'weight_combine_mode': 'blend'} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: detail_alpha = 0.5 +Added to args: detail_lambda = 0.3 +Added to args: detail_window_size = 3 +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Added to args: weight_combine_mode = blend +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.01, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.01 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.012, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.012 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.015, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.015 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.018, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.018 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.02, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.02 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.025, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.025 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.03, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.03 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00 + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_max_w3_da0.5_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_max_w5_da0.5_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_max_w5_da0.5_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_max_w3_da0.4_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_max_w3_da0.4_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_max_w3_da0.6_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_max_w3_da0.6_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_blend_w3_da0.5_lam0.3 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_blend_w3_da0.5_lam0.3 (rc=1, no video) + +========== [dev4] tau0.015_blend_w3_da0.5_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_blend_w3_da0.5_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_blend_w3_da0.5_lam0.7 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_blend_w3_da0.5_lam0.7 (rc=1, no video) + +========== [dev4] tau0.015_product_w3_da0.5_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_product_w3_da0.5_lam0.5 (rc=1, no video) + +========== [dev4] tau0.015_product_w5_da0.5_lam0.5 ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +Traceback (most recent call last): + File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail/inference/pipeline/motioncache.py", line 34, in + from inference.pipeline.cache.motiondetailcache import MotionDetailCache +ModuleNotFoundError: No module named 'inference.pipeline.cache.motiondetailcache' +FAILED: tau0.015_product_w5_da0.5_lam0.5 (rc=1, no video) +Full validation at 240 frames... + +========== [dev3_full] tau0.012_240f ========== +/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers + warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning) +[W614 07:18:29.363647792 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator()) +[2026-06-14 07:18:29,816 - INFO] Initialize torch distribution and model parallel successfully +[2026-06-14 07:18:29,816 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=64, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=False, enable_cuda_graph=False)) +[2026-06-14 07:18:29,816 - INFO] Precompute validation prompt embeddings +You are using the default legacy behaviour of the . This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565 +Loading additional config: {'alpha': 0.5, 'compress_kv_cache': True, 'compress_strategy': 'token', 'discard_nearly_clean_chunk': True, 'log': False, 'mix_lambda': 0.07, 'phase1_steps': 9, 'power': 3, 'print_peak_memory': True, 'query_granularity': 'frame', 'rel_l1_thresh': 0.015, 'score_weighting_method': 'no_weight', 'total_cache_chunk_nums': 5, 'warmup_steps': 5} +Added to args: alpha = 0.5 +Added to args: compress_kv_cache = True +Added to args: compress_strategy = token +Added to args: discard_nearly_clean_chunk = True +Added to args: log = False +Added to args: mix_lambda = 0.07 +Added to args: phase1_steps = 9 +Added to args: power = 3 +Added to args: print_peak_memory = True +Added to args: query_granularity = frame +Added to args: rel_l1_thresh = 0.015 +Added to args: score_weighting_method = no_weight +Added to args: total_cache_chunk_nums = 5 +Added to args: warmup_steps = 5 +Running on GPU: NVIDIA H800 +GPU Memory before pipeline: 0.00 GB + Loading checkpoint shards: 0%| | 0/2 [00:00= max_frames: + break + idx += 1 + cap.release() + return np.stack(frames) if frames else None + + +def align_frames(gt, gen): + import cv2 + import numpy as np + + n = min(len(gt), len(gen)) + gt = gt[:n] + gen = gen[:n] + if gt.shape[1:3] != gen.shape[1:3]: + h, w = gt.shape[1], gt.shape[2] + gen = np.stack([cv2.resize(f, (w, h)) for f in gen]) + return gt, gen + + +def psnr(gt, gen): + import numpy as np + + gt, gen = align_frames(gt, gen) + mse = np.mean((gt.astype(np.float32) - gen.astype(np.float32)) ** 2) + if mse == 0: + return float("inf") + return 10 * np.log10(255**2 / mse) + + +def ssim_simple(gt, gen): + import numpy as np + + gt, gen = align_frames(gt, gen) + gt_f = gt.astype(np.float32) / 255.0 + gen_f = gen.astype(np.float32) / 255.0 + mu_g = gt_f.mean() + mu_p = gen_f.mean() + var_g = gt_f.var() + var_p = gen_f.var() + cov = ((gt_f - mu_g) * (gen_f - mu_p)).mean() + c1, c2 = 0.01**2, 0.03**2 + return ((2 * mu_g * mu_p + c1) * (2 * cov + c2)) / ((mu_g**2 + mu_p**2 + c1) * (var_g + var_p + c2)) + + +def black_ratio(frames, thresh=5): + import numpy as np + return float(np.mean(frames.max(axis=-1) < thresh)) + + +def parse_log(log_path): + reuse_rates = [] + peak_gb = None + with open(log_path, "r", errors="ignore") as f: + text = f.read() + for m in re.finditer(r"reuse_rate=([\d.]+)%", text): + reuse_rates.append(float(m.group(1))) + m = re.search(r"Peak memory allocated:\s*([\d.]+)\s*GB", text) + if m: + peak_gb = float(m.group(1)) + avg_reuse = sum(reuse_rates) / len(reuse_rates) if reuse_rates else None + return avg_reuse, peak_gb + + +def parse_metric(metric_path): + with open(metric_path, "r") as f: + payload = json.load(f) + summary = payload.get("chunk_execution_summary", {}) + rates = [v["reuse_rate"] for v in summary.values()] + return (sum(rates) / len(rates) * 100) if rates else None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--baseline", required=True) + parser.add_argument("--generated", required=True) + parser.add_argument("--log", required=True) + parser.add_argument("--metric", default="") + args = parser.parse_args() + + gt = load_video_frames(args.baseline) + gen = load_video_frames(args.generated) + if gt is None or gen is None: + print("PSNR=NA,SSIM=NA,BLACK=NA,REUSE=NA,PEAK=NA") + return + + p = psnr(gt, gen) + s = ssim_simple(gt, gen) + b = black_ratio(gen) + reuse, peak = parse_log(args.log) + if args.metric: + metric_reuse = parse_metric(args.metric) + if metric_reuse is not None: + reuse = metric_reuse + + psnr_s = "inf" if p == float("inf") else f"{p:.4f}" + ssim_s = f"{s:.6f}" + black_s = f"{b:.6f}" + reuse_s = f"{reuse:.2f}" if reuse is not None else "NA" + peak_s = f"{peak:.2f}" if peak is not None else "NA" + print(f"PSNR={psnr_s}") + print(f"SSIM={ssim_s}") + print(f"BLACK={black_s}") + print(f"REUSE={reuse_s}") + print(f"PEAK={peak_s}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/generate_comparison_report.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/generate_comparison_report.py new file mode 100644 index 0000000000000000000000000000000000000000..35a2065a3105b950784a0bb7f1ffe7132b0ed60a --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/generate_comparison_report.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Generate markdown comparison report from hparam sweep CSV.""" + +import argparse +import csv +from datetime import datetime +from pathlib import Path + + +def score_row(r): + try: + psnr = float(r["psnr_db"]) + if psnr == float("inf"): + psnr = 100.0 + reuse = float(r["reuse_rate_pct"] or 0) + wall = float(r["wall_sec"] or 99999) + # Quality-first with mild speed bonus; penalize very slow + return psnr + 0.015 * reuse - 0.0001 * wall + except (ValueError, TypeError): + return -9999 + + +def fmt_psnr(v): + try: + f = float(v) + if f > 50: + return "∞" + return f"{f:.2f} dB" + except (ValueError, TypeError): + return "N/A" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--results", required=True) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--sweep_dir", default="") + args = parser.parse_args() + + rows = list(csv.DictReader(open(args.results))) + dev3 = [r for r in rows if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")] + dev4 = [r for r in rows if r["version"] == "dev4" and r["psnr_db"] not in ("NA", "")] + dev3_full = [r for r in rows if r["version"] == "dev3_full" and r["psnr_db"] not in ("NA", "")] + dev4_full = [r for r in rows if r["version"] == "dev4_full" and r["psnr_db"] not in ("NA", "")] + + best_dev3 = max(dev3, key=score_row) if dev3 else None + best_dev4 = max(dev4, key=score_row) if dev4 else None + + lines = [ + "# MotionCache (dev3) vs MotionDetailCache (dev4) 超参对比报告", + "", + f"生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", + "", + f"Baseline:`{args.baseline}`(FlowCache 全量推理)", + f"Sweep 目录:`{args.sweep_dir}`", + "", + "## 评分方法", + "", + "综合得分 = PSNR + 0.015 × reuse_rate(%) − 0.0001 × wall_time(s)", + "(画质优先,适度奖励更高 reuse、更短耗时)", + "", + ] + + if best_dev3: + lines += [ + "## dev3 最优超参(120 帧 sweep)", + "", + f"| 参数 | 值 |", + f"|------|-----|", + f"| rel_l1_thresh (τ) | **{best_dev3['tau']}** |", + f"| alpha | {best_dev3['alpha']} |", + f"| PSNR | {fmt_psnr(best_dev3['psnr_db'])} |", + f"| SSIM | {best_dev3['ssim']} |", + f"| reuse_rate | {best_dev3['reuse_rate_pct']}% |", + f"| 耗时 | {best_dev3['wall_sec']}s |", + f"| variant | `{best_dev3['variant']}` |", + "", + ] + + if best_dev4: + lines += [ + "## dev4 最优超参(120 帧 sweep,τ 固定为 dev3 最优)", + "", + f"| 参数 | 值 |", + f"|------|-----|", + f"| rel_l1_thresh (τ) | {best_dev4['tau']} |", + f"| detail_alpha | **{best_dev4['detail_alpha']}** |", + f"| detail_window_size | **{best_dev4['detail_window']}** |", + f"| weight_combine_mode | **{best_dev4['combine_mode']}** |", + f"| detail_lambda | {best_dev4['detail_lambda']} |", + f"| PSNR | {fmt_psnr(best_dev4['psnr_db'])} |", + f"| SSIM | {best_dev4['ssim']} |", + f"| reuse_rate | {best_dev4['reuse_rate_pct']}% |", + f"| 耗时 | {best_dev4['wall_sec']}s |", + f"| variant | `{best_dev4['variant']}` |", + "", + ] + + lines += ["## dev3 全量 τ sweep 结果", "", "| τ | PSNR | reuse% | 耗时(s) | 得分 |", "|---|------|--------|---------|------|"] + for r in sorted(dev3, key=lambda x: float(x["tau"])): + lines.append( + f"| {r['tau']} | {fmt_psnr(r['psnr_db'])} | {r['reuse_rate_pct']} | {r['wall_sec']} | {score_row(r):.3f} |" + ) + lines.append("") + + lines += ["## dev4 全量 detail sweep 结果", "", "| mode | win | d_α | λ | PSNR | reuse% | 耗时(s) | 得分 |", "|------|-----|-----|---|------|--------|---------|------|"] + for r in sorted(dev4, key=score_row, reverse=True): + lines.append( + f"| {r['combine_mode']} | {r['detail_window']} | {r['detail_alpha']} | {r['detail_lambda']} " + f"| {fmt_psnr(r['psnr_db'])} | {r['reuse_rate_pct']} | {r['wall_sec']} | {score_row(r):.3f} |" + ) + lines.append("") + + if dev3_full or dev4_full: + lines += ["## 240 帧全分辨率验证", "", "| 版本 | PSNR | reuse% | 耗时(s) |", "|------|------|--------|---------|"] + for r in dev3_full + dev4_full: + lines.append(f"| {r['version']} ({r['variant']}) | {fmt_psnr(r['psnr_db'])} | {r['reuse_rate_pct']} | {r['wall_sec']} |") + lines.append("") + + if best_dev3 and best_dev4: + d3p = float(best_dev3["psnr_db"]) if best_dev3["psnr_db"] != "inf" else 100 + d4p = float(best_dev4["psnr_db"]) if best_dev4["psnr_db"] != "inf" else 100 + d3r = float(best_dev3["reuse_rate_pct"] or 0) + d4r = float(best_dev4["reuse_rate_pct"] or 0) + d3t = float(best_dev3["wall_sec"]) + d4t = float(best_dev4["wall_sec"]) + lines += [ + "## 结论摘要", + "", + f"- **dev3 推荐配置**:τ={best_dev3['tau']},PSNR {fmt_psnr(best_dev3['psnr_db'])},reuse {d3r:.1f}%", + f"- **dev4 推荐配置**:mode={best_dev4['combine_mode']}, window={best_dev4['detail_window']}, " + f"detail_α={best_dev4['detail_alpha']}, λ={best_dev4['detail_lambda']}," + f"PSNR {fmt_psnr(best_dev4['psnr_db'])},reuse {d4r:.1f}%", + f"- dev4 vs dev3 PSNR 差:{d4p - d3p:+.2f} dB;reuse 差:{d4r - d3r:+.1f}%;耗时差:{d4t - d3t:+.0f}s", + "", + "### 推荐 yaml 片段", + "", + "**dev3** (`motioncache_config.yaml`):", + "```yaml", + f"rel_l1_thresh: {best_dev3['tau']}", + "alpha: 0.5", + "phase1_steps: 9", + "warmup_steps: 5", + "```", + "", + "**dev4** (`motiondetail_config.yaml`):", + "```yaml", + f"rel_l1_thresh: {best_dev4['tau']}", + f"detail_alpha: {best_dev4['detail_alpha']}", + f"detail_window_size: {int(float(best_dev4['detail_window']))}", + f"weight_combine_mode: {best_dev4['combine_mode']}", + f"detail_lambda: {best_dev4['detail_lambda']}", + "alpha: 0.5", + "phase1_steps: 9", + "warmup_steps: 5", + "```", + ] + + Path(args.output).write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"Report written to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_l1_rel.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_l1_rel.py new file mode 100644 index 0000000000000000000000000000000000000000..b117dbc6d97323a0ad71303b700f2cc251773257 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_l1_rel.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 + +import argparse +import json +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +def parse_int_list(value: Optional[str]) -> Optional[Set[int]]: + if not value: + return None + return {int(item.strip()) for item in value.split(",") if item.strip()} + + +def load_l1_rel_records(json_path: Path) -> List[dict]: + with json_path.open("r") as f: + payload = json.load(f) + if isinstance(payload, list): + return payload + if isinstance(payload, dict) and isinstance(payload.get("records"), list): + return payload["records"] + raise ValueError(f"Cannot find records in {json_path}") + + +def collect_by_chunk(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]: + chunks = defaultdict(list) + for record in records: + chunk_idx = int(record["chunk_idx"]) + if chunk_ids is not None and chunk_idx not in chunk_ids: + continue + chunks[chunk_idx].append(record) + + chunks = dict(sorted(chunks.items())) + if max_chunks is not None: + chunks = dict(list(chunks.items())[:max_chunks]) + return chunks + + +def plot_l1_rel( + chunks: Dict[int, List[dict]], + output_path: Path, + x_field: str, + y_field: str, + reverse_x: bool, + title: Optional[str], + figsize: Tuple[float, float], + dpi: int, +) -> None: + fig, ax = plt.subplots(figsize=figsize) + + for chunk_idx, records in chunks.items(): + points = [] + for record in records: + if x_field not in record or y_field not in record: + continue + if record[x_field] is None or record[y_field] is None: + continue + points.append((float(record[x_field]), float(record[y_field]))) + if not points: + continue + + points.sort(key=lambda item: item[0]) + xs, ys = zip(*points) + ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}") + + ax.set_xlabel(x_field) + ax.set_ylabel(y_field) + ax.set_title(title or f"{y_field} by timestep") + ax.grid(True, alpha=0.3) + if reverse_x: + ax.invert_xaxis() + ax.legend(loc="best", fontsize="small", ncols=2) + fig.tight_layout() + + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=dpi) + plt.close(fig) + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Plot per-chunk MAGI relative L1 change curves.") + parser.add_argument("json_path", type=Path, help="Path to L1 relative change JSON saved by --l1_rel_stats_path.") + parser.add_argument("-o", "--output", type=Path, help="Output image path. Defaults to _plot.png.") + parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.") + parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.") + parser.add_argument( + "--x-field", + choices=["timestep", "next_timestep", "cur_denoise_step", "denoise_idx"], + default="next_timestep", + help="Record field used for the x axis. next_timestep is the cleaner MAGI step.", + ) + parser.add_argument( + "--y-field", + choices=[ + "l1_rel", + "l1_rel_ratio", + "delta_l1_norm", + "x_l1_norm", + "x_embedder_l1_rel", + "x_embedder_l1_rel_ratio", + "x_embedder_delta_l1_norm", + "x_embedder_x_l1_norm", + "flowcache_rel_l1", + "flowcache_rel_l1_ratio", + "flowcache_delta_l1_norm", + "flowcache_prev_feat_l1_norm", + "flowcache_accumulated_rel_l1", + "rel_l1_thresh", + ], + default="l1_rel", + help="Record field used for the y axis.", + ) + parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.") + parser.add_argument("--title", type=str, help="Figure title.") + parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.") + parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.") + return parser.parse_args() + + +def main(): + args = parse_arguments() + output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_plot.png") + figsize = [float(part.strip()) for part in args.figsize.split(",")] + if len(figsize) != 2: + raise ValueError("--figsize must be formatted as width,height") + + records = load_l1_rel_records(args.json_path) + chunks = collect_by_chunk(records, parse_int_list(args.chunks), args.max_chunks) + if not chunks: + raise ValueError("No records matched the requested chunks.") + + plot_l1_rel( + chunks=chunks, + output_path=output_path, + x_field=args.x_field, + y_field=args.y_field, + reverse_x=args.reverse_x, + title=args.title, + figsize=(figsize[0], figsize[1]), + dpi=args.dpi, + ) + print(f"Saved plot to {output_path}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_residual_norms.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_residual_norms.py new file mode 100644 index 0000000000000000000000000000000000000000..600e0c35144bca5f6cdc48e6c4e2098972e358ff --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/plot_residual_norms.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 + +import argparse +import json +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +def parse_int_list(value: Optional[str]) -> Optional[Set[int]]: + if not value: + return None + return {int(item.strip()) for item in value.split(",") if item.strip()} + + +def load_records(json_path: Path) -> List[dict]: + with json_path.open("r") as f: + payload = json.load(f) + if isinstance(payload, list): + return payload + if isinstance(payload, dict) and isinstance(payload.get("records"), list): + return payload["records"] + raise ValueError(f"Cannot find records in {json_path}") + + +def group_records(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]: + grouped = defaultdict(list) + for record in records: + chunk_idx = int(record["chunk_idx"]) + if chunk_ids is not None and chunk_idx not in chunk_ids: + continue + grouped[chunk_idx].append(record) + + grouped = dict(sorted(grouped.items())) + if max_chunks is not None: + grouped = dict(list(grouped.items())[:max_chunks]) + return grouped + + +def build_plot( + grouped_records: Dict[int, List[dict]], + output_path: Path, + x_field: str, + y_field: str, + title: Optional[str], + reverse_x: bool, + figsize: Tuple[float, float], + dpi: int, +) -> None: + fig, ax = plt.subplots(figsize=figsize) + + for chunk_idx, records in grouped_records.items(): + points = [] + for record in records: + if x_field not in record or y_field not in record: + continue + if record[x_field] is None or record[y_field] is None: + continue + points.append((float(record[x_field]), float(record[y_field]))) + if not points: + continue + + points.sort(key=lambda item: item[0]) + xs, ys = zip(*points) + ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}") + + ax.set_xlabel(x_field) + ax.set_ylabel(y_field) + ax.set_title(title or f"{y_field} by timestep") + ax.grid(True, alpha=0.3) + if reverse_x: + ax.invert_xaxis() + ax.legend(loc="best", fontsize="small", ncols=2) + fig.tight_layout() + + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=dpi) + plt.close(fig) + + +def parse_arguments(): + parser = argparse.ArgumentParser(description="Plot per-chunk residual norm curves from MAGI residual stats JSON.") + parser.add_argument("json_path", type=Path, help="Path to residual stats JSON saved by --residual_stats_path.") + parser.add_argument( + "-o", + "--output", + type=Path, + help="Output image path. Defaults to _residual_norms.png.", + ) + parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.") + parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.") + parser.add_argument( + "--x-field", + choices=["timestep", "cur_denoise_step", "denoise_idx"], + default="timestep", + help="Record field used for the x axis.", + ) + parser.add_argument( + "--y-field", + choices=["residual_norm", "residual_diff_norm"], + default="residual_norm", + help="Record field used for the y axis.", + ) + parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.") + parser.add_argument("--title", type=str, help="Figure title.") + parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.") + parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.") + return parser.parse_args() + + +def main(): + args = parse_arguments() + output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_residual_norms.png") + figsize_parts = [float(part.strip()) for part in args.figsize.split(",")] + if len(figsize_parts) != 2: + raise ValueError("--figsize must be formatted as width,height") + + records = load_records(args.json_path) + grouped_records = group_records(records, parse_int_list(args.chunks), args.max_chunks) + if not grouped_records: + raise ValueError("No records matched the requested chunks.") + + build_plot( + grouped_records=grouped_records, + output_path=output_path, + x_field=args.x_field, + y_field=args.y_field, + title=args.title, + reverse_x=args.reverse_x, + figsize=(figsize_parts[0], figsize_parts[1]), + dpi=args.dpi, + ) + print(f"Saved plot to {output_path}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/quick_psnr.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/quick_psnr.py new file mode 100644 index 0000000000000000000000000000000000000000..326048ec01e084a3cdf10dc221eedcd316733289 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/quick_psnr.py @@ -0,0 +1,43 @@ +import cv2 +import numpy as np +import sys + + +def load_frames(path): + cap = cv2.VideoCapture(path) + frames = [] + while True: + ret, img = cap.read() + if not ret: + break + frames.append(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + cap.release() + return frames + + +def psnr(gt, gen): + gt = np.stack(gt).astype(np.float32) + gen = np.stack(gen).astype(np.float32) + if gt.shape != gen.shape: + h, w = gt.shape[1], gt.shape[2] + gen = np.stack([cv2.resize(f, (w, h)) for f in gen]) + mse = np.mean((gt - gen) ** 2) + if mse == 0: + return float("inf") + return 10 * np.log10(255**2 / mse) + + +def black_ratio(frames, thresh=5): + arr = np.stack(frames) + return float(np.mean(arr.max(axis=-1) < thresh)) + + +if __name__ == "__main__": + gt_path = sys.argv[1] + gen_path = sys.argv[2] + gt = load_frames(gt_path) + gen = load_frames(gen_path) + print(f"GT: {len(gt)} frames {gt[0].shape}") + print(f"Gen: {len(gen)} frames {gen[0].shape}") + print(f"PSNR: {psnr(gt, gen):.2f} dB") + print(f"Black ratio: {black_ratio(gen):.4f}") diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/reeval_sweep.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/reeval_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..d91b03a71f4494151e6daa187b29548fab66ca11 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/reeval_sweep.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Re-evaluate all runs in a sweep directory and refresh results.csv.""" + +import argparse +import csv +import subprocess +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--sweep_dir", required=True) + parser.add_argument("--baseline", required=True) + parser.add_argument("--eval_script", required=True) + args = parser.parse_args() + + sweep = Path(args.sweep_dir) + csv_path = sweep / "report" / "results.csv" + rows = list(csv.DictReader(open(csv_path))) if csv_path.exists() else [] + + updated = [] + for row in rows: + out = Path(row["video_path"]) + log = Path(row["log_path"]) + metric = out.parent / "metrics.json" + if not out.exists(): + updated.append(row) + continue + cmd = [ + "python3", args.eval_script, + "--baseline", args.baseline, + "--generated", str(out), + "--log", str(log), + ] + if metric.exists(): + cmd += ["--metric", str(metric)] + proc = subprocess.run(cmd, capture_output=True, text=True) + metrics = {} + for line in proc.stdout.splitlines(): + if "=" in line: + k, v = line.split("=", 1) + metrics[k] = v + row["psnr_db"] = metrics.get("PSNR", row.get("psnr_db", "NA")) + row["ssim"] = metrics.get("SSIM", row.get("ssim", "NA")) + row["black_ratio"] = metrics.get("BLACK", row.get("black_ratio", "NA")) + row["reuse_rate_pct"] = metrics.get("REUSE", row.get("reuse_rate_pct", "NA")) + row["peak_gb"] = metrics.get("PEAK", row.get("peak_gb", "NA")) + updated.append(row) + print(f"{row['variant']}: PSNR={row['psnr_db']} reuse={row['reuse_rate_pct']}%") + + fieldnames = list(updated[0].keys()) if updated else [] + with open(csv_path, "w", newline="") as f: + w = csv.DictWriter(f, fieldnames=fieldnames) + w.writeheader() + w.writerows(updated) + print(f"Updated {csv_path}") + + +if __name__ == "__main__": + main() diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_dev4_sweep.sh b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_dev4_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a7b30a399efb72a1e08cde4d63917320ed7ae55 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_dev4_sweep.sh @@ -0,0 +1,204 @@ +#!/usr/bin/env bash +# Continue dev4 hyperparameter sweep and merge with existing dev3 results. +set -euo pipefail + +GPU_ID="${CUDA_VISIBLE_DEVICES:-1}" +SWEEP_FRAMES="${SWEEP_FRAMES:-120}" +BEST_DEV3_TAU="${BEST_DEV3_TAU:-0.012}" +PROMPT="${PROMPT:-a woman dancing.}" +BASELINE="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/a_woman_dancing_2026-05-19_09-49-14/output_2026-05-19_09-49-14.mp4" +FLOWCACHE_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion" +DETAIL_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail" +SWEEP_ROOT="${SWEEP_ROOT:-$FLOWCACHE_ROOT/outputs/hparam_sweep_20260614_063749}" +REPORT_DIR="$SWEEP_ROOT/report" +RESULTS_CSV="$REPORT_DIR/results.csv" +DEV3_CSV="$REPORT_DIR/dev3_results.csv" + +export MASTER_ADDR=localhost +export CUDA_VISIBLE_DEVICES="$GPU_ID" +export PAD_HQ=1 PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true OFFLOAD_VAE_CACHE=true + +if [ -z "${CONDA_DEFAULT_ENV:-}" ] || [ "${CONDA_DEFAULT_ENV}" != "magi" ]; then + source "${HOME}/miniforge3/etc/profile.d/conda.sh" 2>/dev/null || source "${HOME}/anaconda3/etc/profile.d/conda.sh" + conda activate magi +fi + +python3 - <<'PY' +import numpy as np +if int(np.__version__.split(".")[0]) >= 2: + import subprocess + subprocess.check_call(["pip", "install", "-q", "numpy>=1.24,<2.0"]) +PY + +make_runtime_config() { + python3 - "$1" "$2" <<'PY' +import json, sys +dst, frames = int(sys.argv[2]) if False else sys.argv[1], int(sys.argv[2]) +src = "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json" +with open(src) as f: + cfg = json.load(f) +cfg["runtime_config"]["num_frames"] = frames +with open(dst, "w") as f: + json.dump(cfg, f, indent=4) +PY +} + +write_yaml() { + python3 - "$1" "${@:2}" <<'PY' +import sys, yaml +path = sys.argv[1] +params = {} +for kv in sys.argv[2:]: + k, v = kv.split("=", 1) + if v.lower() in ("true", "false"): + params[k] = v.lower() == "true" + elif v.replace(".", "", 1).isdigit(): + params[k] = float(v) if "." in v else int(v) + else: + params[k] = v +base = { + "warmup_steps": 5, "phase1_steps": 9, "alpha": 0.5, + "discard_nearly_clean_chunk": True, "compress_kv_cache": True, + "total_cache_chunk_nums": 5, "compress_strategy": "token", + "mix_lambda": 0.07, "query_granularity": "frame", + "score_weighting_method": "no_weight", "power": 3, + "log": False, "print_peak_memory": True, +} +base.update(params) +with open(path, "w") as f: + yaml.dump(base, f, default_flow_style=False) +PY +} + +run_one() { + local version="$1" run_id="$2" yaml_path="$3" root_dir="$4" + local exp_dir="$SWEEP_ROOT/${version}_${run_id}" + mkdir -p "$exp_dir" + local out="$exp_dir/output.mp4" log="$exp_dir/infer.log" metric="$exp_dir/metrics.json" + export MASTER_PORT=$((6100 + RANDOM % 400)) + if [ "$root_dir" = "$DETAIL_ROOT" ]; then + export PYTHONPATH="${DETAIL_ROOT}:${FLOWCACHE_ROOT}" + else + export PYTHONPATH="${FLOWCACHE_ROOT}:${DETAIL_ROOT}" + fi + echo "========== [$version] $run_id (PYTHONPATH=$PYTHONPATH) ==========" + local t0 t1 elapsed + t0=$(date +%s) + set +e + ( cd "$root_dir" && python3 inference/pipeline/motioncache.py \ + --config_file "$RUNTIME_CFG" --mode t2v --prompt "$PROMPT" \ + --output_path "$out" --additional_config "$yaml_path" \ + --motioncache_metric_stats_path "$metric" 2>&1 | tee "$log" ) + local rc=${PIPESTATUS[0]} + set -e + t1=$(date +%s); elapsed=$((t1 - t0)) + [ -f "$out" ] && [ "$rc" -eq 0 ] || { echo "FAILED $run_id rc=$rc"; return 1; } + eval_out=$(python3 "$FLOWCACHE_ROOT/tools/eval_run.py" --baseline "$BASELINE" --generated "$out" --log "$log" --metric "$metric" 2>/dev/null || true) + PSNR=NA; SSIM=NA; BLACK=NA; REUSE=NA; PEAK=NA + while IFS='=' read -r k v; do + case "$k" in PSNR) PSNR="$v" ;; SSIM) SSIM="$v" ;; BLACK) BLACK="$v" ;; REUSE) REUSE="$v" ;; PEAK) PEAK="$v" ;; esac + done <<< "$eval_out" + echo "$run_id,$version,$TAU,$ALPHA,$DETAIL_ALPHA,$DETAIL_WINDOW,$COMBINE,$DETAIL_LAM,$PSNR,$SSIM,$BLACK,$REUSE,$elapsed,$PEAK,$out,$log" >> "$RESULTS_CSV" + echo " PSNR=${PSNR}dB reuse=${REUSE}% time=${elapsed}s" +} + +# preserve dev3 rows +python3 - "$RESULTS_CSV" "$DEV3_CSV" <<'PY' +import csv, sys, shutil +src, dst = sys.argv[1:3] +rows = list(csv.DictReader(open(src))) +dev3 = [r for r in rows if r["version"].startswith("dev3")] +if dev3: + with open(dst, "w", newline="") as f: + w = csv.DictWriter(f, fieldnames=dev3[0].keys()) + w.writeheader(); w.writerows(dev3) +PY + +cp "$DEV3_CSV" "$RESULTS_CSV" + +RUNTIME_CFG="$SWEEP_ROOT/runtime_${SWEEP_FRAMES}f.json" +make_runtime_config "$RUNTIME_CFG" "$SWEEP_FRAMES" +echo "dev4 sweep tau=$BEST_DEV3_TAU frames=$SWEEP_FRAMES -> $SWEEP_ROOT" + +for spec in \ + "max|3|0.5|0.5" "max|5|0.5|0.5" "max|3|0.4|0.5" "max|3|0.6|0.5" \ + "blend|3|0.5|0.3" "blend|3|0.5|0.5" "blend|3|0.5|0.7" \ + "product|3|0.5|0.5" "product|5|0.5|0.5"; do + IFS='|' read -r mode win da lam <<< "$spec" + rid="tau${BEST_DEV3_TAU}_${mode}_w${win}_da${da}_lam${lam}" + y="$SWEEP_ROOT/dev4_${rid}.yaml" + write_yaml "$y" "rel_l1_thresh=$BEST_DEV3_TAU" "detail_alpha=$da" \ + "detail_window_size=$win" "weight_combine_mode=$mode" "detail_lambda=$lam" + export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$win" COMBINE="$mode" DETAIL_LAM="$lam" + run_one "dev4" "$rid" "$y" "$DETAIL_ROOT" || true +done + +RUNTIME_CFG="$SWEEP_ROOT/runtime_240f.json" +make_runtime_config "$RUNTIME_CFG" 240 + +read -r y4 da dw cm dl BEST_DEV4_ID <<< "$(python3 - "$RESULTS_CSV" "$SWEEP_ROOT" "$BEST_DEV3_TAU" <<'PY' +import csv, sys, yaml, os +csv_path, sweep_root, tau = sys.argv[1:4] +rows = [r for r in csv.DictReader(open(csv_path)) if r["version"] == "dev4" and r["psnr_db"] not in ("NA", "")] +def score(r): + psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0 + return psnr + 0.02 * float(r["reuse_rate_pct"] or 0) +row = max(rows, key=score) +y = { + "rel_l1_thresh": float(tau), "warmup_steps": 5, "phase1_steps": 9, "alpha": 0.5, + "detail_alpha": float(row["detail_alpha"]), + "detail_window_size": int(float(row["detail_window"])), + "weight_combine_mode": row["combine_mode"], + "detail_lambda": float(row["detail_lambda"]), + "discard_nearly_clean_chunk": True, "compress_kv_cache": True, + "total_cache_chunk_nums": 5, "compress_strategy": "token", "mix_lambda": 0.07, + "query_granularity": "frame", "score_weighting_method": "no_weight", + "power": 3, "log": False, "print_peak_memory": True, +} +path = os.path.join(sweep_root, f"dev4_{row['variant']}_full.yaml") +with open(path, "w") as f: yaml.dump(y, f, default_flow_style=False) +print(path, row["detail_alpha"], row["detail_window"], row["combine_mode"], row["detail_lambda"], row["variant"]) +PY +)" +export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$dw" COMBINE="$cm" DETAIL_LAM="$dl" +run_one "dev4_full" "${BEST_DEV4_ID}_240f" "$y4" "$DETAIL_ROOT" || true + +python3 "$FLOWCACHE_ROOT/tools/generate_comparison_report.py" \ + --results "$RESULTS_CSV" --baseline "$BASELINE" \ + --output "$REPORT_DIR/comparison_report.md" --sweep_dir "$SWEEP_ROOT" + +# write optimal configs +python3 - "$RESULTS_CSV" "$FLOWCACHE_ROOT" "$DETAIL_ROOT" <<'PY' +import csv, sys, yaml, os +csv_path, dev3_root, dev4_root = sys.argv[1:4] +rows = list(csv.DictReader(open(csv_path))) +def score(r): + psnr = float(r["psnr_db"]) if r["psnr_db"] not in ("NA", "inf", "") else -999 + if r["psnr_db"] == "inf": psnr = 100 + return psnr + 0.02 * float(r["reuse_rate_pct"] or 0) +dev3 = [r for r in rows if r["version"] == "dev3"] +dev4 = [r for r in rows if r["version"] == "dev4"] +full3 = [r for r in rows if r["version"] == "dev3_full"] +full4 = [r for r in rows if r["version"] == "dev4_full"] +if dev3: + b3 = max(dev3, key=score) + y3 = {"rel_l1_thresh": float(b3["tau"]), "alpha": 0.5, "warmup_steps": 5, "phase1_steps": 9, + "discard_nearly_clean_chunk": True, "compress_kv_cache": True, "total_cache_chunk_nums": 5, + "log": True, "print_peak_memory": True} + with open(os.path.join(dev3_root, "yaml_config/single_run/motioncache_config_best.yaml"), "w") as f: + yaml.dump(y3, f, default_flow_style=False) +if dev4: + b4 = max(dev4, key=score) + y4 = {"rel_l1_thresh": float(b4["tau"]), "alpha": 0.5, "warmup_steps": 5, "phase1_steps": 9, + "detail_alpha": float(b4["detail_alpha"]), "detail_window_size": int(float(b4["detail_window"])), + "weight_combine_mode": b4["combine_mode"], "detail_lambda": float(b4["detail_lambda"]), + "discard_nearly_clean_chunk": True, "compress_kv_cache": True, "total_cache_chunk_nums": 5, + "log": True, "print_peak_memory": True} + with open(os.path.join(dev4_root, "yaml_config/single_run/motiondetail_config_best.yaml"), "w") as f: + yaml.dump(y4, f, default_flow_style=False) +print("Wrote best config yaml files") +PY + +echo "Done. Report: $REPORT_DIR/comparison_report.md" diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_hparam_sweep.sh b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_hparam_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..70cbe0fec507b66b0369f13766dd8902e2954230 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/run_hparam_sweep.sh @@ -0,0 +1,276 @@ +#!/usr/bin/env bash +# Hyperparameter sweep for dev3 (MotionCache) and dev4 (MotionDetailCache). +set -euo pipefail + +GPU_ID="${CUDA_VISIBLE_DEVICES:-1}" +SWEEP_FRAMES="${SWEEP_FRAMES:-120}" +PROMPT="${PROMPT:-a woman dancing.}" +BASELINE="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/a_woman_dancing_2026-05-19_09-49-14/output_2026-05-19_09-49-14.mp4" +FLOWCACHE_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion" +DETAIL_ROOT="/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev4-detail" +SWEEP_ROOT="${SWEEP_ROOT:-$FLOWCACHE_ROOT/outputs/hparam_sweep_$(date +%Y%m%d_%H%M%S)}" +REPORT_DIR="$SWEEP_ROOT/report" +mkdir -p "$REPORT_DIR" + +export MASTER_ADDR=localhost +export CUDA_VISIBLE_DEVICES="$GPU_ID" +export PYTHONPATH="${FLOWCACHE_ROOT}:${DETAIL_ROOT}:${PYTHONPATH:-}" +export PAD_HQ=1 +export PAD_DURATION=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OFFLOAD_T5_CACHE=true +export OFFLOAD_VAE_CACHE=true + +if [ -z "${CONDA_DEFAULT_ENV:-}" ] || [ "${CONDA_DEFAULT_ENV}" != "magi" ]; then + # shellcheck disable=SC1091 + source "${HOME}/miniforge3/etc/profile.d/conda.sh" 2>/dev/null || source "${HOME}/anaconda3/etc/profile.d/conda.sh" + conda activate magi +fi + +ensure_numpy_compat() { + if ! python3 - <<'PY' +import numpy as np +major = int(np.__version__.split(".")[0]) +raise SystemExit(0 if major < 2 else 1) +PY + then + echo "Fixing numpy for transformers (found incompatible version)..." + pip install -q "numpy>=1.24,<2.0" + fi +} +ensure_numpy_compat + +make_runtime_config() { + local dst="$1" frames="$2" + python3 - "$dst" "$frames" <<'PY' +import json, sys +dst, frames = sys.argv[1], int(sys.argv[2]) +src = "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1-dev3-motion/config/single_run/flowcache_t2v.json" +with open(src) as f: + cfg = json.load(f) +cfg["runtime_config"]["num_frames"] = frames +with open(dst, "w") as f: + json.dump(cfg, f, indent=4) +PY +} + +RUNTIME_CFG="$SWEEP_ROOT/runtime_${SWEEP_FRAMES}f.json" +make_runtime_config "$RUNTIME_CFG" "$SWEEP_FRAMES" +echo "Sweep output: $SWEEP_ROOT (num_frames=$SWEEP_FRAMES, GPU=$GPU_ID, host=$(hostname))" + +RESULTS_CSV="$REPORT_DIR/results.csv" +echo "variant,version,tau,alpha,detail_alpha,detail_window,combine_mode,detail_lambda,psnr_db,ssim,black_ratio,reuse_rate_pct,wall_sec,peak_gb,video_path,log_path" > "$RESULTS_CSV" + +run_one() { + local version="$1" run_id="$2" yaml_path="$3" root_dir="$4" + local exp_dir="$SWEEP_ROOT/${version}_${run_id}" + mkdir -p "$exp_dir" + local out="$exp_dir/output.mp4" + local log="$exp_dir/infer.log" + local metric="$exp_dir/metrics.json" + local t0 t1 elapsed + + export MASTER_PORT=$((6000 + RANDOM % 500)) + if [ "$root_dir" = "$DETAIL_ROOT" ]; then + export PYTHONPATH="${DETAIL_ROOT}:${FLOWCACHE_ROOT}:${PYTHONPATH:-}" + else + export PYTHONPATH="${FLOWCACHE_ROOT}:${DETAIL_ROOT}:${PYTHONPATH:-}" + fi + + echo "" + echo "========== [$version] $run_id ==========" + t0=$(date +%s) + set +e + ( + cd "$root_dir" + python3 inference/pipeline/motioncache.py \ + --config_file "$RUNTIME_CFG" \ + --mode t2v \ + --prompt "$PROMPT" \ + --output_path "$out" \ + --additional_config "$yaml_path" \ + --motioncache_metric_stats_path "$metric" \ + 2>&1 | tee "$log" + ) + local rc=${PIPESTATUS[0]} + set -e + t1=$(date +%s) + elapsed=$((t1 - t0)) + + if [ ! -f "$out" ] || [ "$rc" -ne 0 ]; then + echo "FAILED: $run_id (rc=$rc, no video)" + return 1 + fi + + eval_out=$(python3 "$FLOWCACHE_ROOT/tools/eval_run.py" \ + --baseline "$BASELINE" \ + --generated "$out" \ + --log "$log" \ + --metric "$metric" 2>/dev/null || true) + PSNR="NA"; SSIM="NA"; BLACK="NA"; REUSE="NA"; PEAK="NA" + while IFS='=' read -r k v; do + case "$k" in PSNR) PSNR="$v" ;; SSIM) SSIM="$v" ;; BLACK) BLACK="$v" ;; REUSE) REUSE="$v" ;; PEAK) PEAK="$v" ;; esac + done <<< "$eval_out" + echo "$run_id,$version,$TAU,$ALPHA,$DETAIL_ALPHA,$DETAIL_WINDOW,$COMBINE,$DETAIL_LAM,$PSNR,$SSIM,$BLACK,$REUSE,$elapsed,$PEAK,$out,$log" >> "$RESULTS_CSV" + echo " PSNR=${PSNR}dB reuse=${REUSE}% time=${elapsed}s" +} + +write_yaml() { + local path="$1" + shift + python3 - "$path" "$@" <<'PY' +import sys, yaml +path = sys.argv[1] +params = {} +for kv in sys.argv[2:]: + k, v = kv.split("=", 1) + if v.lower() in ("true", "false"): + params[k] = v.lower() == "true" + elif v.replace(".", "", 1).isdigit(): + params[k] = float(v) if "." in v else int(v) + else: + params[k] = v +base = { + "warmup_steps": 5, + "phase1_steps": 9, + "alpha": 0.5, + "discard_nearly_clean_chunk": True, + "compress_kv_cache": True, + "total_cache_chunk_nums": 5, + "compress_strategy": "token", + "mix_lambda": 0.07, + "query_granularity": "frame", + "score_weighting_method": "no_weight", + "power": 3, + "log": False, + "print_peak_memory": True, +} +base.update(params) +with open(path, "w") as f: + yaml.dump(base, f, default_flow_style=False) +PY +} + +# ---------- Phase 1: dev3 tau sweep ---------- +BEST_DEV3_TAU="0.015" + +for tau in 0.010 0.012 0.015 0.018 0.020 0.025 0.030; do + y="$SWEEP_ROOT/dev3_tau${tau}.yaml" + write_yaml "$y" "rel_l1_thresh=$tau" + export TAU="$tau" ALPHA="0.5" DETAIL_ALPHA="" DETAIL_WINDOW="" COMBINE="" DETAIL_LAM="" + run_one "dev3" "tau${tau}" "$y" "$FLOWCACHE_ROOT" || true +done + +BEST_DEV3_TAU=$(python3 - "$RESULTS_CSV" <<'PY' +import csv, sys +rows = [r for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")] +if not rows: + print("0.015") +else: + def score(r): + psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0 + reuse = float(r["reuse_rate_pct"] or 0) + return psnr + 0.02 * reuse + print(max(rows, key=score)["tau"]) +PY +) +echo "Best dev3 tau from sweep: $BEST_DEV3_TAU" + +# ---------- Phase 2: dev4 detail sweep ---------- +for spec in \ + "max|3|0.5|0.5" \ + "max|5|0.5|0.5" \ + "max|3|0.4|0.5" \ + "max|3|0.6|0.5" \ + "blend|3|0.5|0.3" \ + "blend|3|0.5|0.5" \ + "blend|3|0.5|0.7" \ + "product|3|0.5|0.5" \ + "product|5|0.5|0.5"; do + IFS='|' read -r mode win da lam <<< "$spec" + rid="tau${BEST_DEV3_TAU}_${mode}_w${win}_da${da}_lam${lam}" + y="$SWEEP_ROOT/dev4_${rid}.yaml" + write_yaml "$y" \ + "rel_l1_thresh=$BEST_DEV3_TAU" \ + "detail_alpha=$da" \ + "detail_window_size=$win" \ + "weight_combine_mode=$mode" \ + "detail_lambda=$lam" + export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$win" COMBINE="$mode" DETAIL_LAM="$lam" + run_one "dev4" "$rid" "$y" "$DETAIL_ROOT" || true +done + +# ---------- Phase 3: 240-frame validation ---------- +RUNTIME_CFG="$SWEEP_ROOT/runtime_240f.json" +make_runtime_config "$RUNTIME_CFG" 240 +echo "Full validation at 240 frames..." + +DEV3_COUNT=$(python3 - "$RESULTS_CSV" <<'PY' +import csv, sys +print(sum(1 for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", ""))) +PY +) +DEV4_COUNT=$(python3 - "$RESULTS_CSV" <<'PY' +import csv, sys +print(sum(1 for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev4" and r["psnr_db"] not in ("NA", ""))) +PY +) + +if [ "$DEV3_COUNT" -gt 0 ]; then + BEST_DEV3_ID=$(python3 - "$RESULTS_CSV" <<'PY' +import csv, sys +rows = [r for r in csv.DictReader(open(sys.argv[1])) if r["version"] == "dev3" and r["psnr_db"] not in ("NA", "")] +def score(r): + psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0 + return psnr + 0.02 * float(r["reuse_rate_pct"] or 0) +print(max(rows, key=score)["variant"]) +PY +) + y3="$SWEEP_ROOT/dev3_${BEST_DEV3_ID}_full.yaml" + write_yaml "$y3" "rel_l1_thresh=${BEST_DEV3_TAU}" + export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="" DETAIL_WINDOW="" COMBINE="" DETAIL_LAM="" + run_one "dev3_full" "${BEST_DEV3_ID}_240f" "$y3" "$FLOWCACHE_ROOT" || true +fi + +if [ "$DEV4_COUNT" -gt 0 ]; then + read -r y4 da dw cm dl BEST_DEV4_ID <<< "$(python3 - "$RESULTS_CSV" "$SWEEP_ROOT" "$BEST_DEV3_TAU" <<'PY' +import csv, sys, yaml, os +csv_path, sweep_root, tau = sys.argv[1:4] +rows = [r for r in csv.DictReader(open(csv_path)) if r["version"] == "dev4" and r["psnr_db"] not in ("NA", "")] +def score(r): + psnr = float(r["psnr_db"]) if r["psnr_db"] != "inf" else 100.0 + return psnr + 0.02 * float(r["reuse_rate_pct"] or 0) +row = max(rows, key=score) +y = { + "rel_l1_thresh": float(tau), + "warmup_steps": 5, "phase1_steps": 9, "alpha": 0.5, + "detail_alpha": float(row["detail_alpha"]), + "detail_window_size": int(float(row["detail_window"])), + "weight_combine_mode": row["combine_mode"], + "detail_lambda": float(row["detail_lambda"]), + "discard_nearly_clean_chunk": True, + "compress_kv_cache": True, "total_cache_chunk_nums": 5, + "compress_strategy": "token", "mix_lambda": 0.07, + "query_granularity": "frame", "score_weighting_method": "no_weight", + "power": 3, "log": False, "print_peak_memory": True, +} +path = os.path.join(sweep_root, f"dev4_{row['variant']}_full.yaml") +with open(path, "w") as f: + yaml.dump(y, f, default_flow_style=False) +print(path, row["detail_alpha"], row["detail_window"], row["combine_mode"], row["detail_lambda"], row["variant"]) +PY +)" + export TAU="$BEST_DEV3_TAU" ALPHA="0.5" DETAIL_ALPHA="$da" DETAIL_WINDOW="$dw" COMBINE="$cm" DETAIL_LAM="$dl" + run_one "dev4_full" "${BEST_DEV4_ID}_240f" "$y4" "$DETAIL_ROOT" || true +fi + +python3 "$FLOWCACHE_ROOT/tools/generate_comparison_report.py" \ + --results "$RESULTS_CSV" \ + --baseline "$BASELINE" \ + --output "$REPORT_DIR/comparison_report.md" \ + --sweep_dir "$SWEEP_ROOT" + +echo "" +echo "Sweep complete." +echo " CSV: $RESULTS_CSV" +echo " Report: $REPORT_DIR/comparison_report.md" diff --git a/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/video_metrics.py b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/video_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..3873573d52ac923c98523b5ebff648f00c9287c6 --- /dev/null +++ b/FlowCache/FlowCache4MAGI-1-dev3-motion/tools/video_metrics.py @@ -0,0 +1,108 @@ +import os +import cv2 +import argparse +import torch +import lpips +import numpy as np +from tqdm import tqdm +from torchmetrics.image import StructuralSimilarityIndexMeasure + +def load_video_frames(path, resize_to=None): + """ + Load all frames from a video file as a list of HxWx3 uint8 arrays. + Optionally resize each frame to `resize_to` (w, h). + """ + + cap = cv2.VideoCapture(path) + frames = [] + while True: + ret, img = cap.read() + if not ret: + break + if resize_to is not None: + img = cv2.resize(img, resize_to) + frames.append(np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), axis=0)) + cap.release() + return np.concatenate(frames) + + +def compute_video_metrics(frames_gt, frames_gen, + device, ssim_metric, lpips_fn): + """ + Compute PSNR, SSIM, LPIPS for two lists of frames (uint8 BGR). + All computations on `device`. + Returns (psnr, ssim, lpips) scalars. + """ + # ensure same frame count + # convert to tensors [N,3,H,W], normalize to [0,1] + gt_t = torch.from_numpy(frames_gt).float().to(device).permute(0, 3, 1, 2).div_(255).contiguous() + + gen_t = torch.from_numpy(frames_gen).float().to(device).permute(0, 3, 1, 2).div_(255).contiguous() + + # PSNR (data_range=1.0): -10 * log10(mse) + mse = torch.mean((gt_t - gen_t) ** 2) + psnr = -10.0 * torch.log10(mse) + + # SSIM: returns average over batch + ssim_val = ssim_metric(gen_t, gt_t) + + # LPIPS: expects [-1,1] + with torch.no_grad(): + lpips_val = lpips_fn(gt_t * 2.0 - 1.0, gen_t * 2.0 - 1.0).mean() + + return psnr.item(), ssim_val.item(), lpips_val.item() + + +def main(): + parser = argparse.ArgumentParser( + description="Compute PSNR/SSIM/LPIPS on GPU for two folders of .mp4 videos" + ) + parser.add_argument("--original_video", required=True, + help="ground-truth .mp4 videos") + parser.add_argument("--generated_video", required=True, + help="generated .mp4 videos") + parser.add_argument("--device", default="cuda", + help="Torch device, e.g. 'cuda' or 'cpu'") + parser.add_argument("--lpips_net", default="alex", choices=["alex", "vgg"], + help="Backbone for LPIPS") + args = parser.parse_args() + + device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") + # instantiate metrics on device + ssim_metric = StructuralSimilarityIndexMeasure(data_range=1.0).to(device) + lpips_fn = lpips.LPIPS(net=args.lpips_net, spatial=True).to(device) + + # gather .mp4 filenames + gt_files = args.original_video + gen_set = args.generated_video + + psnrs, ssims, lpips_vals = [], [], [] + for fname in tqdm([gt_files], desc="Videos"): + path_gt = gt_files + path_gen = gen_set + + # load frames; resize generated to match GT dimensions + frames_gt = load_video_frames(path_gt) + frames_gen = load_video_frames(path_gen) + + res = compute_video_metrics(frames_gt, frames_gen, + device, ssim_metric, lpips_fn) + if res is None: + continue + p, s, l = res + psnrs.append(p) + ssims.append(s) + lpips_vals.append(l) + + if not psnrs: + print("No valid videos processed.") + return + + print("\n=== Overall Averages ===") + print(f"Average PSNR : {np.mean(psnrs):.2f} dB") + print(f"Average SSIM : {np.mean(ssims):.4f}") + print(f"Average LPIPS: {np.mean(lpips_vals):.4f}") + + +if __name__ == "__main__": + main() \ No newline at end of file