Skip to content

Fix _get_vllm_state_dict for LFM2 models#531

Open
danielhanchen wants to merge 1 commit intomainfrom
fix/lfm2-vllm-state-dict
Open

Fix _get_vllm_state_dict for LFM2 models#531
danielhanchen wants to merge 1 commit intomainfrom
fix/lfm2-vllm-state-dict

Conversation

@danielhanchen
Copy link
Copy Markdown
Contributor

Summary

  • Add full LFM2 support to _get_vllm_state_dict and convert_vllm_to_huggingface
  • LFM2 is a hybrid architecture (alternating attention + conv layers) with different naming conventions than standard transformer models. Previously, the layer loop would crash with UnboundLocalError on layers that lack self_attn (conv layers). Even with else: continue, all conv layer weights would be silently dropped, producing a broken model.
  • Also fix set_additional_modules and get_model_layer_config in empty_model.py so the empty HF model is created with the correct layer names and norm attribute for LFM2

What changed

vllm_utils.py -- _get_vllm_state_dict:

  • Detect LFM2 via model_type == "lfm2" and branch into dedicated extraction logic
  • Handle attention layers with out_proj (LFM2 uses out_proj, not o_proj), plus q_layernorm / k_layernorm
  • Handle conv layers via short_conv (in_proj, out_proj, conv)
  • Handle feed_forward via w1/w2/w3 (LFM2 uses feed_forward, not mlp)
  • Handle layer norms: operator_norm, ffn_norm
  • Fix final norm to use embedding_norm for LFM2 (standard models use norm)
  • Add else: continue for the non-LFM2 path to prevent UnboundLocalError on layers without self_attn or cross_attn

vllm_utils.py -- convert_vllm_to_huggingface:

  • Add LFM2 norm names (operator_norm, ffn_norm, q_layernorm, k_layernorm) to layernorm_names
  • Add Conv1d (3D weight) handling branch for conv.conv weights

empty_model.py:

  • Add LFM2 layer names to standard_layers in get_model_layer_config
  • Add LFM2 norm names to layernorms in get_model_layer_config
  • Fix set_additional_modules to use embedding_norm for LFM2

Test plan

  • LiquidAI/LFM2.5-1.2B-Thinking with fast_inference=True, load_in_16bit=True -- loads and generates correctly
  • Regression: unsloth/Llama-3.2-1B-Instruct with fast_inference=True -- still works
  • Regression: unsloth/Qwen2.5-0.5B-Instruct with fast_inference=True -- still works
  • Backwards compatible: is_lfm2 is always False for non-LFM2 models, so the original code path is unchanged

LFM2 is a hybrid architecture with alternating attention and conv layers
that uses different naming conventions than standard transformer models.
Previously, _get_vllm_state_dict would crash with UnboundLocalError on
layers without self_attn (conv layers), and even if that was patched with
else:continue, all conv layer weights would be silently dropped.

Changes in vllm_utils.py:
- Add is_lfm2 detection based on model_type
- Add LFM2 branch in _get_vllm_state_dict layer loop that handles:
  - Attention layers with out_proj (not o_proj), q_layernorm, k_layernorm
  - Conv layers via short_conv (in_proj, out_proj, conv)
  - Feed forward via feed_forward.w1/w2/w3 (not mlp.gate_up_proj)
  - Layer norms: operator_norm, ffn_norm
- Add else:continue for non-LFM2 path to prevent UnboundLocalError on
  layers without self_attn or cross_attn
- Fix final norm extraction to use embedding_norm for LFM2
- Add LFM2 norm names to layernorm_names in convert_vllm_to_huggingface
- Add Conv1d (3D weight) handling for LFM2 conv.conv weights

Changes in empty_model.py:
- Add LFM2 layer names to standard_layers in get_model_layer_config
- Add LFM2 norm names to layernorms in get_model_layer_config
- Fix set_additional_modules to use embedding_norm for LFM2

Tested with LiquidAI/LFM2.5-1.2B-Thinking (16-bit, fast_inference=True).
Regression tested with Llama-3.2-1B, Gemma-3-1b, Qwen2.5-0.5B, Phi-4-mini.
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 introduces full compatibility for LFM2 models within the vLLM state dictionary extraction and Hugging Face conversion utilities. LFM2 models, characterized by their unique hybrid architecture combining attention and convolutional layers, required specialized handling due to different naming conventions and layer structures. The changes ensure that all LFM2-specific components, including attention, convolutional, and feed-forward layers, along with their associated normalization layers, are correctly identified, extracted, and converted, preventing previous errors and ensuring functional model conversion.

