Spaces:
Running on Zero
Running on Zero
File size: 2,237 Bytes
a8a9bce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import torch
from safetensors.torch import load_file
from flowdis.autoencoder import AutoEncoder
from flowdis.conditioner import HFEmbedder
from flowdis.configs import configs
from flowdis.model import Flux, FluxParams
def load_transformer(
model_name: str,
model_path: str,
device: str | torch.device = "cuda",
config: FluxParams = None,
state_dict: dict = None,
) -> Flux:
with torch.device("meta"):
model = Flux(config if config else configs[model_name]).to(dtype=torch.bfloat16)
model.to_empty(device="cpu")
if state_dict is None:
if str(model_path).endswith(".safetensors"):
state_dict = load_file(model_path, device="cpu")
else:
state_dict = torch.load(model_path, map_location="cpu")
model.load_state_dict(state_dict, assign=True, strict=False)
model = model.to(device=device, dtype=torch.bfloat16)
return model.eval()
def load_autoencoder(
model_path: str,
device: str | torch.device = "cuda"
) -> AutoEncoder:
with torch.device("meta"):
ae = AutoEncoder(configs["autoencoder"])
ae.to_empty(device="cpu")
state_dict = load_file(model_path, device="cpu")
ae.load_state_dict(state_dict, assign=True, strict=False)
ae = ae.to(device=device, dtype=torch.bfloat16)
return ae.eval()
def load_t5(
model_path: str,
max_length: int = 512,
device: str | torch.device = "cuda"
) -> HFEmbedder:
with torch.device("meta"):
t5 = HFEmbedder(
model_path.parent,
max_length=max_length,
is_clip=False,
dtype=torch.bfloat16
)
t5.to_empty(device="cpu")
state_dict = load_file(model_path, device="cpu")
t5.load_state_dict(state_dict, assign=True, strict=False)
return t5.to(device=device, dtype=torch.bfloat16)
def load_clip(
model_path: str,
device: str | torch.device = "cuda"
) -> HFEmbedder:
clip = HFEmbedder(
model_path.parent,
max_length=77,
is_clip=True,
dtype=torch.bfloat16
)
state_dict = load_file(model_path, device="cpu")
clip.load_state_dict(state_dict, assign=True, strict=False)
return clip.to(device=device, dtype=torch.bfloat16)
|