Update code/model.py with chunked cross-entropy and H200 turbo speed optimizations
Browse files174 unmodified lines175176177178179180181182183184185186187188189190191192193194195196197198174 unmodified lineselse:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)logits = self.head(x)loss = Noneif targets is not None:# BUG 1 FIX: Explicit shift_labels flag supportif shift_labels:shift_logits = logits[..., :-1, :].contiguous()shift_targets = targets[..., 1:].contiguous()loss = F.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_targets.view(-1), ignore_index=-100)else:# Targets are already pre-shifted (e.g. pretraining ShardPool y = tokens[i+1:])loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)# z-loss: stabilizes logit magnitudes during pretraining; disable for SFT (z_loss_weight=0)if self.cfg.z_loss_weight > 0:z_loss = self.cfg.z_loss_weight * (torch.logsumexp(logits, dim=-1) ** 2).mean()loss = loss + z_lossreturn logits, lossdef num_params(self):174 unmodified lines175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229174 unmodified lineselse:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)# =====================================================================# ⚡ Chunked Cross-Entropy: Compute loss in 512-token chunks to avoid# materializing the full [B, T, V=64003] logits tensor (~16 GB).# Mathematically IDENTICAL to standard CE. Saves ~12 GB VRAM.# =====================================================================loss = Noneif targets is not None:V = self.cfg.vocab_sizece_chunk = 512 # tokens per chunkif shift_labels:# Shifted: predict token[i+1] from hidden[i]hidden = x[:, :-1, :].contiguous() # [B, T-1, D]tgt = targets[:, 1:].contiguous() # [B, T-1]else:hidden = xtgt = targetstotal_loss = torch.zeros(1, device=x.device, dtype=torch.float32)total_active = 0seq_len = hidden.size(1)for i in range(0, seq_len, ce_chunk):end = min(i + ce_chunk, seq_len)chunk_logits = self.head(hidden[:, i:end, :]) # [B, chunk, V]chunk_tgt = tgt[:, i:end] # [B, chunk]chunk_loss = F.cross_entropy(chunk_logits.view(-1, V), chunk_tgt.view(-1),ignore_index=-100, reduction="sum")chunk_active = (chunk_tgt != -100).sum().item()total_loss = total_loss + chunk_losstotal_active += chunk_activeloss = total_loss / max(1, total_active)# z-loss: stabilizes logit magnitudes during pretraining; disable for SFT (z_loss_weight=0)if self.cfg.z_loss_weight > 0:logits_full = self.head(x)z_loss = self.cfg.z_loss_weight * (torch.logsumexp(logits_full, dim=-1) ** 2).mean()loss = loss + z_loss# During training, return None logits to save ~16 GB VRAM# Caller must NOT use logits when targets are providedreturn None, loss# Inference path: return full logits for generationlogits = self.head(x)return logits, lossdef num_params(self):
code/model.py+39-8