huggingface/transformers · error · ValueError

{cls.__name__} accepts only keyword arguments, but found `{l

Error message

{cls.__name__} accepts only keyword arguments, but found `{len(args)}` positional args.

What it means

ValueError raised by the @strict-style dataclass init wrapper used for new-style configs: configuration classes decorated this way accept only keyword arguments. Any positional argument is rejected because field order is not part of the stable API and silent positional binding could construct an invalid config.

Source

Thrown at src/transformers/configuration_utils.py:117

    """Apply legacy → current layer-type name mapping."""
    return [_LEGACY_LAYER_TYPE_REMAP.get(t, t) for t in layer_types]


# copied from huggingface_hub.dataclasses.strict when `accept_kwargs=True`
def wrap_init_to_accept_kwargs(cls: dataclass):
    # Get the original dataclass-generated __init__
    original_init = cls.__init__

    @wraps(original_init)
    def __init__(self, *args, **kwargs: Any) -> None:
        # Extract only the fields that are part of the dataclass
        dataclass_fields = {f.name for f in fields(cls)}
        standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields}

        # We need to call bare `__init__` without `__post_init__` but the `original_init` of
        # any dataclas contains a call to post-init at the end (without kwargs)
        if len(args) > 0:
            raise ValueError(
                f"{cls.__name__} accepts only keyword arguments, but found `{len(args)}` positional args."
            )

        for f in fields(cls):  # type: ignore
            if f.name in standard_kwargs:
                setattr(self, f.name, standard_kwargs[f.name])
            elif f.default is not MISSING:
                setattr(self, f.name, f.default)
            elif f.default_factory is not MISSING:
                setattr(self, f.name, f.default_factory())
            else:
                raise TypeError(f"Missing required field - '{f.name}'")

        # Pass any additional kwargs to `__post_init__` and let the object
        # decide whether to set the attr or use for different purposes (e.g. BC checks)
        additional_kwargs = {}
        for name, value in kwargs.items():
            if name not in dataclass_fields:

View on GitHub (pinned to a597f97485)

Solutions

  1. Pass every argument as a keyword: SomeConfig(hidden_size=768, num_heads=12)
  2. If unpacking a dict, use SomeConfig(**params) rather than SomeConfig(*params)
  3. Check the config class docstring/fields for the exact accepted keyword names

Example fix

# before
cfg = MyConfig(768, 12)
# after
cfg = MyConfig(hidden_size=768, num_attention_heads=12)
Defensive patterns

Strategy: type-guard

Validate before calling

import inspect
sig = inspect.signature(MyConfig)
assert all(p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY) for p in sig.parameters.values())
cfg = MyConfig(**params)  # never positional

Type guard

def build_strict(cls, params: dict):
    if not all(isinstance(k, str) for k in params):
        raise TypeError('strict configs accept keyword arguments only')
    return cls(**params)

Try / catch

try:
    cfg = MyConfig(**params)
except ValueError as e:
    if 'positional args' in str(e):
        raise TypeError('rewrite the call with keyword arguments') from e
    raise

Prevention

When it happens

Trigger: Constructing a strict config dataclass positionally, e.g. SomeConfig(768, 12) instead of SomeConfig(hidden_size=768, num_heads=12). Also unpacking a tuple/list into the constructor.

Common situations: Porting old code that relied on positional args of a legacy (non-dataclass) config; IDE autocompletion inserting positional placeholders; code generation that emits positional constructors.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/98c762c8f19f2c15. Report an issue: GitHub.