Download source/src/evm_bert/model.py from willynilly-fr/evm-positions-scratch-20ep: direct link, hf CLI and curl.
- Browser
- Download file 9.37 kB
-
https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/model.py
- Command line
-
hf download hf://willynilly-fr/evm-positions-scratch-20ep/source/src/evm_bert/model.py
-
curl -L -o model.py https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/model.py
9.37 kB
| """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 | |