opensi·si

Monkey patching allows you to replace model components globally without modifying the original model code. Once registered, patches are automatically applied when loading any…

Monkey patching

Monkey patching allows you to replace model components globally without modifying the original model code. Once registered, patches are automatically applied when loading any model with PreTrainedModel.from_pretrained or PreTrainedModel.from_config. This enables you to restructure models for specific requirements like quantization compatibility, apply optimizations, or experiment with architectural variants.

Warning Monkey patching should be used as a last resort when you need to change the layout and structure of a module and or its weights. For many customization and optimization needs, try using the Attention interface, Experts interface, or Kernels registry instead. Only use monkey patching when you need structural changes that can't be achieved through custom forward implementations alone (e.g., for quantization library compatibility, fusing layers, or architectural experiments).

Quick start

Here's a simple example showing how to replace a model component:

from transformers import AutoModelForCausalLM
from transformers.models.llama.modeling_llama import LlamaAttention
from transformers.monkey_patching import register_patch_mapping

# Define your replacement class (must inherit from nn.Module)
class CustomLlamaAttention(LlamaAttention):
    def forward(self, *args, **kwargs):
        # Your custom implementation
        print("Using custom attention!")
        return super().forward(*args, **kwargs)

# Register the patch globally (only applies to transformers modeling modules)
register_patch_mapping(mapping={"LlamaAttention": CustomLlamaAttention})

# Load a model - the patch is automatically applied during initialization
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")

# All LlamaAttention layers in the model are now CustomLlamaAttention instances
print(type(model.model.layers[0].self_attn))  # <class '__main__.CustomLlamaAttention'>

How it works

Monkey patches work through a two-step process:

  1. Registration: Call register_patch_mapping to add mappings to a global registry.

  2. Application: Patches are automatically applied during model initialization:

    • from_pretrained / from_config: Patches are automatically applied via an internal context manager. No additional action needed!
    • Manual construction (e.g., Model(config)): You must use the apply_patches context manager manually.

Once patches are registered, they persist and affect all subsequent model loads until you clear them with clear_patch_mapping.

Important limitations:

  • Only classes in transformers modeling modules are allowed to be patched (e.g., LlamaAttention, LlamaMLP).
  • The mapping keys can be either exact class names or regular expression patterns (see Pattern matching below).

Global registration

Use register_patch_mapping to register mappings globally:

from transformers.monkey_patching import register_patch_mapping

# Register a single patch
register_patch_mapping(
    mapping={"Qwen2MoeExperts": SequentialExperts}
)

# Register multiple patches at once
register_patch_mapping(
    mapping={
        "Qwen2MoeExperts": SequentialExperts,
        "Qwen2MoeAttention": CustomAttention,
    },
    # Overwrite existing patches if they exist
    overwrite=True,
)

Pattern matching

You can use regular expressions to match multiple classes with a single pattern:

from transformers.monkey_patching import register_patch_mapping

# Match all classes containing "Attention"
register_patch_mapping(
    mapping={".*Attention": CustomAttention}
)

# More examples
register_patch_mapping(
    mapping={
        ".*MoeExperts$": CustomExperts,           # Ends with "MoeExperts"
        "^Llama\\d+Attention$": CustomAttention,  # Llama2Attention, Llama3Attention, etc.
    }
)

Important: Exact matches take precedence over patterns. If you register both "LlamaAttention" and ".*Attention", classes named LlamaAttention will use the exact-match replacement, while other matching classes will use the pattern-match replacement.

Warning Regex patterns can silently break models. A broad pattern like ".*Attention" will match every class whose name contains "Attention" — including container classes that wrap the attention you actually want to replace. For example, BERT has three attention-related classes: BertSelfAttention and BertCrossAttention (the inner attention implementations) and BertAttention (an outer module that contains one of those inner classes). Patching all three with the same custom attention layer produces a broken model because the outer BertAttention no longer wraps the inner one — it is one, eliminating expected sub-modules like self and output. Prefer narrow patterns (e.g., ".*SelfAttention$") or exact class names to avoid unintended matches.

To unregister patches, use unregister_patch_mapping:

from transformers.monkey_patching import unregister_patch_mapping

# Unregister a single patch (use exact name or pattern from registration)
unregister_patch_mapping(keys=["Qwen2MoeExperts"])

