Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch from manual to pydantic validation of config and LighterSystem #135

Merged
merged 23 commits into from
Sep 4, 2024

Conversation

ibro45
Copy link
Collaborator

@ibro45 ibro45 commented Aug 6, 2024

Description

  • Switched to Pydantic for structure validation. Not ecstatic about this solution (especially Pydantic error messages), but it is better than the current solution. I hope to figure out something better in the future. Resulted in a nice cleanup of runner.py and system.py.

  • Implemented PatchedModuleDict. Cleans up system from the ugly "_" + metric workaround.

  • Added support for multi-command runs, e.g. lighter fit test --config=.... Convenient when you want things to be logged under the same run, not sure if there are additional benefits.

  • Backwards compatible, any previous config should work with this.

  • Reorganized the order of LighterSystem's methods

Related Issue

Type of Change

  • 📚 Examples / docs / tutorials / dependencies update
  • 🔧 Bug fix (non-breaking change which fixes an issue)
  • 🥂 Improvement (non-breaking change which improves an existing feature)
  • 🚀 New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to change)
  • 🔐 Security fix

Checklist

  • I've read the CODE_OF_CONDUCT.md document.
  • I've read the CONTRIBUTING.md guide.
  • I've updated the code style using make codestyle.
  • I've written tests for all new methods and classes that I created.
  • I've written the docstring in Google format for all the methods and classes that I used.

Summary by CodeRabbit

  • New Features

    • Introduced PatchedModuleDict class to enhance module management and prevent key conflicts.
    • Added comprehensive configuration schemas for improved validation and organization of machine learning components.
  • Bug Fixes

    • Enhanced logging by suppressing specific module tracebacks for clearer error messages.
  • Chores

    • Updated project dependencies to include specific versions of numpy and pydantic for better compatibility.
  • Refactor

    • Simplified initialization processes and type annotations across various classes for improved clarity and maintainability.
  • Tests

    • Added parameterized tests for validating configuration schemas to ensure proper formatting and adherence to expected structures.

Copy link
Contributor

coderabbitai bot commented Aug 6, 2024

Walkthrough

The changes involve updates to type annotations across multiple files, primarily replacing torch.Tensor with the imported Tensor type for improved readability. Several classes and functions have been modified to enhance initialization processes and schema validation. New schemas for configuration management have been introduced, and the pyproject.toml file has been updated to include new dependencies. Additionally, a new test file has been added for validating configuration schemas.

Changes

Files Change Summary
lighter/callbacks/utils.py Updated preprocess_image function to use Tensor type instead of torch.Tensor.
lighter/callbacks/writer/base.py Changed write method parameter type from torch.Tensor to Tensor.
lighter/callbacks/writer/file.py Removed constructor from LighterFileWriter, updated write method and write_itk_image function to use Tensor.
lighter/system.py Removed several initialization methods, added schema validation, updated type annotations in forward and _log_stats.
lighter/utils/logging.py Added "pydantic" to SUPPRESSED_MODULES list for improved logging.
lighter/utils/misc.py Removed ensure_dict_schema function.
lighter/utils/patches.py Introduced PatchedModuleDict class to handle key conflicts in ModuleDict.
lighter/utils/runner.py Enhanced CLI functionality and configuration handling, replacing static structure with dynamic schema usage.
lighter/utils/schema.py Added multiple configuration schemas using Pydantic's BaseModel.
pyproject.toml Added dependencies for numpy and pydantic with version constraints.
tests/configs/test1.yaml Introduced a YAML configuration file for testing parameters.
tests/unit/test_schema.py Added parameterized test for validating configuration schemas with pytest.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant ConfigSchema
    participant LighterSystem

    User->>CLI: Run command
    CLI->>ConfigSchema: Validate configuration
    ConfigSchema-->>CLI: Return validated config
    CLI->>LighterSystem: Initialize with config
    LighterSystem-->>CLI: Confirm initialization
    CLI-->>User: Display success message
Loading

🐰 "In the code's bright glade,
Changes hop and dance,
Types refined, schemas made,
A clearer code romance.
With each new line we write,
Our project takes to flight!"
🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@surajpaib
Copy link
Collaborator

@ibro45 Can you fix the style checks?

@ibro45
Copy link
Collaborator Author

ibro45 commented Aug 9, 2024

The PR is still under construction - don't like several things and am taking some time to think out of the box.

Honestly, this whole validation thing is shit. I wish it would be purely Monai Bundle stuff, enforced with _target_ and no dataclasses/validation. It's annoying to have most of LighterSystem intuitively designed, and then there's this weird structure for postprocessing or metrics.

Right now, I'm considering introducing a LighterTrainer, a subclass of PL Trainer. That is, if it is possible to implement new hooks in addition to on_train_epoch_end() and others, allowing us to have Postprocessing, Metrics, Inferer, etc. as callbacks rather than having them defined in LighterSystem.

