Skip to content

vllm.model_executor.model_loader.reload.sanitize

Functions:

  • restore_layer_refs

    Restores references to layer held by tensor attributes.

  • sanitize_layer_refs

    Removes references to layer held by tensor attributes. Specifically, removes the

restore_layer_refs(tensor, layer)

Restores references to layer held by tensor attributes.

Used by restore_layer_on_meta to add back layer references, allowing for proper weight loading.

Parameters:

  • tensor

    (Tensor) –

    tensor to be sanitized

  • layer

    (Module) –

    layer whose references should be removed

Returns:

Source code in vllm/model_executor/model_loader/reload/sanitize.py
def restore_layer_refs(tensor: torch.Tensor, layer: torch.nn.Module) -> torch.Tensor:
    """
    Restores references to layer held by tensor attributes.

    Used by `restore_layer_on_meta` to add back layer references, allowing for proper
    weight loading.

    Args:
        tensor: tensor to be sanitized
        layer: layer whose references should be removed

    Returns:
        sanitized tensor
    """
    for key, value in tensor.__dict__.items():
        if isinstance(value, MethodType) and value.__self__ is layer_ref_sentinel:
            tensor.__dict__[key] = value.__func__.__get__(layer)

    return tensor

sanitize_layer_refs(tensor, layer)

Removes references to layer held by tensor attributes. Specifically, removes the __self__ attribute of weight loader methods attached to the tensor.

Used by capture_layer_to_meta to avoid circular references to layers in LAYERWISE_INFO, leading to modules never being cleaned up. Without sanitation, tensors will reference layers, and the WeakKeyDictionary will never evict entries, even when the model is deleted.

Parameters:

  • tensor

    (Tensor) –

    tensor to be sanitized

  • layer

    (Module) –

    layer whose references should be removed

Returns:

Source code in vllm/model_executor/model_loader/reload/sanitize.py
def sanitize_layer_refs(tensor: torch.Tensor, layer: torch.nn.Module) -> torch.Tensor:
    """
    Removes references to layer held by tensor attributes. Specifically, removes the
    `__self__` attribute of weight loader methods attached to the tensor.

    Used by `capture_layer_to_meta` to avoid circular references to layers in
    `LAYERWISE_INFO`, leading to modules never being cleaned up. Without sanitation,
    tensors will reference layers, and the WeakKeyDictionary will never evict entries,
    even when the model is deleted.

    Args:
        tensor: tensor to be sanitized
        layer: layer whose references should be removed

    Returns:
        sanitized tensor
    """
    for key, value in tensor.__dict__.items():
        if isinstance(value, MethodType) and value.__self__ is layer:
            tensor.__dict__[key] = value.__func__.__get__(layer_ref_sentinel)

    return tensor