Skip to content

Lora kernels fix#2732

Merged
djsaunde merged 3 commits into
mainfrom
lora-kernels-fix
May 28, 2025
Merged

Lora kernels fix#2732
djsaunde merged 3 commits into
mainfrom
lora-kernels-fix

Conversation

@djsaunde

@djsaunde djsaunde commented May 27, 2025

Copy link
Copy Markdown
Collaborator

Description

I realized that a recent change broke the actual application of the self attention code monkeypatches related to LoRA kernels. This PR fixes that.

Also simplified the application of some patches a bit.

Motivation and Context

How has this been tested?

Add pytest, manually tested with and without changes.

Screenshots (if appropriate)

Types of changes

Social Handles (Optional)

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Improved the application sequence and configuration checks for LLaMA loss and self-attention LoRA kernel patches, ensuring correct and non-redundant patching behavior.
  • Tests
    • Enhanced integration tests for LoRA kernel patching, including validation that kernel patching options are auto-enabled and that patched methods are correctly applied to model layers.
  • New Features
    • Expanded model loading capabilities to support additional model types for improved flexibility.

@djsaunde djsaunde requested a review from winglian May 27, 2025 19:24
@djsaunde djsaunde self-assigned this May 27, 2025
@coderabbitai

coderabbitai Bot commented May 27, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

The changes update type annotations and imports in the model loader to support PeftModelForCausalLM, reorganize and rename patching methods in the patch manager for improved logic and configuration handling, and add comprehensive integration tests for LoRA kernel patching, ensuring correct patch application and side effects in loaded models.

Changes

File(s) Change Summary
src/axolotl/loaders/model.py Expanded PEFT imports; updated ModelLoader.load return type to include PeftModelForCausalLM.
src/axolotl/loaders/patch_manager.py Reordered patch calls; renamed and refactored self-attention patch method; adjusted configuration checks.
tests/e2e/patched/lora_kernels/test_lora_kernel_patching.py Enhanced integration tests for LoRA kernel patching and model loading side effects.

Sequence Diagram(s)

sequenceDiagram
    participant Config
    participant ModelLoader
    participant Tokenizer
    participant Model
    participant PatchManager

    Config->>ModelLoader: Provide configuration
    ModelLoader->>Tokenizer: load_tokenizer(config)
    ModelLoader->>Model: load_model(config)
    ModelLoader->>PatchManager: Apply patches to Model
    PatchManager->>Model: Patch self-attention/LoRA kernels
    ModelLoader-->>Config: Return loaded Model and config
Loading

Possibly related PRs

  • axolotl-ai-cloud/axolotl#2680: Refactored ModelLoader into axolotl.loaders.model, directly related to the changes in imports and type annotations in this PR.

Suggested reviewers

  • winglian

Poem

In the warren of code where the LoRA bunnies hop,
Kernels are patched and type hints never stop.
With models and configs all neat and precise,
PatchManager scurries, applying each splice.
Tests now ensure our kernels will sing—
Oh, what delight these new changes bring! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 85ef3bd and e355edb.