Highlights

  • LFM2 Model Support: Added comprehensive support for LFM2 models in _get_vllm_state_dict and convert_vllm_to_huggingface to correctly handle their unique hybrid architecture.
  • Error Resolution: Resolved UnboundLocalError and silent weight dropping issues that occurred when processing LFM2's alternating attention and convolutional layers.
  • Empty Model Configuration: Updated empty_model.py to correctly configure LFM2 layer names and norm attributes, ensuring proper creation of empty Hugging Face models.
Changelog
  • unsloth_zoo/empty_model.py
    • Modified set_additional_modules to dynamically select the final normalization attribute (embedding_norm for LFM2, norm otherwise) based on the model type.
    • Expanded get_model_layer_config to include LFM2-specific layer patterns for attention (self_attn.out_proj, q_layernorm, k_layernorm), convolutional (conv.in_proj, conv.out_proj, conv.conv), and feed-forward (feed_forward.w1, w2, w3) modules.
    • Added LFM2-specific normalization layer names (operator_norm, ffn_norm, q_layernorm, k_layernorm) to the layernorms configuration.
  • unsloth_zoo/vllm_utils.py
    • Introduced LFM2 model type detection to enable a dedicated state dictionary extraction path within _get_vllm_state_dict.
    • Implemented specific logic for LFM2 attention layers, handling out_proj instead of o_proj and extracting q_layernorm and k_layernorm.
    • Added extraction logic for LFM2 convolutional layers, including short_conv, in_proj, out_proj, and conv weights.
    • Updated feed-forward layer extraction for LFM2 to use w1, w2, and w3 naming conventions.
    • Included extraction for LFM2-specific layer norms: operator_norm and ffn_norm.
    • Ensured the final model norm is correctly identified as embedding_norm for LFM2 models during state dict extraction.
    • Added a continue statement for non-LFM2 paths to gracefully skip layers without self_attn or cross_attn, preventing UnboundLocalError.
    • Extended convert_vllm_to_huggingface to recognize LFM2-specific norm names (operator_norm, ffn_norm, q_layernorm, k_layernorm).
    • Added a new branch in convert_vllm_to_huggingface to handle 3D weights for Conv1d layers, specifically for LFM2's conv.conv modules.
Activity
  • No specific activity (comments, reviews, or progress updates) has been recorded for this pull request yet.
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.

get_state_dict(f"{prefix}.v_proj", 2, state_dict, qkv_proj)
elif hasattr(layer, "cross_attn"):
prefix = f"{vllm_text_model_prefix}.layers.{kk}.cross_attn"
qkv_proj = layer.cross_attn.qkv_proj

elif weight.ndim == 3:
# Conv1d weights (e.g. LFM2 conv.conv) - set directly on existing module
weight_param = torch.nn.Parameter(getattr(weight, 'data', weight), requires_grad=False)
Copy link
Copy Markdown
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 adds comprehensive support for LFM2 models within the vLLM utilities, addressing their unique architecture and naming conventions. The changes in empty_model.py and vllm_utils.py appear correct and well-thought-out for handling LFM2-specific layers and norms. I have two suggestions to enhance the code quality: one focuses on refactoring a complex loop for better maintainability, and the other addresses the use of exec, proposing a safer alternative.

Comment on lines +1455 to +1464
elif weight.ndim == 3:
# Conv1d weights (e.g. LFM2 conv.conv) - set directly on existing module
weight_param = torch.nn.Parameter(getattr(weight, 'data', weight), requires_grad=False)
layer_name_br = re.sub(r"\.([\d]{1,})\.", r"[\1].", layer_name)
exec(f"new_model.{layer_name_br}.weight = None")
exec(f"new_model.{layer_name_br}.weight = weight_param")
if bias is not None:
exec(f"new_model.{layer_name_br}.bias = None")
exec(f"new_model.{layer_name_br}.bias = bias")
continue
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.

high

Using exec() is generally discouraged due to security risks and reduced code clarity, and this pattern appears multiple times in the function. It would be safer and more maintainable to replace exec() with a helper function that uses getattr() and setattr() to navigate the model structure and assign the weights. For example, you could write a helper to parse the layer_name_br string, retrieve the target module, and then set its weight and bias attributes directly.

