Surgical SFT/DPO & standalone trust_remote_code fixes

#3
by KitsuVp - opened
Files changed (2) hide show
  1. configuration_neollm.py +29 -0
  2. modeling_neollm.py +154 -19
configuration_neollm.py CHANGED
@@ -971,6 +971,16 @@ class NeoLLMConfig(PretrainedConfig):
971
  linear_attention_head_dim=None, # None: inherit the model's head_dim
972
  linear_attention_expand_v=1.0, # Value-head width / linear head_dim
973
  linear_attention_conv_size=4, # Causal short-convolution width
 
 
 
 
 
 
 
 
 
 
974
  **kwargs,
975
  ):
976
  # ── Main NTP loss backend ─────────────────────────────────────────
@@ -1757,6 +1767,25 @@ class NeoLLMConfig(PretrainedConfig):
1757
  self.iha_sliding_window = iha_sliding_window
1758
  self.iha_global_layers_use_iha = bool(iha_global_layers_use_iha)
1759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1760
  self.auto_map = {
1761
  "AutoConfig": "configuration_neollm.NeoLLMConfig",
1762
  "AutoModel": "modeling_neollm.NeoLLMModel",
 
971
  linear_attention_head_dim=None, # None: inherit the model's head_dim
972
  linear_attention_expand_v=1.0, # Value-head width / linear head_dim
973
  linear_attention_conv_size=4, # Causal short-convolution width
974
+ # ── SFT/DPO structural protection (opt-in, pretraining-off) ───────
975
+ meap_structural_token_ids=None,
976
+ meap_protect_chat_headers=False,
977
+ meap_protect_ignored_labels=False,
978
+ copy_exclude_structural_tokens=False,
979
+ copy_exclude_token_ids=None,
980
+ copy_exclude_chat_headers=False,
981
+ copy_chat_im_start_token_id=6,
982
+ copy_chat_im_end_token_id=7,
983
+ copy_chat_newline_token_id=708,
984
  **kwargs,
985
  ):
986
  # ── Main NTP loss backend ─────────────────────────────────────────
 
1767
  self.iha_sliding_window = iha_sliding_window
1768
  self.iha_global_layers_use_iha = bool(iha_global_layers_use_iha)
1769
 
