Skip to content

[Modular] Add PAN 2 - #15202

Merged
sayakpaul merged 27 commits into
huggingface:mainfrom
ifm-ai:pan2
Nov 10, 2026
Merged

sayakpaul merged 27 commits into
huggingface:mainfrom
ifm-ai:pan2

Conversation

@wu-qing-157

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds PAN 2 to Modular Diffusers. PAN 2 is a foundation world model that simulates how a scene evolves under a time-grounded plan of actions and camera movements; its 29B generative simulator, a dual-stream multimodal diffusion transformer, is what this PR integrates.

  • PAN2Transformer3DModel: separate video and text streams joined in attention; the timestep embedder and modulation run in float32, the rest in bf16
  • PAN2ModularPipeline / PAN2Blocks with two workflows, text-to-video (t2v) and image-to-video from a first frame (i2v), using a Qwen3.5 text encoder and the Wan2.2 VAE
  • a safety checker on the prompt and the generated video (pan2-guardrail), on by default
  • context parallelism (ulysses_anything / ring_anything) and FirstBlockCache / MagCache / TaylorSeer support
  • a checkpoint conversion script (--save_pipeline), docs pages, and model and pipeline tests on hf-internal-testing/tiny-pan2-modular-pipe

Checkpoint: IFM/PAN2

Previous review

