Skip to content

Conversation

@RohitYandigeri
Copy link
Contributor

This PR adds stricter validation for the units argument in keras.layers.Dense.

Previously, non-integer or non-positive values could be accepted and either be
silently truncated or fail later with unclear errors. This change ensures that
units must be a positive integer and raises a clear ValueError otherwise.

Includes unit tests covering invalid units values.

This follows TensorFlow review feedback indicating that Dense API validation
should live in the Keras repository.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @RohitYandigeri, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the keras.layers.Dense layer by implementing robust input validation for its units argument. The change ensures that units is always a positive integer, preventing potential runtime issues or unexpected behavior from invalid inputs. This improvement aligns with best practices for API design and provides clearer error messages to users, making the layer more reliable and user-friendly.

Highlights

  • Input Validation: Stricter validation has been added for the units argument in keras.layers.Dense, ensuring it is a positive integer.
  • Error Handling: Invalid units values now raise a clear ValueError instead of silently failing or producing ambiguous errors.
  • Unit Tests: Comprehensive unit tests have been included to cover various invalid units inputs, such as zero, negative numbers, floats, None, and strings.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds input validation for the units argument in the Dense layer, which is a great improvement for robustness and user experience. The changes ensure that units is a positive integer, raising a clear ValueError for invalid inputs. The accompanying unit tests cover a good range of invalid cases.

My review includes two suggestions:

  1. In keras/src/layers/core/dense.py, I recommend a more robust validation check for units that correctly handles numpy integer types, which are common in the ecosystem. The current isinstance(units, int) is a bit too strict.
  2. In keras/src/layers/core/dense_test.py, I suggest parameterizing the new test for invalid units to make it more concise and easier to maintain.

Overall, this is a valuable and well-implemented change.

Comment on lines 97 to 101
if not isinstance(units, int) or units <= 0:
raise ValueError(
"Received an invalid value for `units`, expected a positive integer. "
f"Received: units={units}"
)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The validation isinstance(units, int) is a bit too strict as it will reject numpy integer types (e.g., numpy.int64), which are commonly used in the scientific Python ecosystem. This can lead to unexpected errors for users.

A more robust approach is to check if units is integer-like by trying to convert it to an int and checking for equality. This correctly handles integers, numpy integers, and integer-like floats (e.g., 2.0), while rejecting non-integer floats and other types like strings.

Suggested change
if not isinstance(units, int) or units <= 0:
raise ValueError(
"Received an invalid value for `units`, expected a positive integer. "
f"Received: units={units}"
)
try:
is_int_like = int(units) == units
except (TypeError, ValueError):
is_int_like = False
if not is_int_like or units <= 0:
raise ValueError(
"Received an invalid value for `units`, expected a positive integer. "
f"Received: units={units}"
)

Comment on lines 61 to 75
def test_dense_invalid_units_raises(self):
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(0)

with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(-3)

with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(2.5)

with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(None)

with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense("64")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

These tests for invalid units values are great. To make the test more concise and easier to extend in the future, you could use parameterized.named_parameters which is already used in this test file.

Suggested change
def test_dense_invalid_units_raises(self):
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(0)
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(-3)
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(2.5)
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(None)
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense("64")
@parameterized.named_parameters(
("zero", 0),
("negative", -3),
("float", 2.5),
("none", None),
("string", "64"),
)
def test_dense_invalid_units_raises(self, units):
with self.assertRaisesRegex(ValueError, "positive integer"):
layers.Dense(units)

@codecov-commenter
Copy link

codecov-commenter commented Dec 7, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.30%. Comparing base (f0a48a6) to head (a39f363).

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #21902   +/-   ##
=======================================
  Coverage   76.30%   76.30%           
=======================================
  Files         580      580           
  Lines       60029    60031    +2     
  Branches     9432     9433    +1     
=======================================
+ Hits        45803    45805    +2     
  Misses      11750    11750           
  Partials     2476     2476           
Flag Coverage Δ
keras 76.17% <100.00%> (+<0.01%) ⬆️
keras-jax 62.12% <100.00%> (+<0.01%) ⬆️
keras-numpy 57.31% <100.00%> (-0.01%) ⬇️
keras-openvino 34.30% <0.00%> (-0.01%) ⬇️
keras-torch 63.22% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@RohitYandigeri
Copy link
Contributor Author

It looks like the test suite completed successfully, but the job exited
with a native-level crash after all tests passed. This may be CI flakiness;
happy to rerun or adjust if needed.

Copy link
Collaborator

@hertschuh hertschuh left a comment

Choose a reason for hiding this comment

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

Thanks you for the PR!

Comment on lines 99 to 100
not isinstance(units, numbers.Integral)
or isinstance(units, bool)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Simply replace this with:

if not isinstance(units, int) or units <= 0:

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the clarification!

I’ve updated the validation to enforce a strict int requirement for units and removed the broader numbers.Integral check accordingly. Tests continue to cover invalid inputs.

Locally, the api-gen pre-commit hook reports modified generated files, but I’ve not included those outputs in the commit, following the usual contributor workflow. Happy to regenerate or adjust if you’d prefer otherwise.

Please let me know if you’d like any further changes.

Copy link
Collaborator

Choose a reason for hiding this comment

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

The "code format" check is failing. I believe it's the extra empty line you added line 104.

But the pre-commit hook should just fix that, just do git add keras after it fails.

@RohitYandigeri
Copy link
Contributor Author

@hertschuh Thanks for the pointer!

I reran the pre-commit hooks and staged the formatting changes as suggested. The code format check is now passing.

Please let me know if there’s anything else to adjust.

@google-ml-butler google-ml-butler bot added kokoro:force-run ready to pull Ready to be merged into the codebase labels Dec 9, 2025
@hertschuh hertschuh merged commit 46813a3 into keras-team:master Dec 9, 2025
10 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kokoro:force-run ready to pull Ready to be merged into the codebase size:S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants