Skip to content

feat(hf_argparser): support dict-typed dataclass fields from CLI (#48030) - #48549

Open
mohmedmm wants to merge 3 commits into
huggingface:mainfrom
mohmedmm:fix-hf-argparser-dict-fields
Open

mohmedmm wants to merge 3 commits into
huggingface:mainfrom
mohmedmm:fix-hf-argparser-dict-fields

Conversation

@mohmedmm

@mohmedmm mohmedmm commented Sep 5, 2026 •

Copy link
Copy Markdown

CPU CI GPU run-slow

Fixes #48030

HfArgumentParser fails when parsing dict-typed dataclass fields from CLI arguments because _parse_dataclass_field falls through to the generic type constructor, raising an invalid dict value error.

This adds a string_to_dict parser supporting JSON strings and file paths, matching the existing list-handling pattern in _parse_dataclass_field.

@nandan2003 nandan2003 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested this locally. works smoothly! This is definitely the right architectural fix for #48030 compared to PR #48033.

Left two small inline notes on string_to_dict.

Once those are tuned, this is ready to approve and merge. LGTM!

Comment thread src/transformers/hf_argparser.py Outdated
Comment on lines +50 to +60
if isinstance(v, dict):
return v
try:
val = json.loads(v)
if isinstance(val, dict):
return val
raise ArgumentTypeError(f"Expected a dict/JSON object, but got {type(val).__name__}: {v!r}")
except (json.JSONDecodeError, TypeError):
pass

try:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good approach! Two small simplifications for inline JSON:

  1. Preserve JSON syntax feedback. If a user passes inline JSON with a typo (e.g. missing quote or unclosed brace), swallowing JSONDecodeError falls through to the file check and gives a generic error. If the trimmed input starts with {, letting JSONDecodeError surface directly gives the user exact line/column feedback on their typo.
  2. Guard against non-strings. If v is None or a non-string, os.path.isfile later raises an unhandled TypeError. Adding an early if not isinstance(v, str): check keeps this safe.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Added non-string guard and let JSONDecodeError surface directly on trimmed { inputs.

Comment thread src/transformers/hf_argparser.py Outdated
Comment on lines +61 to +71
if os.path.isfile(v):
try:
with open(v, "r", encoding="utf-8") as f:
val = json.load(f)
if isinstance(val, dict):
return val
raise ArgumentTypeError(f"Expected a dict from file '{v}', but got {type(val).__name__}")
except Exception as e:
raise ArgumentTypeError(f"Failed to load JSON file '{v}': {e}")
except OSError:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two cleanups on the file-loading logic

  1. Python's stdlib, os.path.isfile() already catches OSError internally and returns False, so the outer try...except OSError block can be safely eliminated.
  2. When a JSON file contains a list instead of a dict, line 67 raises ArgumentTypeError. The except Exception as e: below it catches that same exception and re-wraps it, creating a double-nested error message ("Failed to load JSON file '...': Expected a dict from file..."). Catching specifically (json.JSONDecodeError, OSError) avoids this and lets ArgumentTypeError bubble up cleanly.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Removed redundant outer OSError block and narrowed file load catch to (json.JSONDecodeError, OSError).

@Rocketknight1

Copy link
Copy Markdown
Member

cc @SunMarc maybe?

@mohmedmm

Copy link
Copy Markdown
Author

Applied the feedback @nandan2003. Trimmed inline inputs starting with { now surface JSON errors directly, added the non-string type guard, and narrowed the file loading exception to avoid double-nested errors. Pushed and tests passing!

@github-actions

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 33997888890:2
Result: success | Jobs: 3 | Tests: 44 | Failures: 0 | Duration: 2m 46s

@mohmedmm

mohmedmm commented Oct 2, 2026

Copy link
Copy Markdown
Author

@SunMarc gentle ping when you have a moment — all feedback from @nandan2003 was addressed with tests in place. ready for final review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HfArgumentParser cannot parse dict-typed dataclass fields from the CLI (registers them with type=dict)

3 participants