1770
+ # ── SFT/DPO structural protection (opt-in, pretraining-off) ───────
1771
+ self.meap_structural_token_ids = (
1772
+ None
1773
+ if meap_structural_token_ids is None
1774
+ else tuple(int(token_id) for token_id in meap_structural_token_ids)
1775
+ )
1776
+ self.meap_protect_chat_headers = bool(meap_protect_chat_headers)
1777
+ self.meap_protect_ignored_labels = bool(meap_protect_ignored_labels)
1778
+ self.copy_exclude_structural_tokens = bool(copy_exclude_structural_tokens)
1779
+ self.copy_exclude_token_ids = (
1780
+ None
1781
+ if copy_exclude_token_ids is None
1782
+ else tuple(int(token_id) for token_id in copy_exclude_token_ids)
1783
+ )
1784
+ self.copy_exclude_chat_headers = bool(copy_exclude_chat_headers)
1785
+ self.copy_chat_im_start_token_id = int(copy_chat_im_start_token_id)
1786
+ self.copy_chat_im_end_token_id = int(copy_chat_im_end_token_id)
1787
+ self.copy_chat_newline_token_id = int(copy_chat_newline_token_id)
1788
+
1789
  self.auto_map = {
1790
  "AutoConfig": "configuration_neollm.NeoLLMConfig",
1791
  "AutoModel": "modeling_neollm.NeoLLMModel",
modeling_neollm.py CHANGED
@@ -196,6 +196,27 @@ try:
196
  except (ImportError, ModuleNotFoundError, AttributeError):
197
  pass
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  def _leviathan_config_supported(config) -> bool:
201
  """Check LEV shapes without depending on NeoLLM's optional dtype field."""
@@ -10228,7 +10249,11 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
10228
  raw-token representation for lexical copy keys. The K=1 path shares
10229
  the ordinary producer; no parameters or coordinate gradients are copied.
10230
  """
10231
- from cut_cross_entropy import pool_patch_inputs
 
 
 
 
10232
 
10233
  if input_ids.ndim != 2 or input_ids.dtype not in (torch.int32, torch.int64):
10234
  raise ValueError("Patch preparation requires integer [batch, raw_tokens] input IDs.")
@@ -10726,8 +10751,12 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
10726
  + self.siamese_y_final_norm(siamese_y_states)
10727
  )
10728
  else:
10729
- from cut_cross_entropy.siamesenorm import siamesenorm
10730
- hidden_states = siamesenorm(
 
 
 
 
10731
  hidden_states, siamese_y_states,
10732
  self.siamese_x_final_norm.weight, self.siamese_y_final_norm.weight,
10733
  self.siamese_final_norm.weight,
@@ -11018,6 +11047,7 @@ def compute_tweo_loss(
11018
  power: float,
11019
  eps: float,
11020
  attention_mask: Optional[torch.Tensor] = None,
 
11021
  ) -> torch.Tensor:
11022
  """
11023
  Transformers Without Extreme Outliers activation regularizer.
@@ -11038,6 +11068,18 @@ def compute_tweo_loss(
11038
  mask_weights = attention_mask.to(
11039
  device=block_activations[0].device, dtype=torch.float32
11040
  )
 
 
 
 
 
 
 
 
 
 
 
 
11041
  valid_count = mask_weights.sum().clamp_min(1.0)
11042
 
11043
  scale = float(tau) + float(eps)
@@ -12748,12 +12790,7 @@ class CopyPasteHead(nn.Module):
12748
  raise ValueError("Lexical copy features must match the raw source token domain.")
12749
  keys = keys + self.lexical_up(self.lexical_down(source_token_features))
12750
  query = self.query(hidden[:, :rows])
12751
- if hidden.is_cuda:
12752
- if not _CCE_COPY_PASTE_HAS_METRICS:
12753
- raise ImportError(
12754
- "CUDA Copy-Paste training requires a cut-cross-entropy installation "
12755
- "with Copy-Paste metric support. Update the CCE repository first."
12756
- )
12757
  selected = hidden[:, :rows]
12758
  gate = self.copy_gate(selected).squeeze(-1).float()
12759
  sink = torch.matmul(query.float(), self.sink_key.float()) * self.scale
@@ -13096,7 +13133,62 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13096
  def set_output_embeddings(self, new_embeddings):
13097
  self.lm_head = new_embeddings
13098
 
13099
- def _corrupt_meap_inputs(self, input_ids, attention_mask, meap_seed, *, return_mask):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13100
  """Corrupt raw IDs while preserving the configured structural tokens.
13101
 
13102
  The last valid position is removed before structural-token filtering so
@@ -13140,6 +13232,24 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13140
  for token_id in value if isinstance(value, (list, tuple)) else (value,):
13141
  if token_id is not None:
13142
  eligible = eligible & input_ids.ne(int(token_id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13143
  result = meap_mask_inputs(
13144
  input_ids, int(mask_token_id), enabled=True,
13145
  mask_ratio=float(getattr(self.config, "meap_mask_ratio", 0.15)),
@@ -13171,7 +13281,11 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13171
  lengths before the measured curriculum. Valid-count pooling preserves
13172
  partial patches; empty patches and padding targets are excluded.
13173
  """
13174
- from cut_cross_entropy import PatchTrainingSchedule
 
 
 
 
13175
 
13176
  schedule = PatchTrainingSchedule(0, target_slots)
13177
  # Reuse integer validation without accepting bool/floating K silently.
@@ -13246,6 +13360,10 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13246
  model_inputs: dict = {"input_ids": input_ids, "attention_mask": attention_mask}
13247
  if inputs_embeds is not None and past_key_values is None:
13248
  model_inputs["inputs_embeds"] = inputs_embeds
 
 
 
 
13249
  return model_inputs
13250
 
13251
  def forward(
@@ -13269,11 +13387,20 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13269
  copy_input_ids: Optional[torch.LongTensor] = None,
13270
  copy_attention_mask: Optional[torch.Tensor] = None,
13271
  copy_token_features: Optional[torch.Tensor] = None,
 
13272
  **kwargs: Unpack[TransformersKwargs],
13273
  ) -> CausalLMOutputWithPast:
13274
  self._last_meap_mask_fraction = None
13275
  self._last_meap_masked_tokens = None
13276
  self._last_meap_seed = None
 
 
 
 
 
 
 
 
13277
  copy_source_ids = copy_input_ids
13278
  copy_source_mask = copy_attention_mask
13279
  copy_source_features = copy_token_features
@@ -13304,7 +13431,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13304
  patch_size=raw_patch_size, target_slots=patch_target_slots,
13305
  meap_seed=meap_seed,
13306
  )
13307
- if self.copy_paste_head is not None:
13308
  copy_source_ids = prepared["copy_input_ids"]
13309
  copy_source_mask = prepared["copy_attention_mask"]
13310
  copy_source_features = prepared.get("copy_token_features")
@@ -13375,6 +13502,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13375
  input_ids, meap_selected_mask, meap_metrics, effective_meap_seed = self._corrupt_meap_inputs(
13376
  input_ids, attention_mask, meap_seed,
13377
  return_mask=bool(getattr(self.config, "use_mile_loss", False)),
 
13378
  )
13379
  eligible_count = meap_metrics[0]
13380
  masked_count = meap_metrics[1]
@@ -13384,12 +13512,17 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13384
  self._last_meap_masked_tokens = masked_count.detach()
13385
  self._last_meap_seed = effective_meap_seed.detach()
13386
 
13387
- if self.copy_paste_head is not None:
13388
  if input_ids is not None:
13389
- if copy_input_ids is not None or copy_attention_mask is not None:
13390
- raise ValueError("Copy-Paste uses the observed input_ids and attention_mask; do not supply separate copy inputs too.")
13391
  copy_source_ids = input_ids
13392
- copy_source_mask = attention_mask
 
 
 
 
 
13393
  elif not patch_training_enabled and copy_source_mask is None:
13394
  copy_source_mask = attention_mask
13395
  if copy_source_ids is None:
@@ -13407,6 +13540,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13407
  if meap_enabled and bool(getattr(self.config, "meap_exclude_mask_from_copy", True)):
13408
  # Use observed IDs only: never restore the clean target here.
13409
  copy_source_mask = copy_source_mask & copy_source_ids.ne(int(self.config.meap_mask_token_id))
 
13410
  core = inputs_embeds if inputs_embeds is not None else input_ids
13411
  core_length = core.shape[1]
13412
  if copy_source_ids.shape[0] != core.shape[0] or copy_source_ids.device != core.device:
@@ -13592,7 +13726,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13592
  self._last_stack_gate_effective_slots = None
13593
  self._last_total_loss = None
13594
  if labels is not None:
13595
- if self.copy_paste_head is not None:
13596
  targets = _prepare_lm_labels(labels, hidden_states.device, self.config.pad_token_id)
13597
  if not patch_training_enabled:
13598
  targets = targets[:, 1:].unsqueeze(-1)
@@ -13694,7 +13828,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13694
  patch_targets=patch_training_enabled,
13695
  mile_enabled=(self.ntp_loss_backend == "cce"
13696
  and bool(getattr(self.config, "use_mile_loss", False))),
13697
- vocab_size=(self.vocab_size if self.copy_paste_head is not None else None),
13698
  )
