Download src/train/trainer.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 5.9 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/src/train/trainer.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/src/train/trainer.py
-
curl -L -o trainer.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/src/train/trainer.py
5.9 kB
| """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 | |
| 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 | |