KitsuVp commited on
Commit
59581fd
·
verified ·
1 Parent(s): bf92288

Update modeling_neollm.py

Browse files
Files changed (1) hide show
  1. modeling_neollm.py +51 -21
modeling_neollm.py CHANGED
@@ -1365,7 +1365,10 @@ def infer_key_validity(
1365
  if attention_mask.shape[-2] != seq_len or attention_mask.shape[-1] != seq_len:
1366
  return None
1367
  diag = attention_mask.diagonal(dim1=-2, dim2=-1)
1368
- valid = torch.isfinite(diag) & (diag == 0)
 
 
 
1369
  if valid.shape[1] == 1 and num_heads != 1:
1370
  valid = valid.expand(-1, num_heads, -1)
1371
  elif valid.shape[1] != num_heads:
@@ -1405,7 +1408,8 @@ def _expand_pair_valid_mask(
1405
  if attention_mask.shape[-2] < query_len or attention_mask.shape[-1] < key_len:
1406
  return None
1407
 
1408
- valid = attention_mask[:, :, :query_len, :key_len] == 0
 
1409
  if valid.shape[1] == 1 and num_heads != 1:
1410
  valid = valid.expand(-1, num_heads, -1, -1)
1411
  elif valid.shape[1] != num_heads:
@@ -3255,6 +3259,7 @@ class NeoLLMAttention(nn.Module):
3255
  dropout: float,
3256
  S_orig: int,
3257
  position_ids: Optional[torch.Tensor],
 
3258
  ) -> Tuple[torch.Tensor, None]:
3259
  """
3260
  Flash attention for the IHA seq-expand path (P>1).
@@ -3266,10 +3271,13 @@ class NeoLLMAttention(nn.Module):
3266
  • attention_mask→additive-mask conversion that HF injects (unsupported
3267
  for seq length S·P when the mask is shaped for S)
3268
 
3269
- Calls flash_attn_func (dense path) or flash_attn_varlen_func (packed
3270
- path) directly. Affine-Scaled Attention is also computed inline here
3271
- so that Term 2 sums V over the same valid keys as flash attention on
3272
- the S·P expanded sequence.
 
 
 
3273
 
3274
  Packing detection
3275
  -----------------
@@ -3333,12 +3341,11 @@ class NeoLLMAttention(nn.Module):
3333
 
3334
  # ── Packing detection ─────────────────────────────────────────────────
3335
  # Packing: batch_size==1 and position_ids contains document-boundary
3336
- # resets (non-monotonic positions). Mirrors HF _is_packed_sequence.
3337
- #
3338
- # position_ids may be 3-D [1, S, k] from some trainers; normalise to
3339
- # 1-D [S] for the monotonicity check by taking the first column.
3340
  _pos_for_pack = None
3341
- if position_ids is not None and B == 1:
3342
  _p = position_ids[0] # [S] or [S, k]
3343
  if _p.dim() > 1:
3344
  _p = _p[:, 0] # [S] — take sequential index column
@@ -3347,8 +3354,10 @@ class NeoLLMAttention(nn.Module):
3347
  # .all().item() would break the compiled graph; use bool() which Dynamo
3348
  # can evaluate at trace time when the tensor is a compile-time constant,
3349
  # and falls back to a graph-break-free path otherwise.
3350
- is_packed = _pos_for_pack is not None and not bool(
3351
- (torch.diff(_pos_for_pack.float()) >= 0).all()
 
 
3352
  )
3353
 
3354
  # ── Packed / varlen path ──────────────────────────────────────────────
@@ -3366,7 +3375,7 @@ class NeoLLMAttention(nn.Module):
3366
  )
3367
  doc_starts = boundaries.nonzero(as_tuple=False).squeeze(1) # indices
3368
  doc_lengths = torch.diff(
3369
- torch.cat([doc_starts, torch.tensor([S_orig], device=pos0.device)])
3370
  ) # [num_docs]
3371
  # Scale each document length by P for the expanded sequence.
3372
  doc_lengths_p = doc_lengths * P # [num_docs]
@@ -3377,7 +3386,7 @@ class NeoLLMAttention(nn.Module):
3377
 
3378
  max_seqlen_p = int(doc_lengths_p.max().item())
3379
 
3380
- # Flatten batch dim (B=1 for packing): [1, S·P, H, d] → [S·P, H, d]
3381
  q_flat = q_fa.squeeze(0)
3382
  k_flat = k_fa.squeeze(0)
3383
  v_flat = v_fa.squeeze(0)
@@ -3850,6 +3859,7 @@ class NeoLLMAttention(nn.Module):
3850
  dropout=0.0 if not self.training else self.attention_dropout,
3851
  S_orig=_S_orig,
3852
  position_ids=position_ids,
 
3853
  )
3854
  elif use_affine:
3855
  if self.config._attn_implementation == "eager":
@@ -5339,9 +5349,13 @@ class NeoLLMModel(NeoLLMPreTrainedModel):
5339
  inputs_embeds = self.spelling_bee(input_ids, inputs_embeds)
5340
 
5341
  if position_ids is None:
5342
- position_ids = torch.arange(
5343
- 0, inputs_embeds.shape[1], device=inputs_embeds.device
5344
- ).unsqueeze(0)
 
 
 
 
5345
 
5346
  causal_mask = create_causal_mask(
5347
  config=self.config,
@@ -5663,6 +5677,7 @@ def compute_tweo_loss(
5663
  tau: float,
5664
  power: float,
5665
  eps: float,
 
5666
  ) -> torch.Tensor:
5667
  """
5668
  Transformers Without Extreme Outliers activation regularizer.
@@ -5670,16 +5685,30 @@ def compute_tweo_loss(
5670
  Liang et al. (2026) apply a scaled Lp penalty to the final output
5671
  activations of every Transformer block. The penalty is intentionally
5672
  smooth rather than hinge-thresholded, so normal activations remain cheap
5673
- while extreme outliers become expensive.
 
 
5674
  """
5675
  if not block_activations:
5676
  raise ValueError("TWEO requires at least one Transformer block activation.")
5677
 
 
 
 
 
 
 
 
 
5678
  scale = float(tau) + float(eps)
5679
  total = block_activations[0].new_zeros((), dtype=torch.float32)
5680
  for activation in block_activations:
5681
- scaled = activation.float().abs() / scale
5682
- total = total + scaled.pow(float(power)).mean()
 
 
 
 
5683
  return total / len(block_activations)
5684
 
5685
 
@@ -6123,6 +6152,7 @@ class NeoLLMForCausalLM(NeoLLMPreTrainedModel, GenerationMixin):
6123
  tau=self.config.tweo_tau,
6124
  power=self.config.tweo_power,
6125
  eps=self.config.tweo_eps,
 
6126
  )
6127
  loss = loss + self.config.tweo_loss_weight * tweo_loss
6128
 
 
1365
  if attention_mask.shape[-2] != seq_len or attention_mask.shape[-1] != seq_len:
1366
  return None
1367
  diag = attention_mask.diagonal(dim1=-2, dim2=-1)
1368
+ if attention_mask.dtype == torch.bool:
1369
+ valid = diag
1370
+ else:
1371
+ valid = torch.isfinite(diag) & (diag == 0)
1372
  if valid.shape[1] == 1 and num_heads != 1:
1373
  valid = valid.expand(-1, num_heads, -1)
1374
  elif valid.shape[1] != num_heads:
 
1408
  if attention_mask.shape[-2] < query_len or attention_mask.shape[-1] < key_len:
1409
  return None
1410
 
1411
+ mask = attention_mask[:, :, :query_len, :key_len]
1412
+ valid = mask if mask.dtype == torch.bool else mask == 0
1413
  if valid.shape[1] == 1 and num_heads != 1:
1414
  valid = valid.expand(-1, num_heads, -1, -1)
1415
  elif valid.shape[1] != num_heads:
 
3259
  dropout: float,
3260
  S_orig: int,
3261
  position_ids: Optional[torch.Tensor],
3262
+ attention_mask: Optional[torch.Tensor] = None,
3263
  ) -> Tuple[torch.Tensor, None]:
3264
  """
3265
  Flash attention for the IHA seq-expand path (P>1).
 
3271
  • attention_mask→additive-mask conversion that HF injects (unsupported
3272
  for seq length S·P when the mask is shaped for S)
3273
 
3274
+ Calls flash_attn_func on the dense fixed-shape path, or
3275
+ flash_attn_varlen_func only for true packed sequences without a padding
3276
+ mask. Right padding must not change IHA topology during fixed-length
3277
+ training; padding is handled by position ids and masked losses instead.
3278
+ Affine-Scaled Attention is also computed inline here so that Term 2
3279
+ sums V over the same causal keys as flash attention on the S·P expanded
3280
+ sequence.
3281
 
3282
  Packing detection
3283
  -----------------
 
3341
 
3342
  # ── Packing detection ─────────────────────────────────────────────────
3343
  # Packing: batch_size==1 and position_ids contains document-boundary
3344
+ # resets (non-monotonic positions). When attention_mask is present we
3345
+ # keep the dense fixed-shape path: right padding should affect losses and
3346
+ # position ids, not IHA topology or compiled tensor shapes.
 
3347
  _pos_for_pack = None
3348
+ if position_ids is not None and B == 1 and attention_mask is None:
3349
  _p = position_ids[0] # [S] or [S, k]
3350
  if _p.dim() > 1:
3351
  _p = _p[:, 0] # [S] — take sequential index column
 
3354
  # .all().item() would break the compiled graph; use bool() which Dynamo
3355
  # can evaluate at trace time when the tensor is a compile-time constant,
3356
  # and falls back to a graph-break-free path otherwise.
3357
+ is_packed = (
3358
+ _pos_for_pack is not None
3359
+ and _pos_for_pack.numel() > 1
3360
+ and not bool((torch.diff(_pos_for_pack.float()) >= 0).all())
3361
  )
3362
 
3363
  # ── Packed / varlen path ──────────────────────────────────────────────
 
3375
  )
3376
  doc_starts = boundaries.nonzero(as_tuple=False).squeeze(1) # indices
3377
  doc_lengths = torch.diff(
3378
+ torch.cat([doc_starts, torch.tensor([pos0.numel()], device=pos0.device)])
3379
  ) # [num_docs]
3380
  # Scale each document length by P for the expanded sequence.
3381
  doc_lengths_p = doc_lengths * P # [num_docs]
 
3386
 
3387
  max_seqlen_p = int(doc_lengths_p.max().item())
3388
 
3389
+ # Flatten batch dim (B=1 for packing): [1, S·P, H, d] -> [S·P, H, d]
3390
  q_flat = q_fa.squeeze(0)
3391
  k_flat = k_fa.squeeze(0)
3392
  v_flat = v_fa.squeeze(0)
 
3859
  dropout=0.0 if not self.training else self.attention_dropout,
3860
  S_orig=_S_orig,
3861
  position_ids=position_ids,
3862
+ attention_mask=attention_mask,
3863
  )