13699
  loss = ntp_loss
13700
 
@@ -13729,6 +13863,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
13729
  power=self.config.tweo_power,
13730
  eps=self.config.tweo_eps,
13731
  attention_mask=attention_mask,
 
13732
  )
13733
  # Keep the loss coefficient on the same CUDA graph as the loss.
13734
  # A Python float is lifted as a CPU scalar by AOTAutograd and can
@@ -14034,7 +14169,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
14034
  if isinstance(logits_to_keep, int)
14035
  else logits_to_keep
14036
  )
14037
- if self.copy_paste_head is not None:
14038
  positions = torch.arange(hidden_states.shape[1], device=hidden_states.device)[slice_indices].reshape(-1)
14039
  logits = self.copy_paste_head.logits(
14040
  hidden_states, copy_source_ids, copy_source_mask, positions, self.lm_head,
 
196
  except (ImportError, ModuleNotFoundError, AttributeError):
197
  pass
198
 
199
+ try:
200
+ from cut_cross_entropy import ( # type: ignore[import-not-found]
201
+ pool_patch_inputs as _cce_pool_patch_inputs,
202
+ )
203
+ except (ImportError, ModuleNotFoundError, AttributeError):
204
+ _cce_pool_patch_inputs = None
205
+
206
+ try:
207
+ from cut_cross_entropy import ( # type: ignore[import-not-found]
208
+ PatchTrainingSchedule as _CCE_PatchTrainingSchedule,
209
+ )
210
+ except (ImportError, ModuleNotFoundError, AttributeError):
211
+ _CCE_PatchTrainingSchedule = None
212
+
213
+ try:
214
+ from cut_cross_entropy.siamesenorm import ( # type: ignore[import-not-found]
215
+ siamesenorm as _cce_siamesenorm,
216
+ )
217
+ except (ImportError, ModuleNotFoundError, AttributeError):
218
+ _cce_siamesenorm = None
219
+
220
 
221
  def _leviathan_config_supported(config) -> bool:
222
  """Check LEV shapes without depending on NeoLLM's optional dtype field."""
 
10249
  raw-token representation for lexical copy keys. The K=1 path shares
10250
  the ordinary producer; no parameters or coordinate gradients are copied.
10251
  """
10252
+ if _cce_pool_patch_inputs is None:
10253
+ raise ImportError(
10254
+ "Patch preparation requires `cut_cross_entropy` (`pool_patch_inputs`)."
10255
+ )
10256
+ pool_patch_inputs = _cce_pool_patch_inputs
10257
 
10258
  if input_ids.ndim != 2 or input_ids.dtype not in (torch.int32, torch.int64):
10259
  raise ValueError("Patch preparation requires integer [batch, raw_tokens] input IDs.")
 
10751
  + self.siamese_y_final_norm(siamese_y_states)
10752
  )
10753
  else:
10754
+ if _cce_siamesenorm is None:
10755
+ raise ImportError(
10756
+ f"SiameseNorm backend {norm_backend!r} requires `cut_cross_entropy.siamesenorm`; "
10757
+ "use `siamesenorm_kernel_backend='reference'` or install `cut-cross-entropy`."
10758
+ )
10759
+ hidden_states = _cce_siamesenorm(
10760
  hidden_states, siamese_y_states,
10761
  self.siamese_x_final_norm.weight, self.siamese_y_final_norm.weight,
10762
  self.siamese_final_norm.weight,
 
11047
  power: float,
11048
  eps: float,
11049
  attention_mask: Optional[torch.Tensor] = None,
11050
+ labels: Optional[torch.Tensor] = None,
11051
  ) -> torch.Tensor:
11052
  """
11053
  Transformers Without Extreme Outliers activation regularizer.
 
11068
  mask_weights = attention_mask.to(
11069
  device=block_activations[0].device, dtype=torch.float32
11070
  )
11071
+ if (
11072
+ labels is not None
11073
+ and labels.ndim == 2
11074
+ and labels.shape == block_activations[0].shape[:2]
11075
+ ):
11076
+ label_weights = labels.ne(-100).to(
11077
+ device=block_activations[0].device, dtype=torch.float32
11078
+ )
11079
+ mask_weights = (
11080
+ label_weights if mask_weights is None else mask_weights * label_weights
11081
+ )
11082
+ if mask_weights is not None:
11083
  valid_count = mask_weights.sum().clamp_min(1.0)
11084
 
11085
  scale = float(tau) + float(eps)
 
12790
  raise ValueError("Lexical copy features must match the raw source token domain.")
12791
  keys = keys + self.lexical_up(self.lexical_down(source_token_features))
12792
  query = self.query(hidden[:, :rows])
12793
+ if hidden.is_cuda and _CCE_COPY_PASTE_HAS_METRICS:
 
 
 
 
 
12794
  selected = hidden[:, :rows]
12795
  gate = self.copy_gate(selected).squeeze(-1).float()
12796
  sink = torch.matmul(query.float(), self.sink_key.float()) * self.scale
 
13133
  def set_output_embeddings(self, new_embeddings):
13134
  self.lm_head = new_embeddings
13135
 
13136
+ def _build_chat_header_mask(
13137
+ self,
13138
+ token_ids: torch.Tensor,
13139
+ im_start_id: int,
13140
+ im_end_id: int,
13141
+ newline_id: int,
13142
+ ) -> torch.Tensor:
13143
+ seq_len = token_ids.shape[1]
13144
+ is_start = token_ids.eq(im_start_id)
13145
+ is_end = token_ids.eq(im_end_id)
13146
+ header = is_start | is_end
13147
+ if seq_len > 1:
13148
+ is_nl = token_ids.eq(newline_id)
13149
+ after_start = F.pad(is_start[:, :-1], (1, 0), value=False)
13150
+ after_end_nl = F.pad(is_end[:, :-1], (1, 0), value=False) & is_nl
13151
+ header = header | after_start | after_end_nl
13152
+ if seq_len > 2:
13153
+ after_start_nl = (
13154
+ F.pad(is_start[:, :-2], (2, 0), value=False)
13155
+ & token_ids.eq(newline_id)
13156
+ )
13157
+ header = header | after_start_nl
13158
+ return header
13159
+
13160
+ def _apply_copy_source_exclusions(
13161
+ self,
13162
+ copy_source_ids: torch.LongTensor,
13163
+ copy_source_mask: torch.Tensor,
13164
+ ) -> torch.Tensor:
13165
+ if bool(getattr(self.config, "copy_exclude_structural_tokens", False)):
13166
+ exclude_ids = getattr(self.config, "copy_exclude_token_ids", None)
13167
+ if exclude_ids is None:
13168
+ exclude_ids = tuple(
13169
+ int(token_id)
13170
+ for value in (
13171
+ getattr(self.config, "pad_token_id", None),
13172
+ getattr(self.config, "bos_token_id", None),
13173
+ getattr(self.config, "eos_token_id", None),
13174
+ getattr(self.config, "meap_mask_token_id", None),
13175
+ )
13176
+ for token_id in (value if isinstance(value, (list, tuple)) else (value,))
13177
+ if token_id is not None
13178
+ )
13179
+ for token_id in exclude_ids:
13180
+ copy_source_mask = copy_source_mask & copy_source_ids.ne(int(token_id))
13181
+ if bool(getattr(self.config, "copy_exclude_chat_headers", False)):
13182
+ header_mask = self._build_chat_header_mask(
13183
+ copy_source_ids,
13184
+ int(getattr(self.config, "copy_chat_im_start_token_id", 6)),
13185
+ int(getattr(self.config, "copy_chat_im_end_token_id", 7)),
13186
+ int(getattr(self.config, "copy_chat_newline_token_id", 708)),
13187
+ )
13188
+ copy_source_mask = copy_source_mask & (~header_mask)
13189
+ return copy_source_mask
13190
+
13191
+ def _corrupt_meap_inputs(self, input_ids, attention_mask, meap_seed, *, return_mask, labels=None):
13192
  """Corrupt raw IDs while preserving the configured structural tokens.
13193
 
13194
  The last valid position is removed before structural-token filtering so
 
13232
  for token_id in value if isinstance(value, (list, tuple)) else (value,):
13233
  if token_id is not None:
13234
  eligible = eligible & input_ids.ne(int(token_id))
13235
+ extra_structural = getattr(self.config, "meap_structural_token_ids", None)
13236
+ if extra_structural is not None:
13237
+ for token_id in extra_structural:
13238
+ eligible = eligible & input_ids.ne(int(token_id))
13239
+ if bool(getattr(self.config, "meap_protect_chat_headers", False)):
13240
+ header_mask = self._build_chat_header_mask(
13241
+ input_ids,
13242
+ int(getattr(self.config, "copy_chat_im_start_token_id", 6)),
13243
+ int(getattr(self.config, "copy_chat_im_end_token_id", 7)),
13244
+ int(getattr(self.config, "copy_chat_newline_token_id", 708)),
13245
+ )
13246
+ eligible = eligible & (~header_mask)
13247
+ if (
13248
+ bool(getattr(self.config, "meap_protect_ignored_labels", False))
13249
+ and labels is not None
13250
+ and labels.shape == input_ids.shape
13251
+ ):
13252
+ eligible = eligible & labels.ne(-100)
13253
  result = meap_mask_inputs(
13254
  input_ids, int(mask_token_id), enabled=True,
13255
  mask_ratio=float(getattr(self.config, "meap_mask_ratio", 0.15)),
 
13281
  lengths before the measured curriculum. Valid-count pooling preserves
13282
  partial patches; empty patches and padding targets are excluded.
13283
  """
13284
+ if _CCE_PatchTrainingSchedule is None:
13285
+ raise ImportError(
13286
+ "Patch batch preparation requires `cut_cross_entropy` (`PatchTrainingSchedule`)."
13287
+ )
13288
+ PatchTrainingSchedule = _CCE_PatchTrainingSchedule
13289
 
13290
  schedule = PatchTrainingSchedule(0, target_slots)
13291
  # Reuse integer validation without accepting bool/floating K silently.
 
13360
  model_inputs: dict = {"input_ids": input_ids, "attention_mask": attention_mask}
13361
  if inputs_embeds is not None and past_key_values is None:
13362
  model_inputs["inputs_embeds"] = inputs_embeds
13363
+ if "use_copy_paste" in kwargs and kwargs["use_copy_paste"] is not None:
13364
+ model_inputs["use_copy_paste"] = kwargs["use_copy_paste"]
13365
+ if "copy_attention_mask" in kwargs and kwargs["copy_attention_mask"] is not None:
13366
+ model_inputs["copy_attention_mask"] = kwargs["copy_attention_mask"]
13367
  return model_inputs
13368
 
13369
  def forward(
 
13387
  copy_input_ids: Optional[torch.LongTensor] = None,
13388
  copy_attention_mask: Optional[torch.Tensor] = None,
13389
  copy_token_features: Optional[torch.Tensor] = None,
13390
+ use_copy_paste: Optional[bool] = None,
13391
  **kwargs: Unpack[TransformersKwargs],
13392
  ) -> CausalLMOutputWithPast:
13393
  self._last_meap_mask_fraction = None
13394
  self._last_meap_masked_tokens = None
13395
  self._last_meap_seed = None
13396
+ active_copy_paste = (
13397
+ self.copy_paste_head is not None
13398
+ and (
13399
+ bool(getattr(self.config, "use_copy_paste", True))
13400
+ if use_copy_paste is None
13401
+ else bool(use_copy_paste)
13402
+ )
13403
+ )
13404
  copy_source_ids = copy_input_ids
13405
  copy_source_mask = copy_attention_mask
13406
  copy_source_features = copy_token_features
 
13431
  patch_size=raw_patch_size, target_slots=patch_target_slots,
13432
  meap_seed=meap_seed,
13433
  )