Comment on lines +1098 to 1199
if is_lfm2:
layer_prefix = f"{vllm_text_model_prefix}.layers.{kk}"

# Handle attention or conv sublayers
if hasattr(layer, "self_attn"):
prefix = f"{layer_prefix}.self_attn"
qkv_proj = layer.self_attn.qkv_proj
get_state_dict(f"{prefix}.q_proj", 0, state_dict, qkv_proj)
get_state_dict(f"{prefix}.k_proj", 1, state_dict, qkv_proj)
get_state_dict(f"{prefix}.v_proj", 2, state_dict, qkv_proj)
elif hasattr(layer, "cross_attn"):
prefix = f"{vllm_text_model_prefix}.layers.{kk}.cross_attn"
qkv_proj = layer.cross_attn.qkv_proj
o_proj = layer.cross_attn.o_proj
name = re.sub(r"\.(\d+)\.", r"[\1].", prefix.replace('model.language_model','language_model.model', 1) + ".qkv_proj")
cross_attn_layer = eval(f'vllm_internals.{name}')
q_proj = cross_attn_layer.proj['q_proj_decoder']
kv_proj = cross_attn_layer.proj['kv_proj_encoder']
get_state_dict(f"{prefix}.q_proj", 0, state_dict, q_proj)
get_state_dict(f"{prefix}.k_proj", 1, state_dict, kv_proj)
get_state_dict(f"{prefix}.v_proj", 2, state_dict, kv_proj)

get_state_dict(f"{prefix}.o_proj", 0, state_dict, o_proj)

proj = layer.mlp.gate_up_proj
use_fused_gate_up = _is_fused_module("gate_up_proj")
if use_fused_gate_up:
# For some model types like phi3 vllm will expect fused gate_up_proj (e.g. Phi3, Phi3.5-mini-instruct, Phi4-mini-instruct)
# so we should not split them here otherwise there will be a size mismatch when activating the adapter
# see https://github.com/vllm-project/vllm/blob/9b693d023cf595e60b5346fdeeb41cf2a6eda838/vllm/model_executor/models/phi3.py
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.gate_up_proj", 0, state_dict, proj, slice_weights=False)
# LFM2 uses out_proj, not o_proj
out_proj = layer.self_attn.out_proj
get_state_dict(f"{prefix}.out_proj", 0, state_dict, out_proj)
# Attention-specific norms
for norm_name in ("q_layernorm", "k_layernorm"):
norm_module = getattr(layer.self_attn, norm_name, None)
if norm_module is not None:
norm_key = f"{prefix}.{norm_name}.weight"
state_dict[norm_key] = norm_module.weight.data
quant_state_dict[norm_key] = state_dict[norm_key]
elif hasattr(layer, "short_conv"):
# Conv layers
conv = layer.short_conv
get_state_dict(f"{layer_prefix}.conv.in_proj", 0, state_dict, conv.in_proj, slice_weights=False)
get_state_dict(f"{layer_prefix}.conv.out_proj", 0, state_dict, conv.out_proj, slice_weights=False)
get_state_dict(f"{layer_prefix}.conv.conv", 0, state_dict, conv.conv, slice_weights=False)
else:
continue

# Feed forward (both attention and conv layers have feed_forward)
ff = layer.feed_forward
# w1 is fused (w1 + w3 in HF) -- shard 0 = w1, shard 1 = w3
get_state_dict(f"{layer_prefix}.feed_forward.w1", 0, state_dict, ff.w1)
get_state_dict(f"{layer_prefix}.feed_forward.w3", 1, state_dict, ff.w1)
get_state_dict(f"{layer_prefix}.feed_forward.w2", 0, state_dict, ff.w2, slice_weights=False)

# Layer norms
for norm_name in ("operator_norm", "ffn_norm"):
norm_module = getattr(layer, norm_name, None)
if norm_module is not None:
norm_key = f"{layer_prefix}.{norm_name}.weight"
state_dict[norm_key] = norm_module.weight.data
quant_state_dict[norm_key] = state_dict[norm_key]
else:
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.gate_proj", 0, state_dict, proj)
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.up_proj", 1, state_dict, proj)
if hasattr(layer, "self_attn"):
prefix = f"{vllm_text_model_prefix}.layers.{kk}.self_attn"
qkv_proj = layer.self_attn.qkv_proj
o_proj = layer.self_attn.o_proj

use_fused_qkv = _is_fused_module("qkv_proj")
if use_fused_qkv:
# For some model types like phi3 vllm will expect fused qkv (e.g. Phi3, Phi3.5-mini-instruct, Phi4-mini-instruct)
# so we should not split them here otherwise there will be a size mismatch when activating the adapter
# see https://github.com/vllm-project/vllm/blob/9b693d023cf595e60b5346fdeeb41cf2a6eda838/vllm/model_executor/models/phi3.py
get_state_dict(f"{prefix}.qkv_proj", 0, state_dict, qkv_proj, slice_weights=False)
else:
get_state_dict(f"{prefix}.q_proj", 0, state_dict, qkv_proj)
get_state_dict(f"{prefix}.k_proj", 1, state_dict, qkv_proj)
get_state_dict(f"{prefix}.v_proj", 2, state_dict, qkv_proj)
elif hasattr(layer, "cross_attn"):
prefix = f"{vllm_text_model_prefix}.layers.{kk}.cross_attn"
qkv_proj = layer.cross_attn.qkv_proj
o_proj = layer.cross_attn.o_proj
name = re.sub(r"\.(\d+)\.", r"[\1].", prefix.replace('model.language_model','language_model.model', 1) + ".qkv_proj")
cross_attn_layer = eval(f'vllm_internals.{name}')
q_proj = cross_attn_layer.proj['q_proj_decoder']
kv_proj = cross_attn_layer.proj['kv_proj_encoder']
get_state_dict(f"{prefix}.q_proj", 0, state_dict, q_proj)
get_state_dict(f"{prefix}.k_proj", 1, state_dict, kv_proj)
get_state_dict(f"{prefix}.v_proj", 2, state_dict, kv_proj)
else:
continue

proj = layer.mlp.down_proj
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.down_proj", 0, state_dict, proj)
get_state_dict(f"{prefix}.o_proj", 0, state_dict, o_proj)

# Use layernorms from the layer configuration
layernorm_names = [name.format(kk=kk) for name in layer_config['layernorms']]
proj = layer.mlp.gate_up_proj
use_fused_gate_up = _is_fused_module("gate_up_proj")
if use_fused_gate_up:
# For some model types like phi3 vllm will expect fused gate_up_proj (e.g. Phi3, Phi3.5-mini-instruct, Phi4-mini-instruct)
# so we should not split them here otherwise there will be a size mismatch when activating the adapter
# see https://github.com/vllm-project/vllm/blob/9b693d023cf595e60b5346fdeeb41cf2a6eda838/vllm/model_executor/models/phi3.py
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.gate_up_proj", 0, state_dict, proj, slice_weights=False)
else:
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.gate_proj", 0, state_dict, proj)
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.up_proj", 1, state_dict, proj)

for layernorm_name in layernorm_names:
vllm_name = layernorm_name.replace(f".{kk}.", f"[{kk}].").replace(vllm_text_model_prefix, "vllm_text_model")
try:
layernorm = eval(vllm_name).state_dict()["weight"]
layernorm_name = f"{layernorm_name}.weight"
state_dict[layernorm_name] = layernorm
quant_state_dict[layernorm_name] = state_dict[layernorm_name]
except Exception as e:
skipped_layernorms.append(layernorm_name.split(".")[-1])
proj = layer.mlp.down_proj
get_state_dict(f"{vllm_text_model_prefix}.layers.{kk}.mlp.down_proj", 0, state_dict, proj)

# Use layernorms from the layer configuration
layernorm_names = [name.format(kk=kk) for name in layer_config['layernorms']]

for layernorm_name in layernorm_names:
vllm_name = layernorm_name.replace(f".{kk}.", f"[{kk}].").replace(vllm_text_model_prefix, "vllm_text_model")
try:
layernorm = eval(vllm_name).state_dict()["weight"]
layernorm_name = f"{layernorm_name}.weight"
state_dict[layernorm_name] = layernorm
quant_state_dict[layernorm_name] = state_dict[layernorm_name]
except Exception as e:
skipped_layernorms.append(layernorm_name.split(".")[-1])
pass
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.

medium

The logic inside this loop has become quite complex with the large if is_lfm2: ... else: ... block. To improve readability and maintainability, consider refactoring the logic for LFM2 and non-LFM2 models into separate helper functions. This would make the main loop in _get_vllm_state_dict much cleaner and easier to follow.

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.

1 participant