regex

Utilities for pattern matching on module and layer names.

Functions

matches_pattern

Check if a name matches any of the given patterns.

matches_pattern(name, patterns, *, allow_callable=True)

Check if a name matches any of the given patterns.

This utility function checks if a given name (e.g., module name, layer name) matches any pattern in a collection of patterns. Patterns can be: - String wildcards (using fnmatch syntax, e.g., “.attention.”) - Callable predicates that take a name and return bool - None (matches everything)

Parameters:
  • name (str) – The name to check (e.g., “model.layer1.attention.weight”)

  • patterns (str | Callable[[str], bool] | Iterable[str | Callable[[str], bool]] | None) – A single pattern, iterable of patterns, or None. If None, returns True (matches everything).

  • allow_callable (bool) – If False, raises TypeError when encountering callable patterns. Useful for contexts where only string patterns are allowed.

Returns:

True if the name matches any pattern, False otherwise.

Raises:

TypeError – If pattern type is unsupported or if callable patterns are provided when allow_callable=False.

Return type:

bool

Examples

>>> matches_pattern("model.attention.query", "*.attention.*")
True
>>> matches_pattern("model.mlp.linear", ["*.attention.*", "*.mlp.*"])
True
>>> matches_pattern("model.layer1", lambda x: "layer" in x)
True
>>> matches_pattern("anything", None)
True