Skip to content

Conversation

@gushiqiao
Copy link
Contributor

No description provided.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gushiqiao, 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 focuses on refactoring the LoRA (Low-Rank Adaptation) loading and application mechanism. The core logic for applying LoRA weights has been extracted from the WanLoraWrapper class into a new, dedicated LoRALoader utility. This change aims to enhance code organization, reduce complexity within the WanLoraWrapper, and improve the reusability of the LoRA application functionality across the codebase. Additionally, minor documentation updates were made in related example files to provide clearer guidance.

Highlights

  • Refactored LoRA Application Logic: The detailed implementation for applying LoRA weights, previously embedded within the WanLoraWrapper, has been extracted and moved into a new, dedicated LoRALoader utility class.
  • Improved Modularity: The WanLoraWrapper now delegates the responsibility of applying LoRA weights to the LoRALoader, simplifying its own internal structure and promoting better separation of concerns.
  • Code Cleanup: The internal _apply_lora_weights and remove_lora methods, along with their associated imports (torch, gc), have been removed from WanLoraWrapper as their functionality is now handled by the LoRALoader.
  • Example File Clarifications: Minor comment updates were made in example files (qwen_2511_fp8.py and qwen_2511_with_distill_lora.py) to clarify the possible values for the offload_granularity parameter.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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.

@gushiqiao gushiqiao merged commit 7927554 into main Dec 30, 2025
2 checks passed
@gushiqiao gushiqiao deleted the gsq/fix_lora branch December 30, 2025 07:00
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 refactors the LoRA loading mechanism for WAN models by extracting the logic into a reusable LoRALoader class. This is a positive change for code structure and maintainability. My review focuses on two main points: a potential bug in the application of LoRA scaling factors which could lead to incorrect model behavior, and the removal of functionality for unloading LoRAs, which represents a feature regression. Addressing these points will ensure the refactoring is both correct and functionally complete.

Comment on lines +46 to +51
self.lora_loader.apply_lora(
weight_dict=weight_dict,
lora_weights=lora_weights,
alpha=alpha,
strength=alpha,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The call to self.lora_loader.apply_lora passes the alpha value to both the alpha and strength parameters. Based on the implementation of LoRALoader, this will result in the LoRA weights being scaled by alpha twice (e.g., proportional to alpha^2 for diff-based LoRAs), which is likely not the intended behavior and differs from the original implementation.

The strength parameter seems to be intended for an additional, separate strength multiplier, and it defaults to 1.0. To match the expected behavior of applying the LoRA strength once, you should probably omit the strength parameter in this call.

        self.lora_loader.apply_lora(
            weight_dict=weight_dict,
            lora_weights=lora_weights,
            alpha=alpha,
        )

Comment on lines 52 to -131
self.model._apply_weights(weight_dict)

logger.info(f"Applied LoRA: {lora_name} with alpha={alpha}")
del lora_weights
return True

@torch.no_grad()
def _apply_lora_weights(self, weight_dict, lora_weights, alpha):
lora_pairs = {}
lora_diffs = {}

def try_lora_pair(key, prefix, suffix_a, suffix_b, target_suffix):
if key.endswith(suffix_a):
base_name = key[len(prefix) :].replace(suffix_a, target_suffix)
pair_key = key.replace(suffix_a, suffix_b)
if pair_key in lora_weights:
lora_pairs[base_name] = (key, pair_key)

def try_lora_diff(key, prefix, suffix, target_suffix):
if key.endswith(suffix):
base_name = key[len(prefix) :].replace(suffix, target_suffix)
lora_diffs[base_name] = key

prefixs = [
"", # empty prefix
"diffusion_model.",
]
for prefix in prefixs:
for key in lora_weights.keys():
if not key.startswith(prefix):
continue

try_lora_pair(key, prefix, "lora_A.weight", "lora_B.weight", "weight")
try_lora_pair(key, prefix, "lora_down.weight", "lora_up.weight", "weight")
try_lora_diff(key, prefix, "diff", "weight")
try_lora_diff(key, prefix, "diff_b", "bias")
try_lora_diff(key, prefix, "diff_m", "modulation")

applied_count = 0
for name, param in weight_dict.items():
if name in lora_pairs:
if name not in self.override_dict:
self.override_dict[name] = param.clone().cpu()
name_lora_A, name_lora_B = lora_pairs[name]
lora_A = lora_weights[name_lora_A].to(param.device, param.dtype)
lora_B = lora_weights[name_lora_B].to(param.device, param.dtype)
if param.shape == (lora_B.shape[0], lora_A.shape[1]):
param += torch.matmul(lora_B, lora_A) * alpha
applied_count += 1
elif name in lora_diffs:
if name not in self.override_dict:
self.override_dict[name] = param.clone().cpu()

name_diff = lora_diffs[name]
lora_diff = lora_weights[name_diff].to(param.device, param.dtype)
if param.shape == lora_diff.shape:
param += lora_diff * alpha
applied_count += 1

logger.info(f"Applied {applied_count} LoRA weight adjustments")
if applied_count == 0:
logger.info(
"Warning: No LoRA weights were applied. Expected naming conventions: 'diffusion_model.<layer_name>.lora_A.weight' and 'diffusion_model.<layer_name>.lora_B.weight'. Please verify the LoRA weight file."
)

@torch.no_grad()
def remove_lora(self):
logger.info(f"Removing LoRA ...")

restored_count = 0
for k, v in self.override_dict.items():
self.model.original_weight_dict[k] = v.to(self.model.device)
restored_count += 1

logger.info(f"LoRA removed, restored {restored_count} weights")

self.model._apply_weights(self.model.original_weight_dict)

torch.cuda.empty_cache()
gc.collect()

self.lora_metadata = {}
self.override_dict = {}

def list_loaded_loras(self):
return list(self.lora_metadata.keys())
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This refactoring removes the remove_lora and list_loaded_loras methods. The removal of remove_lora is a significant functionality regression, as it's no longer possible to unload a LoRA after it has been applied.

The underlying mechanism that supported this feature, which involved storing original weights in self.override_dict, has also been removed from the LoRA application logic. As a result, the self.override_dict attribute in WanLoraWrapper is now unused.

If the ability to remove LoRAs is a required feature, this functionality needs to be reinstated. If it's intentionally being removed, the now-dead code (self.override_dict) should also be removed from the __init__ method for clarity.

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.

3 participants