# Unregister multiple patches at once
unregister_patch_mapping(keys=["Qwen2MoeExperts", "Qwen2MoeAttention"])

# Unregister a pattern
unregister_patch_mapping(keys=[".*Attention"])

To clear all registered patches, use clear_patch_mapping:

from transformers.monkey_patching import clear_patch_mapping

clear_patch_mapping()

To view currently registered patches, use get_patch_mapping:

from transformers.monkey_patching import get_patch_mapping

current_patches = get_patch_mapping()
print(current_patches)

Manual model construction

The apply_patches context manager is only needed when you're constructing models manually (e.g., Model(config)) without using from_pretrained or from_config:

from transformers import LlamaModel, LlamaConfig
from transformers.monkey_patching import register_patch_mapping, apply_patches

# Register patch globally
register_patch_mapping(mapping={"LlamaAttention": CustomAttention})

# For manual construction, you need the context manager
with apply_patches():
    model = LlamaModel(LlamaConfig())  # Uses CustomAttention

# Without the context manager, manual construction uses original classes
model = LlamaModel(LlamaConfig())  # Uses LlamaAttention

# But from_pretrained and from_config will always apply registered patches
model = LlamaModel.from_pretrained("meta-llama/Llama-3.2-1B")  # Uses CustomAttention

Important notes

  • Weight handling: Monkey patching only replaces classes, not weights. If your patched class has a different weights layout, you'll need to handle weight conversions separately to ensure compatibility with pretrained weights. See the Complete example below for how to combine monkey patches with weight conversion mappings.

  • Global effect: Patches registered with register_patch_mapping are applied globally to all models loaded after registration. Always use clear_patch_mapping to clean up when done, especially in tests, notebooks, or long-running applications.

  • Class validation: The API automatically validates that replacement classes are nn.Module subclasses. If you pass an invalid class, you'll get a clear error message.

  • Thread safety: All patching operations are thread-safe. You can safely register, unregister, and apply patches from multiple threads.

  • Matching behavior: When using exact class names, they must exactly match the original class names as they appear in the model's source code (case-sensitive). When using regex patterns, they are matched against class names using re.search().

Troubleshooting

My patch isn't being applied

Check class name or pattern: Ensure the class name or pattern in your mapping is correct:

# For exact names - must match exactly (case-sensitive)
register_patch_mapping(mapping={"LlamaAttention": CustomAttention})

# For patterns - use valid regex
register_patch_mapping(mapping={".*Attention": CustomAttention})

Verify registration: Use get_patch_mapping to confirm your mapping is registered:

print(get_patch_mapping())
# Shows all registered mappings: {'LlamaAttention': <class 'CustomAttention'>, '.*MLP': <class 'CustomMLP'>}

Check model source: Find the exact class name in the model's source:

from transformers.models.llama import modeling_llama
print(dir(modeling_llama))  # Look for the class name

How do I know if my patch is working?

Inspect the loaded model to verify the patch:

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")

# Check the type of a specific module
print(type(model.model.layers[0].self_attn))  # Should show your custom class

# Or iterate through all modules
for name, module in model.named_modules():
    if 'attention' in name.lower():
        print(f"{name}: {type(module)}")

Weight shape mismatch errors

If your patched class has different weight shapes, register a weight conversion:

from transformers.conversion_mapping import register_checkpoint_conversion_mapping, WeightConverter
from transformers.monkey_patching import register_patch_mapping

register_patch_mapping(
    mapping={
        "LlamaAttention": LlamaFusedAttention,
    }
)

register_checkpoint_conversion_mapping(
    model_type_or_class_name="llama",
    mapping=[
        WeightConverter(
            source_patterns=["q_proj", "k_proj", "v_proj"],
            target_patterns=["qkv_proj"],
            operations=[
                Concatenate(dim=0),
            ],
        )
    ],
    overwrite=True,
)

Cleaning up patches

Always clean up patches when you're done to avoid affecting other code:

from transformers.monkey_patching import register_patch_mapping, clear_patch_mapping

try:
    register_patch_mapping(mapping={"LlamaAttention": CustomAttention})
    model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
    # ... use model ...
finally:
    clear_patch_mapping()  # Always clean up