huggingface/transformers · error · ValueError
Cannot assign to field {name}, you should create a new insta
Error message
Cannot assign to field {name}, you should create a new instance What it means
Raised by WeightTransform.__setattr__ (core_model_loading.py:847). After construction, the attributes source_patterns and target_patterns are frozen: they are linked (capturing groups are validated together and compiled regexes are derived from them), so reassigning one without the other would corrupt the compiled mapping. Any attempt to set transform.source_patterns = [...] or transform.target_patterns = [...] after init raises this error; you must build a new instance instead.
Source
Thrown at src/transformers/core_model_loading.py:847
self.source_patterns[i] = pattern
# Construct the regex we will use to rename keys from the sources to the targets
branches = []
for i, source_pattern in enumerate(self.source_patterns):
group_name = f"g{i}"
pattern = source_pattern.replace(".*.", r"\..*\.")
branches.append(f"(?P<{group_name}>{pattern})")
self.compiled_sources = re.compile("|".join(branches))
def __repr__(self):
return f"{self.__class__.__name__}(source_patterns={self.source_patterns}, target_patterns={self.target_patterns})"
def __setattr__(self, name, value):
if name in ("source_patterns", "target_patterns"):
# We do not allow to re-set the patterns, as they are linked between each other and changing one
# without the other can mess-up with the capturing groups/compiled sources
if hasattr(self, name):
raise ValueError(f"Cannot assign to field {name}, you should create a new instance")
# Switch str to list
elif isinstance(value, str):
value = [value]
object.__setattr__(self, name, value)
def add_tensor(self, target_key: str, source_key: str, source_pattern: str, future: Future):
self.collected_tensors[source_pattern].append(future)
self.layer_targets[target_key].add(source_key)
def _scoped_match(self, source_key: str) -> tuple[str | None, str, re.Match[str]] | None:
"""
Strip `scope_prefix` (if any) from `source_key`, then match `compiled_sources` against the
remaining suffix.
Returns `(prefix_dot, key_to_match, match_object)` on match, else `None`. `prefix_dot` is
the prefix consumed from `source_key`: either `f"{scope_prefix}."` or that same string with
one `base_model_prefix` level stripped or prepended when the former didn't match.
`None` when `scope_prefix` is unset.View on GitHub (pinned to a597f97485)
Solutions
- Create a fresh instance with the new patterns: WeightTransform(source_patterns=..., target_patterns=...).
- If you need many variants, write a small factory function that constructs a transform per pattern set.
- For mutable-in-place workflows, note that in-place list mutation (transform.source_patterns.append(...)) bypasses the guard but is unsupported and dangerous — do not do it; construct a new instance.
Example fix
# before transform = WeightTransform(source_patterns=[r'a.*'], target_patterns=[r'b.*']) transform.target_patterns = [r'c.*'] # raises # after transform = WeightTransform(source_patterns=[r'a.*'], target_patterns=[r'b.*']) transform2 = WeightTransform(source_patterns=[r'a.*'], target_patterns=[r'c.*'])
Defensive patterns
Strategy: type-guard
Type guard
def can_assign_pattern(transform, name: str) -> bool:
return not hasattr(transform, name) Try / catch
try:
transform.target_patterns = new_patterns
except ValueError:
transform = WeightTransform(source_patterns=transform.source_patterns, target_patterns=new_patterns) Prevention
- Treat transforms as immutable value objects: build new instances instead of mutating.
- Write a small factory (make_transform(sources, targets)) so retargeting always means constructing.
- Never use in-place list mutation (append) on transform.source_patterns — it silently bypasses the guard.
When it happens
Trigger: Code like `converter.source_patterns = new_patterns` or `transform.target_patterns += [extra]` (which rebinds the attribute) on an already-initialized WeightTransform/WeightConverter/GroupWeightRename/PrefixChange instance.
Common situations: Utility code that tries to reuse and retarget an existing transform for a second model/section, or copy-pasted code that 'configures' the transform after creation. Also hit when mutating lists via property setters during debugging.
Related errors
- Multiple different capturing groups found in target_patterns
- Source pattern '{pattern}' contains \\1 backreference, but n
- GroupWeightRename requires N:N length matching, but found le
- You must provide only one of `prefix_to_add` and `prefix_to_
- source keys={self.source_patterns}, target_patterns={self.ta
AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14).
Data as JSON: /api/errors/d03b92ccf202dd2e.
Report an issue: GitHub.