13434
+ if active_copy_paste:
13435
  copy_source_ids = prepared["copy_input_ids"]
13436
  copy_source_mask = prepared["copy_attention_mask"]
13437
  copy_source_features = prepared.get("copy_token_features")
 
13502
  input_ids, meap_selected_mask, meap_metrics, effective_meap_seed = self._corrupt_meap_inputs(
13503
  input_ids, attention_mask, meap_seed,
13504
  return_mask=bool(getattr(self.config, "use_mile_loss", False)),
13505
+ labels=labels,
13506
  )
13507
  eligible_count = meap_metrics[0]
13508
  masked_count = meap_metrics[1]
 
13512
  self._last_meap_masked_tokens = masked_count.detach()
13513
  self._last_meap_seed = effective_meap_seed.detach()
13514
 
13515
+ if active_copy_paste:
13516
  if input_ids is not None:
13517
+ if copy_input_ids is not None:
13518
+ raise ValueError("Copy-Paste uses the observed input_ids; do not supply separate copy_input_ids too.")
13519
  copy_source_ids = input_ids
13520
+ if copy_attention_mask is None:
13521
+ copy_source_mask = attention_mask
13522
+ elif attention_mask is None:
13523
+ copy_source_mask = copy_attention_mask
13524
+ else:
13525
+ copy_source_mask = attention_mask.to(dtype=torch.bool) & copy_attention_mask.to(dtype=torch.bool)
13526
  elif not patch_training_enabled and copy_source_mask is None:
