BranchOne / modeling_branchone.py
ndemirdemir's picture
Accept matching adapter transport metadata from Transformers AutoModel
4f7f1e5 verified
Raw History Blame Contribute Delete
5.57 kB
"""Load the released adapter and decision head through Transformers AutoModel."""
import shutil
import tempfile
from pathlib import Path
import torch
from huggingface_hub import snapshot_download
from transformers import PreTrainedModel
from .calibration import SERVING_FILES
from .configuration_branchone import BranchOneConfig
from .model import BranchOne
class BranchOneModel(PreTrainedModel):
config_class = BranchOneConfig
base_model_prefix = "decision_model"
main_input_name = "request"
def __init__(self, config, decision_model):
super().__init__(config)
self.decision_model = decision_model
# These tensors are already trained. Do not run post_init/initialization.
self.eval()
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path,
*model_args,
config=None,
device="cuda",
revision=None,
cache_dir=None,
token=None,
local_files_only=False,
force_download=False,
**kwargs,
):
"""Load the fixed FP16 inference backend, without a GitHub dependency.
The repository contains an adapter and head. The pinned public Qwen
backbone downloads separately on first use. Use HF_HUB_OFFLINE=1 after
caching both repositories when running entirely offline.
"""
if model_args:
raise TypeError("BranchOne takes no positional model arguments")
for key in ("_from_auto", "_commit_hash", "trust_remote_code"):
kwargs.pop(key, None)
adapter_kwargs = kwargs.pop("adapter_kwargs", None)
if adapter_kwargs:
# AutoModel forwards Hub transport metadata through this dictionary
# when PEFT is installed. Newer releases include the resolved revision.
# These options do not select a different adapter.
if (
not isinstance(adapter_kwargs, dict)
or set(adapter_kwargs) - {"token", "revision"}
):
raise ValueError("External adapter overrides are not supported")
if "token" in adapter_kwargs and adapter_kwargs["token"] != token:
raise ValueError("Adapter authentication must match the model's token option")
compatible_revisions = (
revision,
getattr(config, "_commit_hash", None),
"main" if revision is None else revision,
)
if (
"revision" in adapter_kwargs
and adapter_kwargs["revision"] not in compatible_revisions
):
raise ValueError("Adapter revision must match the loaded model revision")
if kwargs.pop("subfolder", ""):
raise ValueError("Load the root of the BranchOne model repository")
if kwargs:
raise TypeError("Unsupported BranchOne loading arguments: " + ", ".join(sorted(kwargs)))
if torch.device(device).type != "cuda":
raise ValueError("This release is qualified for CUDA FP16; use device='cuda'")
if not torch.cuda.is_available():
raise RuntimeError("A CUDA GPU is required for this release")
if config is None:
config = BranchOneConfig.from_pretrained(
pretrained_model_name_or_path, revision=revision, cache_dir=cache_dir,
token=token, local_files_only=local_files_only, force_download=force_download,
)
files = [*SERVING_FILES, "calibration.json"]
source = Path(pretrained_model_name_or_path)
if not source.is_dir():
# Match the exact commit of the configuration/code resolved by AutoModel.
source = Path(snapshot_download(
repo_id=str(pretrained_model_name_or_path),
revision=getattr(config, "_commit_hash", None) or revision,
cache_dir=cache_dir, token=token, local_files_only=local_files_only,
force_download=force_download, allow_patterns=files,
))
# HF caches may use links to a blob store. Materialize only the allowlisted
# files, then let the existing calibration guard check every file's bytes.
with tempfile.TemporaryDirectory(prefix="branchone-inference-") as directory:
checkpoint = Path(directory)
for name in files:
destination = checkpoint / name
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / name, destination)
decision_model = BranchOne.load(
checkpoint, device=device, trainable=False,
hub_options={"cache_dir": cache_dir, "token": token,
"local_files_only": local_files_only,
"force_download": force_download},
)
return cls(config, decision_model)
@torch.inference_mode()
def forward(self, request):
"""Return one unscaled logit per supplied candidate."""
return self.decision_model(request)
def predict(self, request, *, threshold=None):
"""Return aligned candidate probabilities, selected ID, and policy metadata."""
return self.decision_model.predict(request, threshold=threshold)
def save_pretrained(self, *args, **kwargs):
raise NotImplementedError(
"This is an inference package. Preserve the downloaded repository files "
"to keep the adapter, processor, and calibration binding together."
)