Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load fp32 models in bfloat16 when possible #231

Merged
merged 2 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Automatically use bfloat16 in some cases
  • Loading branch information
norabelrose committed May 1, 2023
commit a6d78307bd476d0bd51767bcf117000476bed65e
2 changes: 1 addition & 1 deletion elk/extraction/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def extract_hiddens(
# welcome message on every rank
with redirect_stdout(None) if rank != 0 else nullcontext():
model = instantiate_model(
cfg.model, device_map={"": device}, load_in_8bit=cfg.int8, torch_dtype=dtype
cfg.model, device=device, load_in_8bit=cfg.int8, torch_dtype=dtype
)
tokenizer = instantiate_tokenizer(
cfg.model, truncation_side="left", verbose=rank == 0
Expand Down
22 changes: 21 additions & 1 deletion elk/utils/hf_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import torch
import transformers
from transformers import (
AutoConfig,
Expand All @@ -19,10 +20,29 @@
_AUTOREGRESSIVE_SUFFIXES = ["ConditionalGeneration"] + _DECODER_ONLY_SUFFIXES


def instantiate_model(model_str: str, **kwargs) -> PreTrainedModel:
def instantiate_model(
model_str: str,
device: str | torch.device = "cpu",
**kwargs,
) -> PreTrainedModel:
"""Instantiate a model string with the appropriate `Auto` class."""
device = torch.device(device)
kwargs["device_map"] = {"": device}

with prevent_name_conflicts():
model_cfg = AutoConfig.from_pretrained(model_str)

# If the model is fp32 but bf16 is available, convert to bf16.
# Usually models with fp32 weights were actually trained in bf16, and
# converting them doesn't hurt performance.
if (
device.type != "cpu"
and model_cfg.torch_dtype == torch.float32
and torch.cuda.is_bf16_supported()
):
kwargs["torch_dtype"] = torch.bfloat16
print("Weights are in fp32, but bf16 is available. Converting to bf16.")

archs = model_cfg.architectures
if not isinstance(archs, list):
return AutoModel.from_pretrained(model_str, **kwargs)
Expand Down