hpcaitech/Open-Sora · error · ValueError

A dict of processors was passed, but the number of processor

Error message

A dict of processors was passed, but the number of processors {len(processor)} does not match the number of attention layers: {count}. Please make sure to pass {count} processor classes.

What it means

set_attn_processor on the Hunyuan causal 3D autoencoder requires that when you pass a dict of processors, its length exactly equals the number of attention layers found by recursively walking the model (len(self.attn_processors)). The guard ensures a 1:1 mapping between layer names and processors.

Source

Thrown at opensora/models/hunyuan_vae/autoencoder_kl_causal_3d.py:235

    def set_attn_processor(
        self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
    ):
        r"""
        Sets the attention processor to use to compute attention.

        Parameters:
            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
                The instantiated processor class or a dictionary of processor classes that will be set as the processor
                for **all** `Attention` layers.

                If `processor` is a dict, the key needs to define the path to the corresponding cross attention
                processor. This is strongly recommended when setting trainable attention processors.

        """
        count = len(self.attn_processors.keys())

        if isinstance(processor, dict) and len(processor) != count:
            raise ValueError(
                f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
                f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
            )

        def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
            if hasattr(module, "set_processor"):
                if not isinstance(processor, dict):
                    module.set_processor(processor, _remove_lora=_remove_lora)
                else:
                    module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)

            for sub_name, child in module.named_children():
                fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)

        for name, module in self.named_children():
            fn_recursive_attn_processor(name, module, processor)

    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor

View on GitHub (pinned to 7ad6a96a13)

Solutions

  1. Get the exact expected keys and count via model.attn_processors and build your dict with the same keys
  2. If you meant to apply one processor to all layers, pass a single processor instance instead of a dict
  3. If loading from a checkpoint, verify the checkpoint matches this model architecture (layer count)

Example fix

# before
model.set_attn_processor({name: AttnProcessor() for name in ["some", "names"]})
# after
model.set_attn_processor({name: AttnProcessor() for name in model.attn_processors})
Defensive patterns

Strategy: validation

Validate before calling

procs = model.attn_processors
assert len(processor_dict) == len(procs), f"{len(processor_dict)} vs {len(procs)}"
assert set(processor_dict) == set(procs), "processor keys must match layer names"

Type guard

def is_valid_processor_dict(model, d) -> bool:
    return isinstance(d, dict) and set(d) == set(model.attn_processors)

Try / catch

try:
    model.set_attn_processor(proc_dict)
except ValueError as e:
    if "number of processors" in str(e):
        model.set_attn_processor(AttnProcessor())  # uniform fallback
    else:
        raise

Prevention

When it happens

Trigger: Calling model.set_attn_processor({...}) where the dict has fewer/more entries than attention layers, e.g. reusing a processor state dict from a different model variant or constructing a partial dict for only some layers.

Common situations: Porting attention processors or LoRA weights between model checkpoints with different layer counts; hand-building a processor dict and losing count; diffusers-version code copied over where counts differed.

Related errors


AI-assisted analysis of hpcaitech/Open-Sora@7ad6a96a13 (2026-08-28). Data as JSON: /api/errors/99c06031b73d7e69. Report an issue: GitHub.