File size: 9,372 Bytes
0edf333 | 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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """A deliberately ordinary, small BERT masked language model."""
from collections.abc import Mapping
import copy
import torch
from transformers import BertConfig, BertForMaskedLM, BertModel
from transformers.models.bert.modeling_bert import BertOnlyMLMHead, BertPreTrainedModel
from .positions import RotarySelfAttention
def config_value(config, path, default=None):
"""Read a nested value from either a dict or an OmegaConf configuration."""
value = config
for part in path.split("."):
if isinstance(value, Mapping):
value = value.get(part, default)
else:
value = getattr(value, part, default)
if value is None:
return default
return value
def build_model(config):
"""Construct standard BERT with tied input/output embeddings, without a pooler."""
hidden_size = int(config_value(config, "model.hidden_size", 48))
heads = int(config_value(config, "model.num_attention_heads", 4))
if hidden_size % heads:
raise ValueError("model.hidden_size must be divisible by num_attention_heads")
bert_config = BertConfig(
vocab_size=int(config_value(config, "tokenizer.vocab_size", 8192)),
hidden_size=hidden_size,
num_hidden_layers=int(config_value(config, "model.num_hidden_layers", 3)),
num_attention_heads=heads,
intermediate_size=int(config_value(config, "model.intermediate_size", 128)),
max_position_embeddings=int(config_value(config, "model.max_position_embeddings", 512)),
type_vocab_size=2,
pad_token_id=0,
tie_word_embeddings=True,
hidden_dropout_prob=float(config_value(config, "model.dropout", 0.1)),
attention_probs_dropout_prob=float(config_value(config, "model.dropout", 0.1)),
)
backend = config_value(config, "model.attn_implementation")
if backend is not None:
if backend not in {"eager", "sdpa"}:
raise ValueError("attn_implementation must be eager or sdpa")
bert_config._attn_implementation = backend
bert_config.evm_attention_backend = backend
encoding = config_value(config, "model.position_encoding", "absolute")
if encoding not in {"absolute", "deepseek_rotary"}:
raise ValueError("position_encoding must be absolute or deepseek_rotary")
if config_value(config, "model.paired_random_initialization", False):
# Construct common weights freshly, never from a checkpoint. Forking CPU
# RNG means architecture construction cannot shift the training stream.
reference = copy.deepcopy(bert_config)
reference.max_position_embeddings = int(config_value(config, "model.paired_absolute_capacity", 512))
reference.position_embedding_type = "absolute"
with torch.random.fork_rng(devices=[]):
torch.manual_seed(int(config_value(config, "training.seed", 17)))
result = BertForMaskedLM(reference)
if encoding == "deepseek_rotary":
result = transfer_to_rotary(result,
rope=dict(config_value(config, "model.rope", {})),
max_positions=bert_config.max_position_embeddings)
result.config.evm_initialization = {
"kind": "paired random common weights; no trained checkpoint",
"seed": int(config_value(config, "training.seed", 17)),
"reference_absolute_capacity": reference.max_position_embeddings,
}
return result
if encoding == "deepseek_rotary":
bert_config.position_embedding_type = "evm_rotary"
bert_config.evm_rope = dict(config_value(config, "model.rope", {}))
bert_config._attn_implementation = "eager"
return RotaryBertForMaskedLM(bert_config)
return BertForMaskedLM(bert_config)
def parameter_count(model):
"""Count shared tensors once (the MLM decoder shares the byte embeddings)."""
return sum(parameter.numel() for parameter in model.parameters())
class RotaryBertConfig(BertConfig):
"""Fail closed in stock AutoModel rather than silently disable rotary."""
model_type = "evm_rotary_bert"
class RotaryBertModel(BertModel):
"""Encoder-only BERT with explicit coordinates passed through cache_position.
The upstream encoder already forwards this tensor through every layer, including
checkpoint recomputation. No mutable ambient state or positional hooks are used.
It carries [batch,length] coordinates here; actual decoding caches are rejected.
"""
def __init__(self, config, add_pooling_layer=False):
config = copy.deepcopy(config)
config._attn_implementation = "eager"
config.position_embedding_type = "evm_rotary"
super().__init__(config, add_pooling_layer=add_pooling_layer)
self.embeddings.position_embeddings = None
for index, layer in enumerate(self.encoder.layer):
# Keep the original parameter initialization and RNG trajectory.
with torch.random.fork_rng(devices=[]):
replacement = RotarySelfAttention(config, index)
replacement.load_state_dict(layer.attention.self.state_dict(), strict=True)
layer.attention.self = replacement
def forward(self, input_ids=None, **kwargs):
if kwargs.get("past_key_values") is not None or kwargs.get("cache_position") is not None:
raise ValueError("Explicit position_ids are required instead of a decoding cache")
source = input_ids if input_ids is not None else kwargs.get("inputs_embeds")
if source is None:
raise ValueError("input_ids or inputs_embeds are required")
batch, length = source.shape[:2]
positions = kwargs.get("position_ids")
if positions is None:
positions = torch.arange(length, device=source.device)[None].expand(batch, -1)
elif positions.shape == (1, length):
positions = positions.expand(batch, -1)
if positions.shape != (batch, length) or positions.dtype not in (torch.int32, torch.int64):
raise ValueError("position_ids must be integer [batch,length] coordinates")
if torch.any(positions < 0) or torch.any(positions >= self.config.max_position_embeddings):
raise ValueError("Position exceeds the explicit configured capacity")
kwargs["position_ids"] = positions
kwargs["cache_position"] = positions
if kwargs.get("token_type_ids") is None:
kwargs["token_type_ids"] = torch.zeros((batch, length), dtype=torch.long, device=source.device)
return super().forward(input_ids=input_ids, **kwargs)
class RotaryBertForMaskedLM(BertForMaskedLM):
"""Save/load-compatible MLM using the explicit local rotary encoder."""
config_class = RotaryBertConfig
def __init__(self, config):
config = RotaryBertConfig(**config.to_dict())
BertPreTrainedModel.__init__(self, config)
self.bert = RotaryBertModel(config, add_pooling_layer=False)
self.cls = BertOnlyMLMHead(config)
self.post_init()
def build_bert_encoder(config, *, add_pooling_layer=False):
"""Build the encoder selected by a persisted BERT configuration."""
if getattr(config, "evm_attention_backend", None):
config = copy.deepcopy(config)
config._attn_implementation = config.evm_attention_backend
cls = RotaryBertModel if config.position_embedding_type == "evm_rotary" else BertModel
return cls(config, add_pooling_layer=add_pooling_layer)
def mlm_from_config(config):
cls = RotaryBertForMaskedLM if config.position_embedding_type == "evm_rotary" else BertForMaskedLM
return cls(config)
def load_mlm_model(path, **kwargs):
"""Load local/HF MLM with our explicit architecture dispatch (no remote code)."""
config = kwargs.pop("config", None)
if config is None:
hub_options = {key: kwargs[key] for key in (
"revision", "cache_dir", "force_download", "proxies", "token", "local_files_only", "subfolder"
) if key in kwargs}
values, _ = BertConfig.get_config_dict(path, **hub_options)
config_class = RotaryBertConfig if values.get("position_embedding_type") == "evm_rotary" else BertConfig
config = config_class.from_dict(values)
cls = RotaryBertForMaskedLM if config.position_embedding_type == "evm_rotary" else BertForMaskedLM
if getattr(config, "evm_attention_backend", None):
kwargs.setdefault("attn_implementation", config.evm_attention_backend)
return cls.from_pretrained(path, config=config, **kwargs)
def transfer_to_rotary(model, *, rope=None, max_positions=2048):
"""Transfer common absolute-BERT weights into a NEW, functionally changed MLM.
No optimizer state transfers. The old model/artifact is never mutated. Removing
the learned table and changing attention requires further training/evaluation.
"""
config = copy.deepcopy(model.config)
config.position_embedding_type = "evm_rotary"
config.evm_rope = dict(rope or {})
config.max_position_embeddings = int(max_positions)
config._attn_implementation = "eager"
result = RotaryBertForMaskedLM(config)
state = {k: v for k, v in model.state_dict().items()
if k != "bert.embeddings.position_embeddings.weight"}
result.load_state_dict(state, strict=True)
result.tie_weights()
return result
|