File size: 5,902 Bytes
3bbd5dd | 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 | """Joint training loop for the MTP stack and its NTP control.
Both stacks read the same frozen-backbone hidden states, so the backbone
forward pass is computed once per batch and shared. They own disjoint
parameter sets and disjoint optimizers, so sharing that forward pass cannot
couple their gradients -- the control stays a control.
Per-head backward passes are taken one head at a time rather than on a
summed loss. The vocabulary projection is the memory cost here (a
(batch, seq, 128256) fp32 logit tensor per head), and stepping head by head
keeps only one such tensor alive instead of n_heads of them, which is what
makes batch x seq of any useful size fit an 11GB card.
"""
import logging
import time
from dataclasses import dataclass, field
import torch
import torch.nn as nn
from src.train.model import MTPStack
logger = logging.getLogger(__name__)
LOG_EVERY_STEPS = 50
@dataclass
class TrainMetrics:
"""Running training summary.
Attributes:
steps: optimizer steps taken.
tokens: training tokens consumed (batch_size * seq_len per step).
mtp_head_losses: mean cross-entropy per MTP head, in nats.
ntp_loss: mean cross-entropy for the control head, in nats.
wall_seconds: wall-clock training time.
tokens_per_second: tokens divided by wall_seconds.
"""
steps: int = 0
tokens: int = 0
mtp_head_losses: list = field(default_factory=list)
ntp_loss: float = 0.0
wall_seconds: float = 0.0
tokens_per_second: float = 0.0
def _shifted_loss(logits: torch.Tensor, input_ids: torch.Tensor, offset: int, loss_fn: nn.Module) -> torch.Tensor:
"""Cross-entropy for predicting the token `offset` positions ahead.
A head reading position t predicts input_ids[t + offset], so the last
`offset` positions have no target and are dropped. Returns a scalar in
nats.
Args:
logits: (batch, seq, vocab) from one head over the full block.
input_ids: (batch, seq) the block's token ids.
offset: prediction distance, >= 1.
"""
if offset >= input_ids.shape[1]:
raise ValueError(f"offset {offset} exceeds sequence length {input_ids.shape[1]}")
used = logits[:, : logits.shape[1] - offset, :]
targets = input_ids[:, offset:]
return loss_fn(used.reshape(-1, used.shape[-1]), targets.reshape(-1))
def train_step(
hidden_states: torch.Tensor,
input_ids: torch.Tensor,
mtp: MTPStack,
ntp: MTPStack,
mtp_optimizer: torch.optim.Optimizer,
ntp_optimizer: torch.optim.Optimizer,
loss_fn: nn.Module,
) -> tuple:
"""One optimizer step for both stacks off a shared frozen hidden-state tensor.
hidden_states must already be detached from the backbone; both stacks
treat it as a constant input.
Returns:
(per-head MTP losses as floats, NTP loss as float).
"""
mtp_optimizer.zero_grad(set_to_none=True)
mtp_trunk = mtp.trunk_states(hidden_states)
head_losses = []
for k in range(mtp.n_heads):
logits = mtp.head_logits(mtp_trunk, k)
loss = _shifted_loss(logits, input_ids, k + 1, loss_fn)
# retain the trunk graph until the final head has contributed its
# gradient; freeing each head's logits between backwards is the point
loss.backward(retain_graph=(k < mtp.n_heads - 1))
head_losses.append(float(loss.detach()))
del logits, loss
mtp_optimizer.step()
ntp_optimizer.zero_grad(set_to_none=True)
ntp_trunk = ntp.trunk_states(hidden_states)
ntp_logits = ntp.head_logits(ntp_trunk, 0)
ntp_loss = _shifted_loss(ntp_logits, input_ids, 1, loss_fn)
ntp_loss.backward()
ntp_optimizer.step()
ntp_value = float(ntp_loss.detach())
del ntp_logits, ntp_loss
return head_losses, ntp_value
def train(
backbone,
mtp: MTPStack,
ntp: MTPStack,
batches,
device: str,
learning_rate: float,
max_steps: int,
) -> TrainMetrics:
"""Run the joint training loop and return summary metrics.
Args:
backbone: the frozen causal LM; only its trunk (`.model`) is called.
mtp: the multi-head stack under test.
ntp: the single-head control stack.
batches: iterable of (batch, seq) LongTensors.
learning_rate: AdamW learning rate, identical for both stacks.
max_steps: cap on optimizer steps.
"""
mtp_optimizer = torch.optim.AdamW(mtp.trainable_parameters(), lr=learning_rate)
ntp_optimizer = torch.optim.AdamW(ntp.trainable_parameters(), lr=learning_rate)
loss_fn = nn.CrossEntropyLoss()
metrics = TrainMetrics(mtp_head_losses=[0.0] * mtp.n_heads)
running_mtp = [0.0] * mtp.n_heads
running_ntp = 0.0
start = time.perf_counter()
for step, block in enumerate(batches):
if step >= max_steps:
break
block = block.to(device)
with torch.no_grad():
hidden = backbone.model(input_ids=block).last_hidden_state
hidden = hidden.detach()
head_losses, ntp_value = train_step(hidden, block, mtp, ntp, mtp_optimizer, ntp_optimizer, loss_fn)
running_mtp = [r + l for r, l in zip(running_mtp, head_losses)]
running_ntp += ntp_value
metrics.steps = step + 1
metrics.tokens += block.numel()
if (step + 1) % LOG_EVERY_STEPS == 0:
elapsed = time.perf_counter() - start
logger.info(
"step %d tokens %d mtp_h1 %.4f ntp %.4f %.0f tok/s",
step + 1, metrics.tokens, head_losses[0], ntp_value, metrics.tokens / elapsed,
)
metrics.wall_seconds = time.perf_counter() - start
metrics.tokens_per_second = metrics.tokens / metrics.wall_seconds if metrics.wall_seconds else 0.0
if metrics.steps:
metrics.mtp_head_losses = [r / metrics.steps for r in running_mtp]
metrics.ntp_loss = running_ntp / metrics.steps
return metrics
|