3864
  elif use_affine:
3865
  if self.config._attn_implementation == "eager":
 
5349
  inputs_embeds = self.spelling_bee(input_ids, inputs_embeds)
5350
 
5351
  if position_ids is None:
5352
+ if attention_mask is not None:
5353
+ position_ids = attention_mask.to(dtype=torch.long).cumsum(-1) - 1
5354
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
5355
+ else:
5356
+ position_ids = torch.arange(
5357
+ 0, inputs_embeds.shape[1], device=inputs_embeds.device
5358
+ ).unsqueeze(0)
5359
 
5360
  causal_mask = create_causal_mask(
5361
  config=self.config,
 
5677
  tau: float,
5678
  power: float,
5679
  eps: float,
5680
+ attention_mask: Optional[torch.Tensor] = None,
5681
  ) -> torch.Tensor:
5682
  """
5683
  Transformers Without Extreme Outliers activation regularizer.
 
5685
  Liang et al. (2026) apply a scaled Lp penalty to the final output
5686
  activations of every Transformer block. The penalty is intentionally
5687
  smooth rather than hinge-thresholded, so normal activations remain cheap
5688
+ while extreme outliers become expensive. Padding tokens are excluded when
5689
+ an attention mask is available; this keeps the regularizer aligned with
5690
+ the causal LM and auxiliary losses without changing tensor shapes.
5691
  """
5692
  if not block_activations:
5693
  raise ValueError("TWEO requires at least one Transformer block activation.")
5694
 
5695
+ mask_weights = None
5696
+ valid_count = None
5697
+ if attention_mask is not None:
5698
+ mask_weights = attention_mask.to(
5699
+ device=block_activations[0].device, dtype=torch.float32
5700
+ )
5701
+ valid_count = mask_weights.sum().clamp_min(1.0)
5702
+
5703
  scale = float(tau) + float(eps)
5704
  total = block_activations[0].new_zeros((), dtype=torch.float32)
5705
  for activation in block_activations:
5706
+ penalty = (activation.float().abs() / scale).pow(float(power))
5707
+ if mask_weights is None:
5708
+ total = total + penalty.mean()
5709
+ else:
5710
+ token_penalty = penalty.mean(dim=-1)
5711
+ total = total + (token_penalty * mask_weights).sum() / valid_count
5712
  return total / len(block_activations)
5713
 
5714
 
 
6152
  tau=self.config.tweo_tau,
6153
  power=self.config.tweo_power,
6154
  eps=self.config.tweo_eps,
6155
+ attention_mask=attention_mask,
6156
  )
6157
  loss = loss + self.config.tweo_loss_weight * tweo_loss
6158