Repository navigation
[Modular] Add PAN 2 - #15202
[Modular] Add PAN 2#15202
Conversation
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).
… CFG 2.5 and shift 9.0
|
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: |
|
/diffusers-bot pytest tests/models/transformers/test_models_transformer_pan2.py tests/modular_pipelines/pan2/test_modular_pipeline_pan2.py |
|
✅ |
| 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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
| # 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: |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Went with #14469 instead, following Kandinsky S2V, in 720d5ff:
- standalone (no guider): encodes
negative_promptonly if passed - guider on: encodes it, or the default one
- guider off: skips it, and warns if
negative_promptwas 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?
| 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() |
There was a problem hiding this comment.
| 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
There was a problem hiding this comment.
We want to make safety checker opt-out (enabled by default) per our legal opinion.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
I make it a component in 9b71fb7, with two concerns listed below. This also removes the to override as well.
- 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.
- this requires a change for
modular_model_index.jsonandsafety_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: |
There was a problem hiding this comment.
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
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 bf16PAN2ModularPipeline/PAN2Blockswith 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 VAEulysses_anything/ring_anything) and FirstBlockCache / MagCache / TaylorSeer support--save_pipeline), docs pages, and model and pipeline tests onhf-internal-testing/tiny-pan2-modular-pipeCheckpoint: 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:
output_type="latent"shortcut in the decoder; to get latents, pop thedecodeblock.image_latents(as in Anima), and raises an error if the height and width passed don't match.guideras a component ([modular]guidershould be an optional component for text encoder blocks #14469).--save_pipelineflag 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.latentsare checked against the expected shape.hf-internal-testing/.test_save_from_pretrainedoverride.set_attention_backend("flash_hub").(None,)in_get_fused_projections: copied from Flux, so it stays in sync throughmake fix-copies.Before submitting
self-reviewskill on the diff?documentation guidelines, and
here are tips on formatting docstrings.
Who can review?
@yiyixuxu @sayakpaul
Self-review
Ran the
self-reviewskill (the@claudeCI rubric,.ai/references/review-rules.mdfrommain) over the whole diff againstmain:src/,tests/, docs andscripts/(25 files, +2989).Verdict: READY.
Blocking
None. The one finding of the first round,
expected_workflow_defaultsnot being set (references/testing.md), is fixed: thet2vandi2vcontracts are now pinned intests/modular_pipelines/pan2/test_modular_pipeline_pan2.py, including the guider'sguidance_scale=2.5.Non-blocking
None.
Dead code (advisory)
path:linetransformer_pan2.py:84,:184attention_maskdispatch_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:152PAN2Attention(processor=...)transformer_pan2.py:55(None,)# Copied fromFlux's_get_fused_projections, kept in sync bymake fix-copies.encoders.pyfpsinputmodular_pipeline.py:23stubPAN2SafetyCheckerpan2_guardrailis 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_onlyflags one file outside this PR; it fails the same way onmain.Tests:
tests/hooksand the components-manager tests give 154 passed, 15 skipped, 1 failed. The failure istest_inference_is_not_nan_cpu, which fails here because the local environment has thecausal_conv1dCUDA kernel installed; it passes in the CPU-only run above.Summary
Nothing to fix before submitting.