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

feat: download only necessary model files #58

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

vatsalkshah
Copy link
Contributor

@vatsalkshah vatsalkshah commented Oct 28, 2024

download only necessary model files

Summary by CodeRabbit

  • New Features

    • Enhanced model loading capabilities with additional parameters for flexibility.
    • Introduced a new lora_only parameter in the validation process to filter models.
  • Bug Fixes

    • Improved error handling for model loading and validation submission processes.
    • Adjusted logic to manage model parameter limits and logging for better clarity.
  • Documentation

    • Updated logging messages for consistency and clarity during execution.

Copy link
Contributor

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes in this pull request primarily focus on enhancements to the src/validate.py file. Key modifications include updates to the load_model function, which now accepts additional parameters for improved model loading flexibility. The validate command has been updated to include a new parameter for controlling validation of models with LoRA weights, alongside refined error handling for model loading and validation processes. Additionally, the loop command has been improved for better error management, and minor adjustments have been made to logging for clarity.

Changes

File Change Summary
src/validate.py Updated load_model function signature to include subfolder and allow_patterns parameters.
Modified validate function signature to include lora_only parameter and refined error handling.
Enhanced error handling in the loop command for validation assignment requests.
Adjusted logging messages for clarity and consistency.

Poem

In the burrow, changes sprout,
Models load, there's no doubt!
With LoRA weights, we validate,
Errors handled, oh, how great!
Hops of joy in code we weave,
A rabbit's heart, we do believe! 🐇✨


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

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 and nitpick comments (3)
src/validate.py (3)

Line range hint 324-326: Initialize 'resp' before using it to avoid 'NameError'

In the loop function, if the for loop completes without a successful assignment (no break is executed), the variable resp might remain undefined. This can lead to a NameError when checking if resp is None or resp.status_code != 200:.

Initialize resp before the for loop:

 def loop(
     validation_args_file: str,
     task_id: str = None,
     auto_clean_cache: bool = True,
     lora_only: bool = True,
 ):
     if task_id is None:
         raise ValueError("task_id is required for asking assignment_id")
     if auto_clean_cache:
         logger.info("Auto clean the model cache except for the base model")
     else:
         logger.info("Skip auto clean the model cache")
 
     repo_path = Path(__file__).resolve().parent.parent
 
     if not IS_DOCKER_CONTAINER:
         is_latest_version(repo_path)
     else:
         logger.info("Skip checking the latest version in docker container")
         logger.info(
             "Please make sure you are using the latest version of the docker image."
         )
 
     fed_ledger = FedLedger(FLOCK_API_KEY)
     task_id_list = task_id.split(",")
     logger.info(f"Validating task_id: {task_id_list}")
+    resp = None  # Initialize resp variable
     last_successful_request_time = [time.time()] * len(task_id_list)
     while True:
         clean_model_cache(auto_clean_cache)

Line range hint 275-278: Add a delay between retries in the exception handling loop

In the loop function, consider adding a brief delay between retries when handling exceptions during validation attempts. This prevents rapid successive attempts and allows for graceful recovery.

Apply this diff to add a delay:

 for attempt in range(3):
     try:
         ctx = click.Context(validate)
         ctx.invoke(
             validate,
             model_name_or_path=resp["task_submission"]["data"]["hg_repo_id"],
             base_model=resp["data"]["base_model"],
             eval_file=eval_file,
             context_length=resp["data"]["context_length"],
             max_params=resp["data"]["max_params"],
             validation_args_file=validation_args_file,
             assignment_id=resp["id"],
             local_test=False,
             lora_only=lora_only,
             revision=revision,
         )
         break  # Break the loop if no exception
     except KeyboardInterrupt:
         sys.exit(1)
     except OSError as e:
         handle_os_error(e, assignment_id, fed_ledger)
     except RuntimeError as e:
         handle_runtime_error(e, assignment_id, fed_ledger)
     except ValueError as e:
         handle_value_error(e, assignment_id, fed_ledger)
     except Exception as e:
         logger.error(f"Attempt {attempt + 1} failed: {e}")
+        time.sleep(5)  # Add a delay before next attempt
         if attempt == 2:
             logger.error(
                 f"Marking assignment {assignment_id} as failed after 3 attempts"
             )
             fed_ledger.mark_assignment_as_failed(assignment_id)

Line range hint 235-239: Specify the exception to be raised for outdated code

In the is_latest_version function, after logging the error about the local code not being up-to-date, the bare raise statement should specify the exception to be raised for clarity and proper exception handling.

Apply this diff to specify the exception:

 if local_commit.hexsha != remote_commit.hexsha:
     logger.error(
         "The local code is not up to date with the main branch. Please update your version."
     )
-    raise
+    raise Exception("Local code is outdated. Please pull the latest changes.")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8366410 and fb9a1b3.

📒 Files selected for processing (1)
  • src/validate.py (1 hunks)
🔇 Additional comments (1)
src/validate.py (1)

Line range hint 190-193: Verify the model after merging adapter weights

After merging and unloading the adapter weights with model = model.merge_and_unload(), ensure that the model remains fully functional and all necessary attributes are intact. This helps prevent unexpected behavior during model evaluation.

Comment on lines +157 to +169
model_name_or_path,
token=HF_TOKEN,
**model_kwargs,
subfolder="",
allow_patterns=[
"adapter_config.json",
"adapter_model.safetensors",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer_config.json",
"training_args.bin",
"tokenizer.model",
],
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace 'token' with 'use_auth_token' in 'from_pretrained'

The AutoModelForCausalLM.from_pretrained method does not accept a token argument. Instead, use use_auth_token=HF_TOKEN to properly authenticate with Hugging Face for private or gated models.

Apply this diff to correct the argument:

 model = AutoModelForCausalLM.from_pretrained(
     model_name_or_path,
-    token=HF_TOKEN,
+    use_auth_token=HF_TOKEN,
     **model_kwargs,
     subfolder="",
     allow_patterns=[
         "adapter_config.json",
         "adapter_model.safetensors",
         "special_tokens_map.json",
         "tokenizer.json",
         "tokenizer_config.json",
         "training_args.bin",
         "tokenizer.model",
     ],
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
model_name_or_path,
token=HF_TOKEN,
**model_kwargs,
subfolder="",
allow_patterns=[
"adapter_config.json",
"adapter_model.safetensors",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer_config.json",
"training_args.bin",
"tokenizer.model",
],
model_name_or_path,
use_auth_token=HF_TOKEN,
**model_kwargs,
subfolder="",
allow_patterns=[
"adapter_config.json",
"adapter_model.safetensors",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer_config.json",
"training_args.bin",
"tokenizer.model",
],

"special_tokens_map.json",
"tokenizer.json",
"tokenizer_config.json",
"training_args.bin",
Copy link
Contributor

Choose a reason for hiding this comment

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

do we need training_args to run successfully?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, it is not always needed. Can help those that want to run custom validation scripts and usually just a few kBs. I'll remove it though for now.

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.

2 participants