This PR was reviewed in the collaboration repo: https://github.com/huggingface/diffusers-new-model-addition-ifm/pull/3 (approved by @sayakpaul and ZJUJeffLai, with modular feedback from @yiyixuxu). What changed there:

  • Modular patterns (yiyixuxu)
  • Conversion script (ZJUJeffLai, sayakpaul): a --save_pipeline flag with default text encoder and VAE repos, as in the LTX-2 / Cosmos / HunyuanVideo converters, instead of checking that the two paths are given together.
  • Latents check (ZJUJeffLai): user-provided latents are checked against the expected shape.
  • Tests (sayakpaul)
    • Safety checker tests cut to a minimum: only that it's on by default.
    • The tiny checkpoint moved to hf-internal-testing/.
    • Dropped the test_save_from_pretrained override.
  • Docs (sayakpaul, ZJUJeffLai)
    • The example uses set_attention_backend("flash_hub").
    • The guardrail section is rewritten.
    • The reasoning backbone that writes the prompts is linked.
  • Kept as is, after discussion (ZJUJeffLai's suggestions)
    • (None,) in _get_fused_projections: copied from Flux, so it stays in sync through make fix-copies.
    • The rope grid loop: written as a loop, as in Wan, HunyuanVideo and the others.
    • No patch-size divisibility check in the transformer: the prepare-latents step already checks the input sizes.
    • The latent mean and std are not cached, as in the other pipelines (sayakpaul agreed).
  • From our own evaluation, after approval
    • Default CFG is 2.5, and the given first frame of image-to-video gets no guidance.
    • Default shift is 9.0.
    • The timestep embedder and modulation run in float32.
    • The default negative prompt is the released one, with its time ranges set to the clip length.
  • Samples generated with the PR code are in the thread (comment).

Before submitting

Who can review?

@yiyixuxu @sayakpaul

Self-review

Ran the self-review skill (the @claude CI rubric, .ai/references/review-rules.md from main) over the whole diff against main: src/, tests/, docs and scripts/ (25 files, +2989).

Verdict: READY.

Blocking

None. The one finding of the first round, expected_workflow_defaults not being set (references/testing.md), is fixed: the t2v and i2v contracts are now pinned in tests/modular_pipelines/pan2/test_modular_pipeline_pan2.py, including the guider's guidance_scale=2.5.

Non-blocking

None.

Dead code (advisory)

path:line Status Reason
transformer_pan2.py:84, :184 attention_mask Kept No mask is passed, since every prompt is unpadded. The parameter is forwarded to dispatch_attention_fn, not ignored, and keeps the processor signature shared with Wan and MiniMax-H3, so a custom processor can use it.
transformer_pan2.py:152 PAN2Attention(processor=...) Kept Same as the attention classes of Flux, Flux2, Wan, Cosmos3, MiniMax-H3 and LTX-2.
transformer_pan2.py:55 (None,) Used # Copied from Flux's _get_fused_projections, kept in sync by make fix-copies.
encoders.py fps input Used Sets the time ranges of the default negative prompt.
modular_pipeline.py:23 stub PAN2SafetyChecker Used Raises the install hint when pan2_guardrail is missing.

Checks

ruff check / ruff format --check, check_copies, check_dummies, check_doc_toc, check_forward_call_docstrings, and the modular auto docstrings all pass. doc-builder style --check_only flags one file outside this PR; it fails the same way on main.

Tests:

  • CPU: the PAN 2 pipeline and transformer tests give 52 passed, 45 skipped (accelerator only).
  • GPU: the PAN 2 tests, tests/hooks and the components-manager tests give 154 passed, 15 skipped, 1 failed. The failure is test_inference_is_not_nan_cpu, which fails here because the local environment has the causal_conv1d CUDA kernel installed; it passes in the CPU-only run above.

Summary

Nothing to fix before submitting.

wu-qing-157 and others added 20 commits October 8, 2026 01:39
PAN2 transformer (29B MoT, video and text streams) and a modular pipeline with
t2v and i2v workflows, using a Qwen3.5 text encoder and the Wan2.2 VAE:
- standard CFG, 50 steps by default
- context parallelism (Ulysses)
- optional safety checker on the prompt and the generated video (pan2-guardrail), following Cosmos
- checkpoint conversion script, docs, model and pipeline tests on a tiny checkpoint
- return annotations on all blocks and the rotary embedding
- "video" wording in block inputs and the auto docstrings
- reset stateful cache hooks after each call, as Cosmos3 does
- move context_type_embedding to the text device (device_map="auto")
- test that latent output skips decoding and the video check
- document the custom safety checker contract; dtype= in the conversion script

Signed-off-by: Yi Gu <Yi.Gu@mbzuai.ac.ae>
- Keep only the default-on safety-checker test and drop the dummy checker, since the PAN2 guardrail package tests the checker itself (test_modular_pipeline_pan2.py).
- Raise a ValueError when user-provided latents do not have the expected shape (PAN2PrepareLatentsStep).
- Write the full pipeline in the conversion script only with --save_pipeline, with --text_encoder_path and --vae_path defaulting to Qwen/Qwen3.5-9B and Wan-AI/Wan2.2-TI2V-5B-Diffusers, so the text encoder and VAE can no longer be given partially.
Co-authored-by: YiYi Xu <yixu310@gmail.com>
The decoder step no longer returns the latents for output_type="latent"; to get them, pop the decode block (blocks.sub_blocks.pop("decode")).
Add PAN2Image2VideoInputStep to the image-to-video denoise blocks, after the text input step. As Anima's image input step does, it takes `height` and `width` from the shape of `image_latents`, and raises a ValueError when they are passed and do not match it. The VAE encoder and prepare-latents steps no longer declare 704 x 1248 as input defaults and fall back to the pipeline's `default_height` / `default_width` (from `default_sample_height` / `default_sample_width`) at run time, as in Wan, so that these defaults do not override the size of `image_latents`. Test the image-to-video workflow from standalone-encoded `image_latents`.
The guider belongs to the denoise step. In the full pipeline, it decides through `requires_unconditional_embeds` whether the negative prompt is encoded, with a warning when a `negative_prompt` is given but guidance does not use it. Standalone, the text encoder has no guider and still encodes the negative prompt, since the PAN2 denoise step uses classifier-free guidance by default.
Co-authored-by: Sayak Paul <spsayakpaul@gmail.com>
…thout their models

Describe PAN2 as a foundation world model (intro, pipeline and transformer docstrings, conversion script) instead of a video generation model. Describe the guardrails as checking the prompt and each generated video, without naming the guard models, and say that turning them off with `disable_safety_checker()` is at your own risk (docs, error messages and a new docstring).
@github-actions github-actions Bot added documentation Improvements or additions to documentation models tests modular-pipelines utils hooks size/L PR with diff > 200 LOC labels Nov 6, 2026
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@sayakpaul sayakpaul added this to the Release 0.43.0 milestone Nov 7, 2026
@sayakpaul

Copy link
Copy Markdown
Member

/diffusers-bot pytest tests/models/transformers/test_models_transformer_pan2.py tests/modular_pipelines/pan2/test_modular_pipeline_pan2.py

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ pytest tests/models/transformers/test_models_transformer_pan2.py tests/modular_pipelines/pan2/test_modular_pipeline_pan2.py passed on GPU — view logs.

Comment on lines +291 to +298
if components.requires_safety_checker:
components.load_safety_checker()
components.safety_checker.to(device)
try:
if not components.safety_checker.check_text_safety(block_state.prompt):
raise ValueError("The PAN 2 guardrail detected unsafe content in the prompt.")
finally:
components.safety_checker.to("cpu")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, can we find a way to not load it for every call? 👀

Also, this manual components.safety_checker.to("cpu") feels a bit hacky. We typically don't do it for other components.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in d164bc7; now the safety_check loads with load_components and reside on the same device as other components; no moving during the calls

@sayakpaul sayakpaul left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! My major comment is around how we're handling the safety checker. I don't like it that we're loading it during the calls.

… pipeline

The guardrail is loaded once by `load_components()` when the checks are on and the package is
installed, and `pipe.to()` moves it with the other components. The text encoder and decoder steps
no longer load it or move it between devices during a call; they only raise when the checks are on
and it is not loaded.
@sayakpaul
sayakpaul requested a review from yiyixuxu November 8, 2026 06:17
Comment thread docs/source/en/api/pipelines/pan2.md Resolved
# needed. Standalone, there is no guider and the negative prompt is encoded, since the PAN 2 denoise step uses
# classifier-free guidance by default.
block_state.negative_prompt_embeds = None
if getattr(components, "guider", None) is None or components.requires_unconditional_embeds:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh do you want to change the requires_uncondiontal_embeds property to default to True when guider is not present? it differs from other pipelines but it's consistent with the behavior here, i.e. it will use the default negative prompt and encode anyway

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went with #14469 instead, following Kandinsky S2V, in 720d5ff:

  • standalone (no guider): encodes negative_prompt only if passed
  • guider on: encodes it, or the default one
  • guider off: skips it, and warns if negative_prompt was passed

requires_unconditional_embeds stays False without a guider, like the other pipelines.

We previously encoded it anyway because a standalone text_encoder → denoise chain crashed: denoise defaults to CFG and got no negative embeddings. Following Kandinsky S2V and #14469, we now leave that chain crashing unless negative_prompt is passed.

Leaving this open. @yiyixuxu do you have different opinions here?

Comment on lines +102 to +106
def load_components(self, names: list[str] | str | None = None, workflow: str | None = None, **kwargs):
r"""Load the components, and the PAN 2 guardrail too when the checks are on and it is installed."""
super().load_components(names=names, workflow=workflow, **kwargs)
if self.requires_safety_checker and is_pan2_guardrail_available():
self.enable_safety_checker()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def load_components(self, names: list[str] | str | None = None, workflow: str | None = None, **kwargs):
r"""Load the components, and the PAN 2 guardrail too when the checks are on and it is installed."""
super().load_components(names=names, workflow=workflow, **kwargs)
if self.requires_safety_checker and is_pan2_guardrail_available():
self.enable_safety_checker()

can we just call pipe.enable_safety_checker() explicitly in docs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to make safety checker opt-out (enabled by default) per our legal opinion.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the safety checkers are still on by default without this override: by default it's configured as self.config.enable_safety_checker=True so the user cannot run the model unless they explicitly turn it off with disable_safety_checker(). the only thing this override changes is that it's loaded implicitly instead of an explicit call to the checker outside of the pipeline

I think the best plan here is to make the safety checker a regular components that works with modular_model_index.json though

you can just declare ComponentSpec("safety_checker", PAN2SafetyChecker) in the blocks that needs it, and add it to modular_model_index.json. then load_components() will load it with everything else and we can remove the to override as well. It should work as long as it supports the from_pretrained API - but let me know if you run into any issues

@wu-qing-157 wu-qing-157 Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I make it a component in 9b71fb7, with two concerns listed below. This also removes the to override as well.

  1. We now have
    from pan2_guardrail import PAN2SafetyChecker as _PAN2SafetyChecker

    class PAN2SafetyChecker(_PAN2SafetyChecker):
        r"""The PAN 2 guardrail. Defined in diffusers so that a saved pipeline records it as a diffusers class."""

save_pretrained records the checker's class from where it's defined: pan2_guardrail.safety_checker.PAN2SafetyChecker with the package, diffusers.PAN2SafetyChecker (the stub) without it, which doesn't exist. Either way, reloading breaks in the other environment. Without the package, as in CI, test_save_from_pretrained and test_load_expected_components_from_save_pretrained fail.
Defining it in diffusers (a thin subclass, or the stub) and exporting it as diffusers.PAN2SafetyChecker makes every save record a class that resolves everywhere.

  1. this requires a change for modular_model_index.json and safety_checker/ in HF model repo, and a change in the guardrail repo; though it now works with 9b71fb7 here and our other repos, I need double check with my teammates on the change. I'll merge those changes after this change is agreed on

def to(self, *args, **kwargs):
r"""Move the pipeline, and the PAN 2 guardrail with it."""
pipeline = super().to(*args, **kwargs)
if getattr(pipeline, "safety_checker", None) is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to register safety checker as a regular components? so that we don't need a special to method here

if not, can we move the safety checker inside call to execution device? anyways let;s not create a custom to here

@yiyixuxu yiyixuxu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

@sayakpaul
sayakpaul merged commit a17ab72 into huggingface:main Nov 10, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation hooks models modular-pipelines size/L PR with diff > 200 LOC tests utils

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants