Patch to fix the embedding layer slowness on Qwen3VL when processing images or videos

If you are also facing embedding layer slowness on Qwen3VL running on PyTorch 2.9.0

I implemented this patch before loading the model:

# ══════════════════════════════════════════════════════════════════════════════
# Patch to make shortten time to first token (ttft)
# ══════════════════════════════════════════════════════════════════════════════

### PASTE:
import types
def _fast_patch_embed(model):
    """PyTorch 2.9.0 runs this Conv3d slowly in fp16. kernel == stride, so it is a matrix multiply."""
    pe = model.model.visual.patch_embed
    def forward(self, hidden_states):
        w = self.proj.weight
        x = hidden_states.reshape(-1, w[0].numel()).to(w.dtype)
        return torch.nn.functional.linear(x, w.reshape(w.shape[0], -1), self.proj.bias)
    pe.forward = types.MethodType(forward, pe)
###

# ══════════════════════════════════════════════════════════════════════════════
# load(): put the model and its processor on the GPU, once
# ══════════════════════════════════════════════════════════════════════════════
def load(max_vision_tokens: int = 8192):

Result: time to first token (Embedding phase) from ~150 s to 2.19 s.

More here: Cosmos-Reason-2-Speed-Blocker/README.md at main · marcelpatrick/Cosmos-Reason-2-Speed-Blocker · GitHub

1 Like