13527
  copy_source_mask = attention_mask
13528
  if copy_source_ids is None:
 
13540
  if meap_enabled and bool(getattr(self.config, "meap_exclude_mask_from_copy", True)):
13541
  # Use observed IDs only: never restore the clean target here.
13542
  copy_source_mask = copy_source_mask & copy_source_ids.ne(int(self.config.meap_mask_token_id))
13543
+ copy_source_mask = self._apply_copy_source_exclusions(copy_source_ids, copy_source_mask)
13544
  core = inputs_embeds if inputs_embeds is not None else input_ids
13545
  core_length = core.shape[1]
13546
  if copy_source_ids.shape[0] != core.shape[0] or copy_source_ids.device != core.device:
 
13726
  self._last_stack_gate_effective_slots = None
13727
  self._last_total_loss = None
13728
  if labels is not None:
13729
+ if active_copy_paste:
13730
  targets = _prepare_lm_labels(labels, hidden_states.device, self.config.pad_token_id)
13731
  if not patch_training_enabled:
13732
  targets = targets[:, 1:].unsqueeze(-1)
 
13828
  patch_targets=patch_training_enabled,
13829
  mile_enabled=(self.ntp_loss_backend == "cce"
13830
  and bool(getattr(self.config, "use_mile_loss", False))),
13831
+ vocab_size=(self.vocab_size if active_copy_paste else None),
13832
  )
13833
  loss = ntp_loss
13834
 
 
13863
  power=self.config.tweo_power,
13864
  eps=self.config.tweo_eps,
13865
  attention_mask=attention_mask,
13866
+ labels=None if patch_training_enabled else labels,
13867
  )
13868
  # Keep the loss coefficient on the same CUDA graph as the loss.
13869
  # A Python float is lifted as a CPU scalar by AOTAutograd and can
 
14169
  if isinstance(logits_to_keep, int)
14170
  else logits_to_keep
14171
  )
14172
+ if active_copy_paste:
14173
  positions = torch.arange(hidden_states.shape[1], device=hidden_states.device)[slice_indices].reshape(-1)
14174
  logits = self.copy_paste_head.logits(
14175
  hidden_states, copy_source_ids, copy_source_mask, positions, self.lm_head,