Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

2.0 KB
Raw Blame
# Initially pulled from https://github.com/black-forest-labs/flux

import torch
from torch import Tensor, nn
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast

from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device


class HFEncoder(nn.Module):
    def __init__(
        self,
        encoder: PreTrainedModel,
        tokenizer: PreTrainedTokenizer | PreTrainedTokenizerFast,
        is_clip: bool,
        max_length: int,
        device: torch.device | None = None,
    ):
        super().__init__()
        self.max_length = max_length
        self.is_clip = is_clip
        self.output_key = "pooler_output" if self.is_clip else "last_hidden_state"
        self.tokenizer = tokenizer
        self.hf_module = encoder
        self.hf_module = self.hf_module.eval().requires_grad_(False)
        # The intended compute device for the encoder. Prefer passing this explicitly (e.g. the loaded model's
        # compute_device): with partial loading, inferring the device from current parameter residency can wrongly
        # return CPU when all weights are temporarily offloaded to RAM, running the whole encode on the CPU (#9373).
        self.device = device

    def forward(self, text: list[str]) -> Tensor:
        batch_encoding = self.tokenizer(
            text,
            truncation=True,
            max_length=self.max_length,
            return_length=False,
            return_overflowing_tokens=False,
            padding="max_length",
            return_tensors="pt",
        )

        # Move inputs to the same device as the model to support cpu_only models. Fall back to inferring the device
        # from parameter residency only when an explicit device was not provided.
        model_device = self.device if self.device is not None else get_effective_device(self.hf_module)

        outputs = self.hf_module(
            input_ids=batch_encoding["input_ids"].to(model_device),
            attention_mask=None,
            output_hidden_states=False,
        )
        return outputs[self.output_key]