MediaStreamAI commited on
Commit
ce61751
·
verified ·
1 Parent(s): 1c07ac0

Upload modeling_mother.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_mother.py +185 -4
modeling_mother.py CHANGED
@@ -1,5 +1,186 @@
1
- """Trampoline file — imports the real wrapper from mother_hf."""
 
 
 
 
 
 
 
 
 
 
 
2
  import sys
3
- sys.path.insert(0, '/home/ckenna/mother-core-reasoning')
4
- from mother_hf.modeling_mother import MotherCoreForCausalLM
5
- __all__ = ['MotherCoreForCausalLM']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MotherCoreForCausalLM — HF-compatible wrapper around MotherCoreModel.
3
+
4
+ This class holds an instance of the REAL MotherCoreModel
5
+ (from mother_core.model). Every forward pass delegates to that model.
6
+ No architecture is reimplemented here.
7
+
8
+ If you delete this file, MOTHER CORE still works perfectly via its
9
+ native training/inference code. This wrapper is for external tool
10
+ compatibility only.
11
+ """
12
+ import os
13
  import sys
14
+ import torch
15
+ import torch.nn as nn
16
+ from typing import Optional, Tuple, List
17
+
18
+ # Add MOTHER CORE's code directory so we can import the real model
19
+
20
+ from .model import MotherCoreModel
21
+ from .config import ModelConfig
22
+
23
+ from transformers import PreTrainedModel, GenerationMixin
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+
26
+ from .configuration_mother import MotherConfig
27
+
28
+
29
+ class MotherCoreForCausalLM(PreTrainedModel, GenerationMixin):
30
+ """
31
+ HuggingFace-compatible wrapper for MOTHER CORE.
32
+
33
+ Internally holds a MotherCoreModel (the sovereign MediaStream AI model).
34
+ All operations delegate to the wrapped model.
35
+ """
36
+ config_class = MotherConfig
37
+ base_model_prefix = "mother"
38
+ supports_gradient_checkpointing = True
39
+ _no_split_modules = ["MotherCoreBlock"]
40
+
41
+ def __init__(self, config: MotherConfig):
42
+ super().__init__(config)
43
+
44
+ # Translate HF config → MOTHER CORE native ModelConfig
45
+ mother_config = ModelConfig(
46
+ vocab_size=config.vocab_size,
47
+ dim=config.hidden_size,
48
+ n_layers=config.num_hidden_layers,
49
+ n_heads=config.num_attention_heads,
50
+ n_kv_heads=config.num_key_value_heads,
51
+ ff_mult=config.ff_mult,
52
+ max_seq_len=config.max_position_embeddings,
53
+ rope_theta=config.rope_theta,
54
+ rms_norm_eps=config.rms_norm_eps,
55
+ tie_embeddings=config.tie_word_embeddings,
56
+ )
57
+
58
+ # Instantiate the REAL MOTHER CORE model
59
+ self.mother = MotherCoreModel(mother_config)
60
+
61
+ # Required for HF compatibility
62
+ self.post_init()
63
+
64
+ def forward(
65
+ self,
66
+ input_ids: torch.LongTensor = None,
67
+ attention_mask: Optional[torch.Tensor] = None,
68
+ position_ids: Optional[torch.LongTensor] = None,
69
+ past_key_values: Optional[List[Tuple[torch.Tensor]]] = None,
70
+ inputs_embeds: Optional[torch.FloatTensor] = None,
71
+ labels: Optional[torch.LongTensor] = None,
72
+ use_cache: Optional[bool] = None,
73
+ output_attentions: Optional[bool] = None,
74
+ output_hidden_states: Optional[bool] = None,
75
+ return_dict: Optional[bool] = None,
76
+ **kwargs,
77
+ ) -> CausalLMOutputWithPast:
78
+ """Passes through to MotherCoreModel.forward()."""
79
+ if inputs_embeds is not None:
80
+ raise NotImplementedError(
81
+ "inputs_embeds not supported — pass input_ids directly."
82
+ )
83
+
84
+ # Convert HF's LongTensor attention_mask to Bool
85
+ # MotherCoreModel expects Boolean masks (masked_fill requires it).
86
+ # HF tokenizers return 0/1 LongTensors by default.
87
+ if attention_mask is not None and attention_mask.dtype != torch.bool:
88
+ attention_mask = attention_mask.bool()
89
+
90
+ # Delegate to real MOTHER CORE
91
+ # Force use_cache=False at wrapper boundary — HF's cache format differs
92
+ # from MotherCoreModel's native format. Native MOTHER CORE generate()
93
+ # still uses its own cache correctly for production use.
94
+ out = self.mother(
95
+ input_ids=input_ids,
96
+ labels=labels,
97
+ past_key_values=None,
98
+ use_cache=False,
99
+ attention_mask=attention_mask,
100
+ output_hidden_states=bool(output_hidden_states)
101
+ if output_hidden_states is not None else False,
102
+ )
103
+
104
+ # Format MOTHER CORE's dict output as HF's CausalLMOutputWithPast
105
+ return CausalLMOutputWithPast(
106
+ loss=out.get('loss'),
107
+ logits=out['logits'],
108
+ past_key_values=out.get('past_key_values'),
109
+ hidden_states=tuple(out['hidden_states'])
110
+ if out.get('hidden_states') is not None else None,
111
+ attentions=None,
112
+ )
113
+
114
+ def prepare_inputs_for_generation(
115
+ self,
116
+ input_ids: torch.LongTensor,
117
+ past_key_values=None,
118
+ attention_mask: Optional[torch.Tensor] = None,
119
+ **kwargs,
120
+ ):
121
+ """HF generate() calls this to prepare each step's inputs.
122
+
123
+ We disable HF's cache threading (use_cache=False) because HF's
124
+ cache format differs from MotherCoreModel's internal format.
125
+ MOTHER CORE's own native generate() uses its own cache correctly;
126
+ this path is only for external HF tool compatibility (benchmarks).
127
+ Slightly slower but guaranteed correct.
128
+ """
129
+ return {
130
+ 'input_ids': input_ids,
131
+ 'past_key_values': None,
132
+ 'attention_mask': attention_mask,
133
+ 'use_cache': False,
134
+ }
135
+
136
+ def get_input_embeddings(self) -> nn.Module:
137
+ return self.mother.tok_emb
138
+
139
+ def set_input_embeddings(self, value: nn.Module):
140
+ self.mother.tok_emb = value
141
+
142
+ def get_output_embeddings(self) -> nn.Module:
143
+ return self.mother.lm_head
144
+
145
+ def set_output_embeddings(self, new_embeddings: nn.Module):
146
+ self.mother.lm_head = new_embeddings
147
+
148
+ @classmethod
149
+ def from_mother_checkpoint(cls, ckpt_path: str, config: MotherConfig = None):
150
+ """
151
+ Load a MOTHER CORE native checkpoint directly into the wrapper.
152
+
153
+ This lets us load v11_BEST_19of20_PROTECTED.pt without any
154
+ conversion — the wrapper just hosts the same weights.
155
+ """
156
+ if config is None:
157
+ config = MotherConfig() # defaults match MOTHER CORE v11
158
+
159
+ model = cls(config)
160
+
161
+ # Load the raw MOTHER CORE checkpoint
162
+ raw = torch.load(ckpt_path, map_location='cpu', weights_only=False)
163
+ sd = raw.get('model', raw)
164
+
165
+ # MotherCoreModel tensors are at top level (tok_emb, blocks.*, lm_head, etc.)
166
+ # We need to prefix them with 'mother.' for our wrapper
167
+ prefixed = {f'mother.{k}': v for k, v in sd.items()}
168
+
169
+ missing, unexpected = model.load_state_dict(prefixed, strict=False)
170
+
171
+ if unexpected:
172
+ print(f" [wrapper] Unexpected keys (ignored): {len(unexpected)}")
173
+ for k in unexpected[:5]:
174
+ print(f" - {k}")
175
+ if missing:
176
+ # Filter out expected missing (gradient-checkpointing etc.)
177
+ real_missing = [k for k in missing
178
+ if not k.endswith('.inv_freq')
179
+ and not 'cos_cached' in k
180
+ and not 'sin_cached' in k]
181
+ if real_missing:
182
+ print(f" [wrapper] Missing keys: {len(real_missing)}")
183
+ for k in real_missing[:5]:
184
+ print(f" - {k}")
185
+
186
+ return model