📒 Files selected for processing (2)
  • src/axolotl/loaders/model.py (2 hunks)
  • src/axolotl/loaders/patch_manager.py (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🔭 Outside diff range comments (2)
src/axolotl/loaders/model.py (1)

148-154: 🛠️ Refactor suggestion

Return annotation no longer covers every path

load() can still legitimately return a PeftModel or PeftMixedModel when

  • self.qlora_fsdp is True (model is not merged back)
  • cfg.merge_lora is False
  • a mixed PEFT model is produced for IPO/DPO reference models, etc.

Those concrete types were removed from the signature, while PeftModelForCausalLM was added (which is already a subclass of PeftModel).
To keep static checkers (e.g. mypy, pyright) happy, include all possibilities:

-    def load(self) -> tuple[PreTrainedModel | PeftModelForCausalLM, PeftConfig | None]:
+    def load(
+        self,
+    ) -> tuple[
+        PreTrainedModel | PeftModel | PeftMixedModel | PeftModelForCausalLM,
+        PeftConfig | None,
+    ]:

(or simply PreTrainedModel | PeftModel | PeftMixedModel).
Clarifies intent and avoids false-positive type errors downstream.

tests/e2e/patched/lora_kernels/test_lora_kernel_patching.py (1)

473-504: ⚠️ Potential issue

Test leaves global patch in place – may create cross-test bleed-through

ModelLoader.load() patches the class attention_cls.forward, and the test asserts on that – but never restores the original implementation afterwards.
If another test in the same session relies on the un-patched forward (or performs its own patch/unpatch cycle) you can get flaky failures.

Add a try/finally (or addfinalizer) to put the original method back:

-    model, _ = ModelLoader(cfg, tokenizer).load()
+    model, _ = ModelLoader(cfg, tokenizer).load()
     ...
-    assert found_patched_attn
+    assert found_patched_attn
+
+    # cleanup – restore original forward to avoid polluting other tests
+    attention_cls.forward = original_forward_method
+    if hasattr(attention_cls, "_original_forward"):
+        delattr(attention_cls, "_original_forward")

Small change, big reduction in hidden coupling between tests.

🧹 Nitpick comments (2)
src/axolotl/loaders/model.py (1)

18-24: Import list getting long – consider localising PEFT-only imports

The PEFT-specific classes (PeftConfig, PeftModel*, prepare_model_for_kbit_training, …) are now imported at module level.
Because they are only used in a handful of helper methods, moving them into the functions that actually need them (lazy import) keeps the import surface smaller and avoids importing PEFT when the caller never asks for adapter support (pure inference on a base model).
Minor, but it can trim CLI start-up latency and helps with optional-dependency hygiene.

src/axolotl/loaders/patch_manager.py (1)

173-179: Guard-clause good, but feature toggle names diverge from tests

The new helper checks cfg.lora_qkv_kernel and cfg.lora_o_kernel only.
Tests expect cfg.lora_mlp_kernel to be auto-enabled as well; that switch is handled elsewhere but may confuse future readers.

Consider updating the doc-string to reflect that only self-attention kernels (QKV & O) are patched here, whereas MLP kernels are handled later. A tiny clarification now avoids hunting through call-stacks later.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a8af60 and 85ef3bd.

📒 Files selected for processing (3)
  • src/axolotl/loaders/model.py (2 hunks)
  • src/axolotl/loaders/patch_manager.py (3 hunks)
  • tests/e2e/patched/lora_kernels/test_lora_kernel_patching.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/axolotl/loaders/model.py (1)
src/axolotl/utils/schemas/peft.py (1)
  • PeftConfig (17-20)
src/axolotl/loaders/patch_manager.py (2)
src/axolotl/integrations/base.py (2)
  • cfg (317-318)
  • cfg (321-322)
tests/test_exact_deduplication.py (1)
  • cfg (221-235)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: PyTest (3.11, 2.5.1)
  • GitHub Check: PyTest from Source Dist (3.11, 2.7.0)
  • GitHub Check: PyTest from Source Dist (3.11, 2.5.1)
  • GitHub Check: PyTest from Source Dist (3.11, 2.6.0)
  • GitHub Check: PyTest (3.11, 2.6.0)
  • GitHub Check: PyTest (3.11, 2.7.0)
  • GitHub Check: pre-commit
  • GitHub Check: pre-commit
🔇 Additional comments (2)
src/axolotl/loaders/patch_manager.py (2)

60-66: Patch order refactor looks good, but double-check idempotency

_patch_loss_llama() and _apply_self_attention_lora_patch() are now invoked unconditionally during the pre-load phase.
Because both monkey-patch global classes/functions, a second invocation (e.g. loading two models in the same process or running pytest with “-n auto”) could overwrite _original_forward a second time or wrap an already-patched function.

Please ensure each patch helper exits early when it detects the target has already been patched (many of them do, some still don’t).
This keeps multi-model or repeated test runs safe.


236-238: Early return prevents unnecessary work – nice

The new guard short-circuits for non-LLaMA models, avoiding wasted imports.
Looks correct and desirable.

@codecov

codecov Bot commented May 27, 2025

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/axolotl/loaders/patch_manager.py 83.33% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@NanoCode012 NanoCode012 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Was this issue caused from some accidental rebase+merge?

@djsaunde djsaunde merged commit 2962a39 into main May 28, 2025
8 of 9 checks passed
@djsaunde djsaunde deleted the lora-kernels-fix branch May 28, 2025 14:03
@coderabbitai coderabbitai Bot mentioned this pull request Sep 25, 2025
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