[Bugfix] LoRA for DeepSeek V3.2 (#35077)
Signed-off-by: Hollow Man <hollowman@opensuse.org> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: Jee Jee Li <pandaleefree@gmail.com>
This commit is contained in:
co-authored by
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Jee Jee Li
parent
04eac6ba24
commit
a250f1bd5f
@@ -203,7 +203,16 @@ class BaseLinearLayerWithLoRA(BaseLayerWithLoRA):
|
||||
self, x: torch.Tensor, bias: torch.Tensor | None = None
|
||||
) -> torch.Tensor:
|
||||
output = self.base_layer.quant_method.apply(self.base_layer, x, bias)
|
||||
return self._apply_lora_to_output(x, output)
|
||||
|
||||
def _apply_base_forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
base_output = self.base_layer(x)
|
||||
output = base_output[0] if isinstance(base_output, tuple) else base_output
|
||||
return self._apply_lora_to_output(x, output)
|
||||
|
||||
def _apply_lora_to_output(
|
||||
self, x: torch.Tensor, output: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
original_shape = output.shape if output.ndim == 3 else None
|
||||
|
||||
# In transformers backend, x and output have extra batch dimension like
|
||||
|
||||
@@ -40,11 +40,19 @@ def _mcp_apply(x, bias, layer: "ColumnParallelLinearWithLoRA"):
|
||||
|
||||
# Since communication is needed, the buffer is directly initialized as a
|
||||
# tensor rather than a tuple of tensor.
|
||||
buffers = torch.zeros(
|
||||
(layer.n_slices, x.shape[0], layer.lora_a_stacked[0].shape[2]),
|
||||
local_lora_rank = layer.lora_a_stacked[0].shape[2]
|
||||
buffer_shape = (layer.n_slices, x.shape[0], local_lora_rank)
|
||||
# Under torch.compile, the local-rank-1 fully-sharded path can otherwise
|
||||
# get lowered to a reinterpret view with a non-canonical layout. The
|
||||
# Triton shrink op mutates this buffer in place and expects the standard
|
||||
# contiguous [slice, token, rank] stride contract.
|
||||
buffers = torch.empty_strided(
|
||||
buffer_shape,
|
||||
(x.shape[0] * local_lora_rank, local_lora_rank, 1),
|
||||
dtype=torch.float32,
|
||||
device=x.device,
|
||||
)
|
||||
buffers.zero_()
|
||||
|
||||
shrunk_buffers: torch.Tensor | None = layer.punica_wrapper.add_shrink(
|
||||
buffers, x, layer.lora_a_stacked, 1.0
|
||||
@@ -86,7 +94,7 @@ class ColumnParallelLinearWithLoRA(BaseLinearLayerWithLoRA):
|
||||
# The base_layer type is ColumnParallelLinear or
|
||||
# MergedColumnParallelLinear, their weight sharding logic is
|
||||
# inconsistent when TP is greater than 1.
|
||||
self.is_merged_col_linear = type(base_layer) is MergedColumnParallelLinear
|
||||
self.is_merged_col_linear = isinstance(base_layer, MergedColumnParallelLinear)
|
||||
self.output_size = self.base_layer.output_size_per_partition
|
||||
# There is only one LoRA layer
|
||||
self.n_slices = 1
|
||||
@@ -158,7 +166,7 @@ class ColumnParallelLinearWithLoRA(BaseLinearLayerWithLoRA):
|
||||
) -> bool:
|
||||
if type(source_layer) is maybe_get_oot_by_class(ColumnParallelLinear):
|
||||
return True
|
||||
if type(source_layer) is maybe_get_oot_by_class(MergedColumnParallelLinear):
|
||||
if isinstance(source_layer, maybe_get_oot_by_class(MergedColumnParallelLinear)):
|
||||
if len(packed_modules_list) != 1:
|
||||
return False
|
||||
# Exclude layers with 3+ output sizes - those are handled by
|
||||
@@ -275,19 +283,41 @@ class MergedColumnParallelLinearWithLoRA(ColumnParallelLinearWithLoRA):
|
||||
index, 0, : lora_b_i.shape[0], : lora_b_i.shape[1]
|
||||
].copy_(lora_b_i, non_blocking=True)
|
||||
|
||||
def apply(self, x: torch.Tensor, bias: torch.Tensor | None = None) -> torch.Tensor:
|
||||
merged_cls = maybe_get_oot_by_class(MergedColumnParallelLinear)
|
||||
# Effectively unsharded subclasses can safely reuse their custom
|
||||
# forward() implementation before applying the LoRA delta.
|
||||
if (
|
||||
self.tp_size == 1
|
||||
and type(self.base_layer) is not merged_cls
|
||||
and type(self.base_layer).forward is not merged_cls.forward
|
||||
):
|
||||
return self._apply_base_forward(x)
|
||||
return _mcp_apply(x, bias, self)
|
||||
|
||||
@classmethod
|
||||
@_not_fully_sharded_can_replace
|
||||
def can_replace_layer(
|
||||
cls,
|
||||
source_layer: nn.Module,
|
||||
lora_config: LoRAConfig,
|
||||
packed_modules_list: list,
|
||||
model_config: PretrainedConfig | None = None,
|
||||
decorate: bool = True,
|
||||
) -> bool:
|
||||
return (
|
||||
type(source_layer) is MergedColumnParallelLinear
|
||||
and len(packed_modules_list) == 2
|
||||
)
|
||||
merged_cls = maybe_get_oot_by_class(MergedColumnParallelLinear)
|
||||
if not isinstance(source_layer, merged_cls) or len(packed_modules_list) != 2:
|
||||
return False
|
||||
|
||||
tp_size = getattr(source_layer, "tp_size", 1)
|
||||
if type(source_layer) is merged_cls:
|
||||
if not decorate:
|
||||
return True
|
||||
return not lora_config.fully_sharded_loras or tp_size == 1
|
||||
|
||||
# Only support effectively unsharded subclasses here. Sharded
|
||||
# subclasses may have custom communication semantics that the generic
|
||||
# merged-column LoRA path does not know how to preserve.
|
||||
return tp_size == 1
|
||||
|
||||
|
||||
class QKVParallelLinearWithLoRA(ColumnParallelLinearWithLoRA):
|
||||
@@ -607,7 +637,9 @@ class MergedColumnParallelLinearVariableSliceWithLoRA(
|
||||
) -> bool:
|
||||
# Support MergedColumnParallelLinear with 3 or more slices
|
||||
# (2 slices are handled by MergedColumnParallelLinearWithLoRA)
|
||||
if type(source_layer) is not maybe_get_oot_by_class(MergedColumnParallelLinear):
|
||||
if not isinstance(
|
||||
source_layer, maybe_get_oot_by_class(MergedColumnParallelLinear)
|
||||
):
|
||||
return False
|
||||
|
||||
# If packed_modules_list has 3+ items, use this class
|
||||
|
||||
@@ -46,6 +46,12 @@ class ReplicatedLinearWithLoRA(BaseLinearLayerWithLoRA):
|
||||
|
||||
return output, output_bias
|
||||
|
||||
def apply(self, x: torch.Tensor, bias: torch.Tensor | None = None) -> torch.Tensor:
|
||||
# ReplicatedLinear subclasses such as GateLinear override forward() to
|
||||
# dispatch custom kernels and/or adjust the output dtype. Apply LoRA on
|
||||
# top of the actual base-layer output instead of bypassing that path.
|
||||
return self._apply_base_forward(x)
|
||||
|
||||
# ReplicatedLinear should always be replaced, regardless of the fully
|
||||
# sharded LoRAs setting, because it is, by definition, copied per GPU.
|
||||
@classmethod
|
||||
@@ -56,7 +62,7 @@ class ReplicatedLinearWithLoRA(BaseLinearLayerWithLoRA):
|
||||
packed_modules_list: list,
|
||||
model_config: PretrainedConfig | None = None,
|
||||
) -> bool:
|
||||
return type(source_layer) is maybe_get_oot_by_class(ReplicatedLinear)
|
||||
return isinstance(source_layer, maybe_get_oot_by_class(ReplicatedLinear))
|
||||
|
||||
def slice_lora_a(
|
||||
self, lora_a: torch.Tensor | list[torch.Tensor | None]
|
||||
|
||||
@@ -437,12 +437,21 @@ class LoRAModelManager:
|
||||
),
|
||||
)
|
||||
|
||||
# In some models, especially multimodal ones, layers with the same
|
||||
# name may have different types, such as nn.Linear and
|
||||
# ReplicatedLinear. The nn.Linear layers cannot be replaced with
|
||||
# LoRA layers, leading to assertion error. The following check
|
||||
# aims to prevent this error
|
||||
if self.supports_mm and not isinstance(new_module, BaseLayerWithLoRA):
|
||||
# Some matched modules can be unsupported by LoRA wrappers
|
||||
# (e.g. subclasses with specialized forward behavior).
|
||||
if not isinstance(new_module, BaseLayerWithLoRA):
|
||||
error_msg = (
|
||||
"LoRA target module "
|
||||
f"{module_name} ({type(module).__name__}) matched the "
|
||||
"deployment configuration but could not be wrapped by any "
|
||||
"LoRA layer implementation."
|
||||
)
|
||||
if self.lora_config.target_modules is not None:
|
||||
raise ValueError(
|
||||
f"{error_msg} target_modules="
|
||||
f"{sorted(self.lora_config.target_modules)}"
|
||||
)
|
||||
logger.warning_once("%s It will be ignored.", error_msg)
|
||||
continue
|
||||
self.register_module(module_name, new_module)
|
||||
|
||||
@@ -578,6 +587,38 @@ class LoRAModelManager:
|
||||
model.loras[module_name] = lora
|
||||
return model
|
||||
|
||||
def get_dummy_lora_warmup_rank(self, default_rank: int) -> int:
|
||||
"""Return a dummy LoRA rank compatible with wrapped modules.
|
||||
|
||||
Dummy LoRAs keep warmup memory low by using a small rank. Fully
|
||||
sharded MoE wrappers additionally require the dummy rank to be divisible
|
||||
by tensor parallel size because they shard W13 along the rank axis.
|
||||
"""
|
||||
if not self.lora_config.fully_sharded_loras:
|
||||
return default_rank
|
||||
|
||||
required_multiple = 1
|
||||
for module in self.modules.values():
|
||||
if not getattr(module, "fully_sharded", False):
|
||||
continue
|
||||
required_multiple = math.lcm(required_multiple, module.tp_size)
|
||||
|
||||
if required_multiple == 1 or default_rank % required_multiple == 0:
|
||||
return default_rank
|
||||
|
||||
adjusted_rank = (
|
||||
(default_rank + required_multiple - 1) // required_multiple
|
||||
) * required_multiple
|
||||
if adjusted_rank > self.lora_config.max_lora_rank:
|
||||
raise ValueError(
|
||||
"Unable to choose a dummy LoRA warmup rank compatible with "
|
||||
"fully sharded MoE modules: "
|
||||
f"default_rank={default_rank}, "
|
||||
f"required_multiple={required_multiple}, "
|
||||
f"max_lora_rank={self.lora_config.max_lora_rank}"
|
||||
)
|
||||
return adjusted_rank
|
||||
|
||||
def _match_target_modules(self, module_name: str) -> bool:
|
||||
"""Check if a module should have LoRA applied.
|
||||
|
||||
@@ -594,7 +635,11 @@ class LoRAModelManager:
|
||||
"""
|
||||
if not is_supported_lora_module(module_name, self.supported_lora_modules):
|
||||
return False
|
||||
return is_in_target_modules(module_name, self.lora_config.target_modules)
|
||||
return is_in_target_modules(
|
||||
module_name,
|
||||
self.lora_config.target_modules,
|
||||
self.packed_modules_mapping,
|
||||
)
|
||||
|
||||
def _get_punica_wrapper(self, module_name: str) -> PunicaWrapperBase | None:
|
||||
"""
|
||||
|
||||
+25
-3
@@ -73,7 +73,9 @@ def get_lora_id():
|
||||
return _GLOBAL_LORA_ID
|
||||
|
||||
|
||||
_all_lora_classes: set[type[BaseLayerWithLoRA]] = {
|
||||
# Order matters here: more specific wrappers must be checked before generic
|
||||
# merged/column-parallel wrappers in from_layer().
|
||||
_all_lora_classes: tuple[type[BaseLayerWithLoRA], ...] = (
|
||||
VocabParallelEmbeddingWithLoRA,
|
||||
ColumnParallelLinearWithLoRA,
|
||||
MergedColumnParallelLinearWithLoRA,
|
||||
@@ -90,7 +92,7 @@ _all_lora_classes: set[type[BaseLayerWithLoRA]] = {
|
||||
RowParallelLinearWithShardedLoRA,
|
||||
FusedMoEWithLoRA,
|
||||
FusedMoE3DWithLoRA,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def is_moe_model(model: nn.Module) -> bool:
|
||||
@@ -258,6 +260,7 @@ def is_supported_lora_module(
|
||||
def is_in_target_modules(
|
||||
module_name: str,
|
||||
target_modules: list[str] | None,
|
||||
packed_modules_mapping: dict[str, list[str]] | None = None,
|
||||
) -> bool:
|
||||
"""Check if a module passes the deployment-time target_modules filter.
|
||||
|
||||
@@ -268,14 +271,33 @@ def is_in_target_modules(
|
||||
module_name: Full dot-separated module name.
|
||||
target_modules: Optional deployment-time restriction list from
|
||||
LoRAConfig.target_modules.
|
||||
packed_modules_mapping: Optional model-defined mapping from packed
|
||||
runtime module names to their adapter-visible submodule names
|
||||
(e.g. ``{"gate_up_proj": ["gate_proj", "up_proj"]}``).
|
||||
|
||||
Returns:
|
||||
True if the module passes the filter, False otherwise.
|
||||
"""
|
||||
if target_modules is None:
|
||||
return True
|
||||
target_module_set = set(target_modules)
|
||||
module_suffix = module_name.split(".")[-1]
|
||||
return module_suffix in set(target_modules)
|
||||
if module_suffix in target_module_set or module_name in target_module_set:
|
||||
return True
|
||||
|
||||
if not packed_modules_mapping:
|
||||
return False
|
||||
|
||||
# Runtime packed parent matched by deployment-time child targets.
|
||||
packed_children = packed_modules_mapping.get(module_suffix)
|
||||
if packed_children and any(child in target_module_set for child in packed_children):
|
||||
return True
|
||||
|
||||
# Adapter-visible packed child matched by deployment-time parent target.
|
||||
return any(
|
||||
module_suffix in children and packed_parent in target_module_set
|
||||
for packed_parent, children in packed_modules_mapping.items()
|
||||
)
|
||||
|
||||
|
||||
def get_adapter_absolute_path(lora_path: str) -> str:
|
||||
|
||||
@@ -160,7 +160,11 @@ class WorkerLoRAManager:
|
||||
lora_request.lora_path,
|
||||
", ".join(sorted(expected_lora_modules_lst)),
|
||||
)
|
||||
elif not is_in_target_modules(module_name, target_modules):
|
||||
elif not is_in_target_modules(
|
||||
module_name,
|
||||
target_modules,
|
||||
packed_modules_mapping,
|
||||
):
|
||||
logger.warning_once(
|
||||
"LoRA module '%s' in adapter '%s' is not in the "
|
||||
"deployment-time target_modules restriction [%s]."
|
||||
@@ -197,6 +201,9 @@ class WorkerLoRAManager:
|
||||
self._cached_dummy_lora = dummy_lora
|
||||
return self._adapter_manager.add_adapter(dummy_lora)
|
||||
|
||||
def get_dummy_lora_warmup_rank(self, default_rank: int) -> int:
|
||||
return self._adapter_manager.get_dummy_lora_warmup_rank(default_rank)
|
||||
|
||||
def pin_adapter(self, adapter_id: int) -> bool:
|
||||
return self._adapter_manager.pin_adapter(adapter_id)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user