This crossed my mind yesterday. I still have to look into whether it's possible and if it just ends up complicating it. But this could potentially solve a lot of problems rn - maybe it would even open up a way to nicely re-design how data loaders are defined (not clear to me how rn, but food for thought).

Let me know what you think.

ibro45 and others added 18 commits August 9, 2024 12:55
Bumps [aiohttp](https://github.com/aio-libs/aiohttp) from 3.9.5 to 3.10.2.
- [Release notes](https://github.com/aio-libs/aiohttp/releases)
- [Changelog](https://github.com/aio-libs/aiohttp/blob/master/CHANGES.rst)
- [Commits](aio-libs/aiohttp@v3.9.5...v3.10.2)

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ibrahim Hadzic <[email protected]>
Bumps [zipp](https://github.com/jaraco/zipp) from 3.19.0 to 3.19.1.
- [Release notes](https://github.com/jaraco/zipp/releases)
- [Changelog](https://github.com/jaraco/zipp/blob/main/NEWS.rst)
- [Commits](jaraco/zipp@v3.19.0...v3.19.1)

---
updated-dependencies:
- dependency-name: zipp
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ibrahim Hadzic <[email protected]>
Bumps [certifi](https://github.com/certifi/python-certifi) from 2024.2.2 to 2024.7.4.
- [Commits](certifi/python-certifi@2024.02.02...2024.07.04)

---
updated-dependencies:
- dependency-name: certifi
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ibrahim Hadzic <[email protected]>
@ibro45 ibro45 marked this pull request as ready for review August 28, 2024 18:03
@dosubot dosubot bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Aug 28, 2024
@ibro45 ibro45 requested a review from surajpaib August 28, 2024 18:04
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3e043af and 442cee3.

Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
Files selected for processing (10)
  • lighter/callbacks/utils.py (2 hunks)
  • lighter/callbacks/writer/base.py (3 hunks)
  • lighter/callbacks/writer/file.py (4 hunks)
  • lighter/system.py (8 hunks)
  • lighter/utils/logging.py (1 hunks)
  • lighter/utils/misc.py (1 hunks)
  • lighter/utils/patches.py (1 hunks)
  • lighter/utils/runner.py (4 hunks)
  • lighter/utils/schema.py (1 hunks)
  • pyproject.toml (1 hunks)
Files skipped from review due to trivial changes (4)
  • lighter/callbacks/utils.py
  • lighter/callbacks/writer/base.py
  • lighter/utils/logging.py
  • lighter/utils/misc.py
Additional comments not posted (35)
lighter/utils/patches.py (8)

18-20: LGTM!

The __init__ method is correctly implemented.

The code changes are approved.


22-34: LGTM!

The __setitem__ method is correctly implemented and ensures unique internal keys.

The code changes are approved.


36-47: LGTM!

The __getitem__ method is correctly implemented.

The code changes are approved.


49-57: LGTM!

The __delitem__ method is correctly implemented.

The code changes are approved.


59-70: LGTM!

The __contains__ method is correctly implemented.

The code changes are approved.


72-79: LGTM!

The keys method is correctly implemented.

The code changes are approved.


81-88: LGTM!

The items method is correctly implemented.

The code changes are approved.


90-97: LGTM!

The values method is correctly implemented.

The code changes are approved.

lighter/callbacks/writer/file.py (3)

9-9: LGTM!

The import statement for Tensor from torch is correctly added.

The code changes are approved.


41-41: LGTM!

The type annotation for the write method is correctly updated to use Tensor instead of torch.Tensor.

The code changes are approved.


82-82: LGTM!

The type annotation for the write_itk_image function is correctly updated to use Tensor instead of torch.Tensor.

The code changes are approved.

lighter/utils/runner.py (6)

12-12: LGTM!

The import statement for ArgsConfigSchema and ConfigSchema is correctly added.

The code changes are approved.


17-18: LGTM!

The cli function is correctly updated to dynamically generate commands based on the schema.

The code changes are approved.


35-45: LGTM!

The parse_config function is correctly updated to use the schema for configuration validation.

The code changes are approved.


49-63: LGTM!

The run function is correctly updated to accept multiple methods and validate them against the schema.

The code changes are approved.


Line range hint 66-86: LGTM!

The run function is correctly updated to use the parse_config function for configuration parsing.

The code changes are approved.


90-97: LGTM!

The run function is correctly updated to execute the specified methods of the Trainer or Tuner.

The code changes are approved.

lighter/utils/schema.py (9)

17-39: LGTM!

The ArgsConfigSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


42-48: LGTM!

The ConfigSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


54-58: LGTM!

The DatasetSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


61-65: LGTM!

The SamplerSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


68-72: LGTM!

The CollateFnSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


75-85: LGTM!

The MetricsSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


88-92: LGTM!

The ModeSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


95-98: LGTM!

The DataSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.


101-105: LGTM!

The PostprocessingSchema class is well-structured and effectively uses Pydantic's validation.

The code changes are approved.

pyproject.toml (2)

47-47: LGTM!

The addition of numpy with the version constraint < 2.0.0 is appropriate.

The code changes are approved.


49-49: LGTM!

The addition of pydantic with the version constraint ^2.8.2 is appropriate.

The code changes are approved.

lighter/system.py (7)

100-106: LGTM!

The __init__ method is well-structured and effectively uses schema validation.

The code changes are approved.


Line range hint 115-134: LGTM!

The forward method is well-structured and uses the Tensor type appropriately.

The code changes are approved.


136-147: LGTM!

The configure_optimizers method is well-structured and ensures that the optimizer and scheduler are correctly configured.

The code changes are approved.


149-175: LGTM!

The setup method is well-structured and ensures that the dataloaders and step methods are correctly set up based on the training stage.

The code changes are approved.


177-217: LGTM!

The _base_dataloader method is well-structured and ensures that the dataloader is correctly instantiated for a given mode. The use of a collate function to handle corrupted examples is appropriate.

The code changes are approved.


Line range hint 218-309: LGTM!

The _base_step method is well-structured and ensures that the base step is correctly performed for all modes. The inclusion of postprocessing and validation of the batch data is appropriate.

The code changes are approved.


Line range hint 311-329: LGTM!

The _log_stats method is well-structured and ensures that the loss, metrics, and optimizer statistics are correctly logged.

The code changes are approved.

@surajpaib
Copy link
Collaborator

@ibro45 Could you add some tests for the config validation?

I think tests similar to what MONAI does would be very useful moving ahead.

P.S: Cursor writes amazing tests if you reference a source tests file and select a target file to be tested in the code embeds

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 442cee3 and 0766968.

Files selected for processing (1)
  • lighter/utils/schema.py (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • lighter/utils/schema.py

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
tests/unit/test_schema.py (1)

8-22: LGTM! Consider adding more assertions to validate the structure and contents of the parsed configuration.

The test function is well-structured and follows the Arrange-Act-Assert pattern. The use of the @pytest.mark.parametrize decorator is effective for testing multiple configuration files. The function has a clear and concise docstring that explains the purpose of the test.

To further improve the test, consider adding more assertions to validate the structure and contents of the parsed configuration. For example, you could assert the presence of specific keys or the types of values associated with those keys.

# Example assertions
assert "model" in parsed_config.config
assert isinstance(parsed_config.config["model"], dict)
assert "optimizer" in parsed_config.config
assert isinstance(parsed_config.config["optimizer"], dict)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0766968 and 451a33a.

Files selected for processing (2)
  • tests/configs/test1.yaml (1 hunks)
  • tests/unit/test_schema.py (1 hunks)
Additional context used
yamllint
tests/configs/test1.yaml

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)

Additional comments not posted (2)
tests/configs/test1.yaml (2)

1-1: Verify the usage of the _requires_ section.

The _requires_ section is used to import the os module, which is a non-standard YAML feature. This could be a project-specific convention.

Run the following script to verify the usage of the _requires_ section:


2-16: Verify the usage of the defined variables and arguments.

The file defines variables in the vars section and arguments for different commands in the args section.

Run the following script to verify the usage of the defined variables and arguments:

Verification successful

Variables and Arguments Not Used in Python Codebase

The variables some_var and arguments some_arg defined in the YAML file are not found in the Python codebase. This suggests they are currently unused in the Python files. Please verify if they are intended to be used elsewhere or if they need to be integrated into the code.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the defined variables and arguments in the codebase.

# Test: Search for the usage of the defined variables. Expect: Occurrences in the codebase.
rg --type python 'some_var'

# Test: Search for the usage of the defined arguments. Expect: Occurrences in the codebase.
rg --type python 'some_arg'

Length of output: 117


Script:

#!/bin/bash
# Description: Verify the usage of the defined variables and arguments in the codebase.

# Test: Search for the usage of the defined variables. Expect: Occurrences in the codebase.
rg --type py 'some_var'

# Test: Search for the usage of the defined arguments. Expect: Occurrences in the codebase.
rg --type py 'some_arg'

Length of output: 47

Tools
yamllint

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)

lr_find:
some_arg: "value"
scale_batch_size:
some_arg: "value"
Copy link
Contributor

Choose a reason for hiding this comment

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

Add a newline at the end of the file.

The yamllint tool reported an error indicating a missing newline at the end of the file.

Add a newline at the end of the file to fix the yamllint error.

Tools
yamllint

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 451a33a and c424343.

Files selected for processing (1)
  • tests/unit/test_schema.py (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/unit/test_schema.py

@surajpaib surajpaib merged commit 5bc2ccb into main Sep 4, 2024
3 checks passed
@surajpaib surajpaib deleted the pydantic branch September 4, 2024 22:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size:XL This PR changes 500-999 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants