Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@xingchensong
Copy link
Owner

@xingchensong xingchensong commented Jun 2, 2025

Summary by CodeRabbit

  • New Features

    • Expanded support for new model types, including "llama", "llama.asr", "qwen2_audio", and "kimi_audio".
    • Integrated additional model configurations for improved compatibility with external libraries.
  • Improvements

    • Streamlined batch handling and device management during training for improved performance and reliability.
    • Improved tokenizer setup to handle missing special tokens more robustly.
    • Ensured model parameters use consistent data types post-parallelization for better convergence.
  • Refactor

    • Simplified internal module structure for easier maintenance and reduced side effects during imports.
    • Removed redundant parameter counting utilities to consolidate functionality.

@coderabbitai
Copy link

coderabbitai bot commented Jun 2, 2025

Warning

Rate limit exceeded

@xingchensong has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 25 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between af88586 and 8a0c13d.

📒 Files selected for processing (2)
  • touchnet/__init__.py (1 hunks)
  • touchnet/bin/train.py (7 hunks)

Walkthrough

The changes centralize model training specification and configuration registration by moving them from individual model submodules, such as touchnet/models/llama, into the package's main __init__.py. Batch handling, tokenizer construction, and model parameter dtype management are refactored in the training script. Utility functions are reorganized, and redundant imports and registrations are removed. Test imports for datapipe classes are updated.

Changes

File(s) Change Summary
touchnet/init.py Centralizes explicit imports and registers training specs and model configs/classes for multiple models, including new audio models.
touchnet/bin/train.py Refactors batch handling, tokenizer construction, dtype conversion, and model parameter counting for improved robustness and consistency.
touchnet/models/init.py Removes import and side-effect registration for llama model specs.
touchnet/models/llama/init.py Removes all training spec and transformer registration logic; adds a utility function for counting model parameters.
touchnet/utils/metrics.py Removes the get_num_params function, now relocated to the llama model module.
tests/touchnet/bin/test_make_data.py Updates import and instantiation from TouchDatapipe to LowLevelTouchDatapipe.
tests/touchnet/data/test_dataloader.py Replaces TouchDatapipe with LowLevelTouchDatapipe in imports and instantiations.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Trainer
    participant Model
    participant Tokenizer
    participant TrainSpecRegistry

    User->>Trainer: Initialize Trainer
    Trainer->>TrainSpecRegistry: Retrieve TrainSpec for model
    Trainer->>Tokenizer: Build tokenizer (conditionally pass special tokens)
    Trainer->>Model: Build and parallelize model
    Model->>Trainer: Return model (converted to float32)
    Trainer->>User: Ready for training steps

    User->>Trainer: Train step with batch
    Trainer->>Trainer: Move batch tensors to device
    Trainer->>Model: Forward pass with unpacked batch
    Model->>Trainer: Return outputs
    Trainer->>User: Compute loss, accuracy, and metrics
Loading

Possibly related PRs

Poem

In the warren of code, we hop and we shift,
Registries gathered, no specs left adrift.
Batch moves are nimble, dtypes align,
Tokenizers check for each special sign.
Llama and friends, their specs now reside,
In one cozy burrow, where all models abide!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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: 2

🧹 Nitpick comments (2)
touchnet/models/llama/__init__.py (1)

50-60: Add docstring and consider improving readability.

The function implementation is correct, but it needs documentation and could be slightly more readable.

 def get_num_params(model: torch.nn.Module, exclude_embedding: bool = False) -> int:
+    """Calculate the total number of parameters in a model.
+    
+    Args:
+        model: The PyTorch model to analyze.
+        exclude_embedding: If True, exclude embedding layer parameters from the count.
+        
+    Returns:
+        The total number of parameters.
+    """
     num_params = sum(p.numel() for p in model.parameters())
     if exclude_embedding:
         base_model_prefix = getattr(model, "base_model_prefix", "model")
         submodel = getattr(model, f"{base_model_prefix}")
-        num_params -= sum(
-            sum(p.numel() for p in m.parameters())
-            for m in submodel.children()
-            if isinstance(m, torch.nn.Embedding)
-        )
+        embedding_params = sum(
+            p.numel()
+            for m in submodel.children()
+            if isinstance(m, torch.nn.Embedding)
+            for p in m.parameters()
+        )
+        num_params -= embedding_params
     return num_params
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 50-50: Missing function or method docstring

(C0116)

touchnet/bin/train.py (1)

332-334: Simplify dictionary iteration.

Remove unnecessary .keys() when iterating over dictionary keys.

-        for key in batch.keys():
+        for key in batch:
             if batch[key] is not None and torch.is_tensor(batch[key]):
                 batch[key] = batch[key].to(device_type)
🧰 Tools
🪛 Ruff (0.11.9)

332-332: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b70643d and f5ffa40.

📒 Files selected for processing (5)
  • touchnet/__init__.py (1 hunks)
  • touchnet/bin/train.py (7 hunks)
  • touchnet/models/__init__.py (0 hunks)
  • touchnet/models/llama/__init__.py (1 hunks)
  • touchnet/utils/metrics.py (0 hunks)
💤 Files with no reviewable changes (2)
  • touchnet/models/init.py
  • touchnet/utils/metrics.py
🧰 Additional context used
🪛 Pylint (3.3.7)
touchnet/models/llama/__init__.py

[convention] 50-50: Missing function or method docstring

(C0116)

touchnet/bin/train.py

[convention] 238-238: Line too long (110/100)

(C0301)


[convention] 240-240: Line too long (113/100)

(C0301)


[convention] 244-244: Line too long (104/100)

(C0301)


[convention] 245-245: Line too long (104/100)

(C0301)


[convention] 250-250: Line too long (111/100)

(C0301)


[convention] 251-251: Line too long (110/100)

(C0301)


[convention] 257-257: Line too long (103/100)

(C0301)


[convention] 258-258: Line too long (104/100)

(C0301)


[convention] 259-259: Line too long (119/100)

(C0301)


[convention] 345-345: Line too long (103/100)

(C0301)


[warning] 337-348: String statement has no effect

(W0105)


[convention] 425-425: Line too long (107/100)

(C0301)


[convention] 426-426: Line too long (104/100)

(C0301)

touchnet/__init__.py

[error] 6-6: Unable to import 'transformers'

(E0401)


[error] 7-7: Unable to import 'transformers.models.llama'

(E0401)


[error] 8-9: Unable to import 'transformers.models.qwen2_audio'

(E0401)


[warning] 11-11: Module import itself

(W0406)

🪛 Ruff (0.11.9)
touchnet/bin/train.py

332-332: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

🔇 Additional comments (5)
touchnet/__init__.py (2)

30-109: Excellent centralization of model training specifications!

Moving the training specifications from individual model modules to a central location improves maintainability and discoverability. The TODO comments clearly document the current limitations for qwen2_audio and kimi_audio models.


112-115: Proper integration with transformers library.

The model registration with AutoConfig and AutoModelForCausalLM follows the correct pattern and ensures no duplicate registrations with exist_ok=False.

touchnet/bin/train.py (3)

126-138: Good defensive programming for tokenizer construction.

The conditional checking for special token attributes before passing them to the tokenizer builder prevents potential AttributeErrors and makes the code more robust across different model configurations.


238-266: Excellent documentation of the parallelization process and good practice for training stability.

The detailed comments explaining DTensor transformations during parallelization are extremely helpful for understanding the complex process. Converting model parameters to float32 after parallelization is a good practice for better convergence.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 238-238: Line too long (110/100)

(C0301)


[convention] 240-240: Line too long (113/100)

(C0301)


[convention] 244-244: Line too long (104/100)

(C0301)


[convention] 245-245: Line too long (104/100)

(C0301)


[convention] 250-250: Line too long (111/100)

(C0301)


[convention] 251-251: Line too long (110/100)

(C0301)


[convention] 257-257: Line too long (103/100)

(C0301)


[convention] 258-258: Line too long (104/100)

(C0301)


[convention] 259-259: Line too long (119/100)

(C0301)


419-430: Clean batch unpacking implementation.

Using .pop() to extract values that shouldn't be passed to the model's forward call is a good practice. It makes the code cleaner and prevents unnecessary data from being passed downstream.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 425-425: Line too long (107/100)

(C0301)


[convention] 426-426: Line too long (104/100)

(C0301)

@xingchensong xingchensong merged commit 5af581e into main Jun 2, 2025
3 checks passed
@xingchensong xingchensong deleted the dev branch June 2, 2025 11:03
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