herb-150m / encoder_decision.py
ericlewis's picture
Publish Herb-150M (hf_stage_herb_main) to main
53b8f3b verified
Raw History Blame Contribute Delete
30.6 kB
"""Encoders and cross-encoder rerankers as Unsloth decision models.
from encoder_decision import FastDecisionModel
model, tokenizer = FastDecisionModel.from_pretrained("cross-encoder/ms-marco-MiniLM-L6-v2", full_finetuning=True)
FastDecisionModel is Unsloth's, with one more kind of checkpoint it loads: a BERT-style encoder (BERT, RoBERTa,
DeBERTa, ModernBERT, UltraBERT, ...), be it a bare encoder, an embedding model or a cross-encoder reranker. The
reranker's scoring head is dropped and the bare encoder gets a new decision head. decision_head picks which:
None, "clef" Unsloth's Clef head, as it gives a language model. One pass answers every question of a row.
"cosine" the small cosine head of cosine_head.py, in the Clef layout.
"laya" Laya's head: the layout Unsloth already has for an encoder, so the saved folder is an ordinary
Laya checkpoint that stock Unsloth and the laya runtime load. One pass per question.
masked_lm=True keeps a masked LM whole where the prediction head would be dropped (clef and cosine heads). The
decision head then reads the hidden states the LM's own decoder reads, and rows of that decoder, as it does on a
language model. Without it the head reads the bare encoder's output and rows of the input embedding table, which
for a model that does not tie the two (UltraBERT) is another table. A saved folder remembers which it was.
sequence="lean" writes records in the short sequence of lean_sequence.py instead of Clef's chat (clef and cosine
heads). A saved folder remembers that too, and loading it marks the tokenizer it returns.
Either way get_peft_model, build_dataset, DecisionTrainer, evaluate, calibrate and the save methods work unchanged.
A checkpoint that already has a decision head loads with it, and every other checkpoint goes to Unsloth's own
from_pretrained untouched.
load_encoder_as_laya_model and load_encoder_as_decision_model are the two loaders underneath.
"""
import functools
import inspect
import json
import math
import types
from pathlib import Path
import torch
import unsloth # noqa: F401 (before transformers)
HEAD_FILES = ("joint_head.safetensors", "joint_head_config.json")
CAUSAL_ONLY = ("use_cache", "return_dict")
DECISION_CONFIG = "unsloth_decision_config.json"
def _checkpoint_json(model_name, filename, token=None, revision=None, local_files_only=False):
try:
root = Path(str(model_name)).expanduser()
if root.is_dir():
path = root / filename
else:
from huggingface_hub import hf_hub_download
path = hf_hub_download(str(model_name), filename, token=token, revision=revision,
local_files_only=local_files_only)
return json.loads(Path(path).read_text(encoding="utf-8"))
except Exception:
# Let the underlying loader report missing or inaccessible model files.
return None
def is_encoder(model_name, subfolder=None, token=None, revision=None, local_files_only=False) -> bool:
"""Whether a checkpoint is a BERT-style encoder or a decision model trained from one."""
if subfolder:
return False
return _is_encoder_config(_checkpoint_json(model_name, "config.json", token, revision, local_files_only))
def _is_encoder_config(config):
if not isinstance(config, dict) or config.get("is_decoder") or config.get("is_encoder_decoder"):
return False
# Custom code says what it is by the classes it registers; a built-in type by having a masked-LM class.
auto_map = config.get("auto_map") or {}
if "AutoModelForCausalLM" in auto_map:
return False
if {"AutoModelForMaskedLM", "AutoModelForSequenceClassification"} & set(auto_map):
return True
from transformers.models.auto.modeling_auto import MODEL_FOR_MASKED_LM_MAPPING_NAMES
return config.get("model_type") in MODEL_FOR_MASKED_LM_MAPPING_NAMES
def position_limit(backbone):
"""How many tokens the encoder has positions for, or None when it has no fixed table."""
positions = getattr(backbone.config, "max_position_embeddings", None)
encoder = getattr(backbone, "base_model", backbone) # a masked LM keeps its tables on its encoder
table = getattr(getattr(encoder, "embeddings", None), "position_embeddings", None)
# RoBERTa-style tables start counting after the padding index, so two rows are never a position
skipped = table.padding_idx + 1 if getattr(table, "padding_idx", None) is not None else 0
return positions - skipped if positions else None
def adapt_encoder(backbone):
"""Give a bare encoder the two things ClefDecisionModel.forward asks of a backbone: a forward that
tolerates the causal-LM keywords it passes (use_cache, return_dict), and get_output_embeddings()."""
named = inspect.signature(backbone.forward).parameters
open_ended = any(p.kind is p.VAR_KEYWORD for p in named.values())
# Kept as an attribute (not a closure) so a deepcopy of the model rebinds it to the copy.
backbone._strict_forward = backbone.forward
def tolerant(self, *args, **kwargs):
# A forward that takes **kwargs may still reject these two, so they pass only when named.
return self._strict_forward(*args, **{k: v for k, v in kwargs.items()
if k in named or (open_ended and k not in CAUSAL_ONLY)})
backbone.forward = types.MethodType(tolerant, backbone)
# The head only reads token embedding rows, so the input table stands in for an LM head.
backbone.get_output_embeddings = backbone.get_input_embeddings
return keep_weight_names(backbone)
def keep_weight_names(backbone):
# Transformers writes some models back under the weight names of their first release (UltraBERT: an
# `ultrabert.` prefix). Unsloth reloads checkpoints by name, so they keep the names this model has.
if "save_original_format" in inspect.signature(backbone.save_pretrained).parameters:
backbone.save_pretrained = functools.partial(backbone.save_pretrained, save_original_format=False)
return backbone
def _read_through(hidden_states):
return hidden_states
def adapt_masked_lm(masked_lm):
"""Make a masked LM return, as its logits, the hidden states its decoder reads. The decoder (the LM's output
embedding layer) keeps its weight, which the decision head reads rows of, and passes its input through.
Checked against the LM's own logits first, so an architecture whose logits are not decoder(hidden) is refused."""
decoder = masked_lm.get_output_embeddings()
if not isinstance(decoder, torch.nn.Linear):
raise ValueError(f"{type(masked_lm).__name__} has no output embedding layer to read, so it cannot be "
"loaded with masked_lm=True.")
weight, training = decoder.weight, masked_lm.training
ids = (torch.arange(12, device=weight.device).reshape(2, 6) * 7 + 3) % masked_lm.config.vocab_size
inputs = {"input_ids": ids, "attention_mask": torch.ones_like(ids)}
masked_lm.eval()
try:
with torch.no_grad():
logits = masked_lm(**inputs).logits.float()
decoder.forward = _read_through
read = masked_lm(**inputs).logits
same_width = read.shape[-1] == weight.shape[1]
rebuilt = torch.nn.functional.linear(read, weight, decoder.bias).float() if same_width else None
finally:
masked_lm.train(training)
tolerance = 1e-3 if weight.dtype in (torch.float32, torch.float64) else 5e-2
if rebuilt is None or not torch.allclose(rebuilt, logits, rtol=tolerance, atol=tolerance * float(logits.abs().max())):
del decoder.forward
raise ValueError(f"{type(masked_lm).__name__}'s logits are not its output embedding layer applied to a "
"hidden state, so it cannot be loaded with masked_lm=True.")
return keep_weight_names(masked_lm)
class MaskedLMBackbone:
"""A masked LM the way ClefDecisionModel reads a backbone: `model(...)` gives, as last_hidden_state, the
hidden states the LM's decoder reads, and every other attribute is the masked LM's own."""
def __init__(self, masked_lm):
self.masked_lm = masked_lm
def model(self, input_ids=None, attention_mask=None, **causal_only):
from transformers.modeling_outputs import BaseModelOutput
read = self.masked_lm(input_ids=input_ids, attention_mask=attention_mask).logits
return BaseModelOutput(last_hidden_state=read)
def __getattr__(self, name):
if name == "masked_lm":
raise AttributeError(name)
return getattr(self.masked_lm, name)
@functools.lru_cache(maxsize=None)
def masked_lm_decision_model():
"""ClefDecisionModel for a masked LM: the same model, reading its backbone through MaskedLMBackbone."""
from unsloth.models.decision import ClefDecisionModel
class MaskedLMDecisionModel(ClefDecisionModel):
def _backbone(self):
return MaskedLMBackbone(super()._backbone())
MaskedLMDecisionModel.__qualname__ = "MaskedLMDecisionModel"
globals()["MaskedLMDecisionModel"] = MaskedLMDecisionModel # found by name, so the model can be pickled
return MaskedLMDecisionModel
def load_encoder(model_name, dtype=None, masked_lm=False, attn_implementation=None, **hub):
"""The bare encoder of any checkpoint. A custom-code repo that registers only a task model
(a reranker's AutoModelForSequenceClassification) is loaded as that and unwrapped.
With masked_lm, the whole masked LM instead: the encoder and the prediction head AutoModel drops."""
from transformers import AutoConfig, AutoModel, AutoModelForSequenceClassification
dtype = dtype or torch.float32
if attn_implementation: # for the model only: the config and tokenizer loads do not take it
hub = {**hub, "attn_implementation": attn_implementation}
config_hub = {key: value for key, value in hub.items() if key != "attn_implementation"}
else:
config_hub = hub
if masked_lm:
from transformers import AutoModelForMaskedLM
model, report = AutoModelForMaskedLM.from_pretrained(str(model_name), dtype=dtype, output_loading_info=True, **hub)
if report["missing_keys"]:
raise ValueError(f"{model_name} has no weights for {sorted(report['missing_keys'])[:3]}: it does not hold "
"a masked LM's prediction head, so it cannot be loaded with masked_lm=True.")
return model
auto_map = getattr(AutoConfig.from_pretrained(str(model_name), **config_hub), "auto_map", None) or {}
if auto_map and "AutoModel" not in auto_map:
task = AutoModelForSequenceClassification.from_pretrained(str(model_name), dtype=dtype, **hub)
if task.base_model is task:
raise ValueError(f"{model_name} does not expose its encoder through base_model.")
return task.base_model
# AutoModel drops a masked-LM or reranker head.
return AutoModel.from_pretrained(str(model_name), dtype=dtype, **hub)
def fold_cosine_temperature():
"""Unsloth saves a calibrated head_temperature by dividing it into the Clef head's own scales. Teach it the
cosine head's one scale; exact while the result stays under the head's clamp at log 100."""
from unsloth.models import decision
clef = decision._fold_temperature
if getattr(clef, "cosine", False):
return
def fold(state, temperature):
if "logit_scale" not in state:
return clef(state, temperature)
value = min(float(state["logit_scale"]), math.log(100.0)) - math.log(temperature)
if value > math.log(100.0):
return False
state["logit_scale"] = torch.tensor(value, dtype=state["logit_scale"].dtype)
return True
fold.cosine = True
decision._fold_temperature = fold
def make_head(config):
if config.get("kind") == "cosine":
from cosine_head import CosineSpanHead
fold_cosine_temperature()
return CosineSpanHead(**config)
if config.get("kind") == "hybrid_sab":
from hybrid_sab_head import PortableHybridSetAttentionHead
return PortableHybridSetAttentionHead(**config)
from unsloth.models.clef import JointSchemaHead
return JointSchemaHead(**config)
def load_encoder_as_decision_model(model_name, max_seq_length=None, full_finetuning=True, head_width=None,
head_config=None, dtype=None, token=None, revision=None,
random_state=3407, device=None, use_gradient_checkpointing=False,
masked_lm=False, sequence=None, attn_implementation=None, **kwargs):
from safetensors.torch import load_file
from transformers import AutoTokenizer
from unsloth.models.decision import (CLEF_MAX_LEN, ClefDecisionModel, _attach_clef_saving,
_device, _mark_full_finetuning)
from unsloth.models.decision_from_lm import _source_folder, default_head_config
hub = {"token": token, "revision": revision, **kwargs}
folder = Path(str(model_name)).expanduser()
if not folder.is_dir(): # a Hub repo: fetch what a trained model would hold
from huggingface_hub import snapshot_download
folder = Path(snapshot_download(str(model_name), token=token, revision=revision,
local_files_only=bool(kwargs.get("local_files_only")),
allow_patterns=[*HEAD_FILES, DECISION_CONFIG, "model*.safetensors"]))
trained = all((folder / name).is_file() for name in HEAD_FILES) # saved by model.save_pretrained
saved = json.loads((folder / DECISION_CONFIG).read_text(encoding="utf-8")) if trained else {}
saved.pop("training", None)
# A trained folder's weights are for the kind of backbone it was trained on, whatever is asked for.
masked_lm = bool(saved.get("masked_lm")) if trained else bool(masked_lm)
# Likewise the token sequence its records were written in: Clef's, or the lean one of lean_sequence.py.
sequence = saved.get("sequence") if trained else sequence
if sequence not in (None, "clef", "lean", "lean-start"):
raise ValueError(f"Unsloth: sequence is 'clef', 'lean' or 'lean-start', not {sequence!r}.")
tokenizer = AutoTokenizer.from_pretrained(str(model_name), **hub)
if trained and saved.get("base_model") not in (None, str(model_name)):
# The saved folder holds weights but not a custom architecture's code, so the architecture
# comes from the model the fine-tune started from and the trained weights go on top.
backbone = load_encoder(saved["base_model"], dtype, masked_lm=masked_lm, attn_implementation=attn_implementation,
**{**hub, "revision": None})
state = {}
for shard in sorted(folder.glob("model*.safetensors")):
state.update(load_file(str(shard)))
# A folder saved before adapt_encoder kept the names: the weights are under UltraBERT's first prefix
state = {key.removeprefix("ultrabert."): value for key, value in state.items()}
missing, unexpected = backbone.load_state_dict(state, strict=False)
# A weight tied to another (a masked LM's decoder to its input table) is stored under one of its names.
names = {}
for name, parameter in backbone.named_parameters(remove_duplicate=False):
names.setdefault(id(parameter), []).append(name)
stored = {name for shared in names.values() if set(shared) & set(state) for name in shared}
missing = [key for key in missing if key not in stored]
if missing or unexpected or not state:
raise RuntimeError(f"{model_name} does not match {saved['base_model']} "
f"(missing {sorted(missing)[:3]}, unexpected {sorted(unexpected)[:3]}).")
else:
backbone = load_encoder(model_name, dtype, masked_lm=masked_lm, attn_implementation=attn_implementation, **hub)
if getattr(backbone.config, "is_decoder", False):
raise ValueError(f"{model_name} is a decoder; load it with FastDecisionModel.from_pretrained.")
if hasattr(backbone.config, "reference_compile"):
backbone.config.reference_compile = False # ModernBERT would torch.compile itself
if masked_lm:
adapt_masked_lm(backbone)
else:
adapt_encoder(backbone)
if not full_finetuning:
backbone.requires_grad_(False)
if tokenizer.pad_token_id is None:
raise ValueError(f"{model_name}'s tokenizer has no pad token.")
if masked_lm:
# The head reads what the LM's decoder reads and rows of that decoder, which are equally wide.
hidden_size = int(backbone.get_output_embeddings().weight.shape[1])
else:
hidden_size = int(backbone.config.hidden_size)
embedding = backbone.get_input_embeddings().weight
if embedding.shape[1] != hidden_size:
raise ValueError(f"{model_name} embeds tokens in {embedding.shape[1]} dims but its hidden size is "
f"{hidden_size}; the decision head needs them equal.")
max_len, limit = int(max_seq_length or CLEF_MAX_LEN), position_limit(backbone)
if limit and max_len > limit:
if max_seq_length:
print(f"Unsloth: {model_name} reads at most {limit} tokens, so max_seq_length is {limit}, not {max_len}.")
max_len = limit
if use_gradient_checkpointing and getattr(backbone, "supports_gradient_checkpointing", False):
backbone.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
# head_config = dict(kind="cosine", ...) builds the small cosine head, anything else the Clef head
if trained:
head = make_head(json.loads((folder / HEAD_FILES[1]).read_text(encoding="utf-8")))
head.load_state_dict(load_file(str(folder / HEAD_FILES[0])), strict=True)
else:
with torch.random.fork_rng(devices=[]):
torch.manual_seed(random_state)
head = make_head({"hidden_size": hidden_size, **(head_config or default_head_config(hidden_size, head_width))})
if head.config["hidden_size"] != hidden_size:
raise ValueError(f"The head reads {head.config['hidden_size']} dims, {model_name} has {hidden_size}.")
device = torch.device(device) if device is not None else _device()
if masked_lm:
model_class = masked_lm_decision_model()
elif getattr(head, "scalar_mix", None) is not None:
from hybrid_sab_head import multi_layer_clef_decision_model
model_class = multi_layer_clef_decision_model()
else:
model_class = ClefDecisionModel
model = model_class(backbone.to(device), head.to(device=device, dtype=torch.float32))
model.decision_config = {"layout": "clef", "max_len": max_len, "temperature": [1.0] * 3,
"base_model": str(model_name), "load_in_4bit": False}
if masked_lm:
model.decision_config["masked_lm"] = True
if sequence in ("lean", "lean-start"):
from lean_sequence import use_lean_sequence
use_lean_sequence(tokenizer, start=sequence == "lean-start") # records built with this tokenizer are lean
model.decision_config["sequence"] = sequence
model.decision_config.update(saved, max_len=max_len)
_mark_full_finetuning(model, full_finetuning)
model._unsloth_forced_float32 = False
model._unsloth_fast_backbone = False # get_peft_model then uses plain PEFT
model._unsloth_encoder_backbone = True
model._saved_temp_tokenizer = tokenizer
model._unsloth_source_vocab = len(tokenizer)
source = _source_folder(model_name, token, revision, False)
model._unsloth_source_folder = str(source) if source is not None else ""
_attach_clef_saving(model)
# An encoder is small: with LoRA adapters it still saves whole (merged), which is the one layout this file loads.
model.save_pretrained = model.save_pretrained_merged
return model, tokenizer
def has_clef_head(model_name, token=None, revision=None, local_files_only=False) -> bool:
"""Whether an encoder checkpoint already holds a Clef-layout decision head: a model this file trained and saved."""
folder = Path(str(model_name)).expanduser()
if folder.is_dir():
return all((folder / name).is_file() for name in HEAD_FILES)
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError
try:
hf_hub_download(str(model_name), HEAD_FILES[1], token=token, revision=revision, local_files_only=local_files_only)
except EntryNotFoundError:
return False
return True
def laya_problem(model_name, **hub) -> str:
"""Why a Laya checkpoint cannot hold this encoder, or "" when it can. The checkpoint keeps the encoder's config
and weights but not its code, is loaded with SDPA attention, and writes each question with the tokenizer's
[CLS], [SEP] and [MASK]."""
from transformers import AutoConfig, AutoModel, AutoTokenizer
model_class = AutoModel._model_mapping.get(type(AutoConfig.from_pretrained(str(model_name), **hub)), None)
if not getattr(model_class, "__module__", "").startswith("transformers."):
return "its encoder runs on code that is not part of Transformers"
if not model_class._supports_sdpa:
return f"{model_class.__name__} has no SDPA attention"
tokenizer = AutoTokenizer.from_pretrained(str(model_name), **hub)
missing = [name for name in ("cls_token", "sep_token", "mask_token", "pad_token") if getattr(tokenizer, name) is None]
return f"its tokenizer has no {', '.join(missing)}" if missing else ""
def load_encoder_as_laya_model(model_name, max_seq_length=None, full_finetuning=True, head_layers=2, dtype=None,
token=None, revision=None, random_state=3407, device=None,
use_gradient_checkpointing=False, **kwargs):
"""Laya's decision model on any encoder, with a new head. What Unsloth's Laya route does for a trained
checkpoint, starting from the encoder alone; the result saves as a Laya checkpoint that route loads."""
from transformers import AutoTokenizer
from unsloth.models import decision
hub = {"token": token, "revision": revision, **kwargs}
problem = laya_problem(model_name, **hub)
if problem:
raise ValueError(f'{model_name} cannot be a Laya decision model: {problem}. decision_head="clef" works.')
tokenizer = AutoTokenizer.from_pretrained(str(model_name), **hub)
encoder = load_encoder(model_name, **hub)
if hasattr(encoder.config, "reference_compile"):
encoder.config.reference_compile = False # ModernBERT would torch.compile itself
config = {"encoder": str(model_name), "head_layers": head_layers, "act_costs": {}, "temperature": [1.0] * 3}
with torch.random.fork_rng(devices=[]):
torch.manual_seed(random_state)
model = decision._laya().common.DecisionModel(encoder, head_layers, len(config["act_costs"]) + 1)
config["max_len"], config["head_max_len"] = decision._served_lengths(
config, position_limit(encoder) or decision.TRAIN_MAX_LEN, max_seq_length)
model.decision_config = config
device = torch.device(device) if device is not None else decision._device()
model.float()
if not full_finetuning:
dtype = dtype or (torch.float32 if device.type == "cpu" else torch.float16)
for param in model.encoder.parameters(): # weights only, as Unsloth's Laya route freezes them
param.requires_grad_(False)
param.data = param.data.to(dtype)
model.to(device)
decision._mark_full_finetuning(model, full_finetuning)
decision._gradient_checkpointing(
model, use_gradient_checkpointing if getattr(encoder, "supports_gradient_checkpointing", False) else False)
model._unsloth_encoder_backbone = True
model._saved_temp_tokenizer = tokenizer
model._unsloth_encoder_config = encoder.config.to_json_string()
model.save_pretrained_merged = types.MethodType(decision.save_pretrained_merged, model)
model.push_to_hub_merged = types.MethodType(decision.push_to_hub_merged, model)
decision._attach_gguf_saving(model)
return model, tokenizer
_Unsloth = getattr(unsloth, "FastDecisionModel", None)
if _Unsloth is None: # a CPU-only install does not export it
from unsloth.models.decision import FastDecisionModel as _Unsloth
def within_positions(model):
"""Unsloth's Laya route takes max_position_embeddings as the length; a RoBERTa-style table holds two fewer."""
if isinstance(model, torch.nn.Module) and not getattr(model, "is_clef", False):
config, limit = model.decision_config, position_limit(model.encoder)
if limit and config["max_len"] > limit:
config["max_len"], config["head_max_len"] = limit, min(config["head_max_len"], limit // 2)
return model
class FastDecisionModel(_Unsloth):
"""Unsloth's FastDecisionModel, which also loads encoders and cross-encoder rerankers (see the top of this file).
For those, decision_head is "clef" (the default), "cosine" or "laya", and load_in_4bit is ignored.
masked_lm=True keeps a masked LM's prediction head under a clef or cosine head."""
@staticmethod
def from_pretrained(model_name, *args, **kwargs):
bound = inspect.signature(_Unsloth.from_pretrained).bind(model_name, *args, **kwargs).arguments
options = {**bound, **bound.get("kwargs", {})}
hub = {key: options.get(key) for key in ("token", "revision")}
offline = bool(options.get("local_files_only"))
config = None if options.get("subfolder") else _checkpoint_json(model_name, "config.json", local_files_only=offline, **hub)
if isinstance(config, dict) and config.get("model_type") == "klm":
head_config = options.get("head_config") or {}
saved_head = _checkpoint_json(model_name, HEAD_FILES[1], local_files_only=offline, **hub) or {}
if (options.get("decision_head") == "cosine" or head_config.get("kind") == "cosine"
or saved_head.get("head_type") == "cosine_span_v1"):
from klm_decision import load_klm_decision
if options.get("dtype") not in (None, torch.float32) or options.get("load_in_4bit") or options.get("load_in_8bit"):
raise ValueError("Native KLM uses FP32 master weights; enable BF16 autocast in the trainer")
if options.get("masked_lm"):
raise ValueError("Native KLM uses its causal backbone")
return load_klm_decision(
model_name, max_seq_length=options.get("max_seq_length"), sequence=options.get("sequence"),
initial_scale=head_config.get("scale", head_config.get("initial_scale", 8.0)),
width=head_config.get("width", options.get("head_width") or 512),
full_finetuning=options.get("full_finetuning", False),
use_gradient_checkpointing=options.get("use_gradient_checkpointing", False),
seed=options.get("random_state", 3407), device=options.get("device"),
attn_implementation=options.get("attn_implementation") or "sdpa",
local_files_only=offline, **hub)
if not _is_encoder_config(config):
model, tokenizer = _Unsloth.from_pretrained(model_name, *args, **kwargs)
return within_positions(model), tokenizer
if _Unsloth.__module__.endswith("mlx"):
raise NotImplementedError("Unsloth: encoder decision models run on PyTorch; MLX does not load them yet.")
if options.get("load_in_8bit"):
raise NotImplementedError("Unsloth: decision models do not support load_in_8bit.")
head = options.get("decision_head") or "clef"
if head not in ("clef", "cosine", "laya"):
raise ValueError(f"Unsloth: an encoder takes a clef, a cosine or a laya decision head, not {head!r}.")
local = {key: options[key] for key in ("trust_remote_code", "local_files_only") if options.get(key)}
common = dict(
max_seq_length=options.get("max_seq_length"),
full_finetuning=options.get("full_finetuning", False),
dtype=options.get("dtype"),
random_state=options.get("random_state", 3407),
use_gradient_checkpointing=options.get("use_gradient_checkpointing", "unsloth"),
**hub,
**local,
)
# A folder saved with a Clef-layout head loads with it, whatever is asked for.
if head == "laya" and not has_clef_head(model_name, local_files_only=bool(local.get("local_files_only")), **hub):
if options.get("masked_lm"):
raise ValueError("Unsloth: a Laya checkpoint holds a bare encoder, so masked_lm=True needs a clef or a cosine head.")
return load_encoder_as_laya_model(model_name, **common)
return load_encoder_as_decision_model(
model_name,
head_width=options.get("head_width"),
head_config=options.get("head_config") or ({"kind": "cosine"} if head == "cosine" else None),
masked_lm=bool(options.get("masked_lm")),
sequence=options.get("sequence"),
attn_implementation=options.get("attn_implementation"),
**common,
)
@staticmethod
def get_peft_model(model, *args, **kwargs):
bound = inspect.signature(_Unsloth.get_peft_model).bind(model, *args, **kwargs)
if getattr(model, "_unsloth_encoder_backbone", False) and bound.arguments.get("target_modules", "all-linear") == "all-linear":
# Unsloth's default names a language model's layers; an encoder's linear layers are found by type.
# A masked LM's decoder is left out: the decision head reads its weight as it is.
decoder = model.encoder.get_output_embeddings() if model.decision_config.get("masked_lm") else None
bound.arguments["target_modules"] = [
name for name, module in model.encoder.named_modules()
if isinstance(module, torch.nn.Linear) and not name.startswith("pooler") and module is not decoder]
return _Unsloth.get_peft_model(*bound.args, **bound.kwargs)