Fix Rank-3 OOM bias, RMSNorm BF16, RoPE optimization, causal mask & DDP sync bugs
Browse files13 unmodified lines14151617181920212 unmodified lines24252627282930313233343536373839 unmodified lines78798081828384105 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521668 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931045 unmodified lines35635735835936036136236322 unmodified lines38638738838939039139239339413 unmodified linesdef forward(self, x):x_fp32 = x.float()norm = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)# Optimized: removed redundant self.weight.float() cast for bfloat16/float16 throughputreturn (norm * self.weight).type_as(x)def precompute_rope(head_dim, max_len, theta=10000.0, device="cpu"):freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))2 unmodified linesreturn torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin, start_pos=0):cos = cos.to(x.dtype)sin = sin.to(x.dtype)x1, x2 = x[..., ::2], x[..., 1::2]# x is [B, n_heads, T, head_dim]# cos, sin are [max_len, head_dim//2]T = x.size(2)cos = cos[start_pos:start_pos + T][None, None, :, :]sin = sin[start_pos:start_pos + T][None, None, :, :]rotated = torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)return rotated.flatten(-2)def repeat_kv(x, n_rep):39 unmodified linesnew_cache = Nonedropout_p = self.attn_dropout if self.training else 0.0is_causal = (attn_mask is None) and (T > 1)try:if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p, enable_gqa=True)105 unmodified linesnoise = torch.zeros_like(x).uniform_(-1.0, 1.0) * mag * special_maskx = x + noisecos = self.rope_cos.to(x.device)sin = self.rope_sin.to(x.device)# FIXED: Do NOT mask pad_id (64002 / <|endofturn|>) in Causal LM!# In a right-padded Causal LM with -100 label masking, is_causal=True naturally# prevents real tokens from attending to right-side pads, while allowing tokens# to attend to in-prompt <|endofturn|> delimiters.# Keeping attn_mask=None also enables PyTorch's native FlashAttention-2 kernel.attn_mask = Nonenew_kv_caches = [] if kv_caches is not None else Nonefor l_idx, block in enumerate(self.blocks):layer_cache = kv_caches[l_idx] if kv_caches is not None else Noneif self.training and self.cfg.use_checkpoint:if attn_mask is not None:x = checkpoint(block, x, cos, sin, attn_mask, use_reentrant=False)else:x = checkpoint(block, x, cos, sin, use_reentrant=False)else:if kv_caches is not None:x, updated_cache = block(x, cos, sin, attn_mask, start_pos=start_pos, kv_cache=layer_cache)new_kv_caches.append(updated_cache)else:x = block(x, cos, sin, attn_mask, start_pos=start_pos)68 unmodified linesself.eval()idx = idx.to(next(self.parameters()).device)# Truncate prompt from left if it exceeds context window minus requested tokensmax_allowed_prompt = self.cfg.context_length - max_new_tokensif max_allowed_prompt <= 0:max_allowed_prompt = self.cfg.context_length - 1if idx.shape[1] > max_allowed_prompt:idx = idx[:, -max_allowed_prompt:]prompt_len = idx.shape[1]def _is_all_eos(next_tokens):if eos_token_id is None:return Falseif isinstance(eos_token_id, (list, tuple, set)):is_eos = torch.zeros(next_tokens.shape[0], dtype=torch.bool, device=next_tokens.device)for eid in eos_token_id:is_eos |= (next_tokens.squeeze(-1) == eid)return is_eos.all().item()return (next_tokens == eos_token_id).all().item()kv_caches = [None] * self.cfg.n_layers if use_cache else Noneidx_next = Nonefor cur_step in range(max_new_tokens):45 unmodified linesif temperature <= 0:idx_next = logits.argmax(dim=-1, keepdim=True)idx = torch.cat([idx, idx_next], dim=1)if _is_all_eos(idx_next):breakcontinue22 unmodified linesprobs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)idx = torch.cat([idx, idx_next], dim=1)if _is_all_eos(idx_next):breakreturn idx13 unmodified lines14151617181920212 unmodified lines24252627282930313233343536373839 unmodified lines78798081828384858687888990919293105 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422568 unmodified lines29429529629729829930030130230330430530630730830931031131231331431531631731831945 unmodified lines36536636736836937037137237337437522 unmodified lines39839940040140240340440540640740840913 unmodified linesdef forward(self, x):x_fp32 = x.float()norm = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)# Optimized: maintain pure bfloat16/float16 execution without promoting to FP32return norm.type_as(x) * self.weight.type_as(x)def precompute_rope(head_dim, max_len, theta=10000.0, device="cpu"):freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))2 unmodified linesreturn torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin, start_pos=0):# Fast-path: if cos, sin are already pre-sliced and pre-cast [1, 1, T, head_dim//2]if cos.dim() == 4:c, s = cos, sinelse:T = x.size(2)c = cos[start_pos:start_pos + T].to(x.dtype)[None, None, :, :]s = sin[start_pos:start_pos + T].to(x.dtype)[None, None, :, :]x1, x2 = x[..., ::2], x[..., 1::2]rotated = torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1)return rotated.flatten(-2)def repeat_kv(x, n_rep):39 unmodified linesnew_cache = Nonedropout_p = self.attn_dropout if self.training else 0.0if attn_mask is None and T > 1:if kv_cache is not None and cached_k is not None:cache_len = cached_k.size(2)# Lower-right aligned causal mask: query i attends to cached prefix + keys 0..cache_len+iattn_mask = torch.ones((T, cache_len + T), device=q.device, dtype=torch.bool).tril(diagonal=cache_len)is_causal = Falseelse:is_causal = Trueelse:is_causal = Falsetry:if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p, enable_gqa=True)105 unmodified linesnoise = torch.zeros_like(x).uniform_(-1.0, 1.0) * mag * special_maskx = x + noise# Pre-slice and pre-cast RoPE buffers ONCE outside the 24-layer block loop# Eliminates 48 redundant casting/slicing CUDA kernel launches per micro-batchcos = self.rope_cos[start_pos:start_pos + T].to(dtype=x.dtype)[None, None, :, :]sin = self.rope_sin[start_pos:start_pos + T].to(dtype=x.dtype)[None, None, :, :]# Pre-allocate multi-token KV-cache causal mask ONCE for all 24 blocks (saves 24 allocations)if kv_caches is not None and T > 1 and len(kv_caches) > 0 and kv_caches[0] is not None and kv_caches[0][0] is not None:cache_len = kv_caches[0][0].size(2)attn_mask = torch.ones((T, cache_len + T), device=x.device, dtype=torch.bool).tril(diagonal=cache_len)else:attn_mask = Nonenew_kv_caches = [] if kv_caches is not None else Nonefor l_idx, block in enumerate(self.blocks):layer_cache = kv_caches[l_idx] if kv_caches is not None else Noneif self.training and self.cfg.use_checkpoint:x = checkpoint(block, x, cos, sin, attn_mask, start_pos, use_reentrant=False)else:if kv_caches is not None:c = layer_cache if layer_cache is not None else (None, None)x, updated_cache = block(x, cos, sin, attn_mask, start_pos=start_pos, kv_cache=c)new_kv_caches.append(updated_cache)else:x = block(x, cos, sin, attn_mask, start_pos=start_pos)68 unmodified linesself.eval()idx = idx.to(next(self.parameters()).device)# Truncate prompt from left only if it exceeds context windowif idx.shape[1] >= self.cfg.context_length:idx = idx[:, -(self.cfg.context_length - 1):]# Clamp max_new_tokens to fit within remaining context windowmax_new_tokens = min(max_new_tokens, self.cfg.context_length - idx.shape[1])prompt_len = idx.shape[1]finished = torch.zeros(idx.shape[0], dtype=torch.bool, device=idx.device)def _check_eos_and_update(next_tokens):if eos_token_id is None:return Falseis_eos_curr = torch.zeros(next_tokens.shape[0], dtype=torch.bool, device=next_tokens.device)eids = eos_token_id if isinstance(eos_token_id, (list, tuple, set)) else [eos_token_id]for eid in eids:is_eos_curr |= (next_tokens.squeeze(-1) == eid)finished.logical_or_(is_eos_curr)return finished.all().item()kv_caches = [(None, None)] * self.cfg.n_layers if use_cache else Noneidx_next = Nonefor cur_step in range(max_new_tokens):45 unmodified linesif temperature <= 0:idx_next = logits.argmax(dim=-1, keepdim=True)if eos_token_id is not None and finished.any():pad_eos = next(iter(eos_token_id)) if isinstance(eos_token_id, (list, tuple, set)) else eos_token_ididx_next = torch.where(finished.unsqueeze(-1), torch.full_like(idx_next, pad_eos), idx_next)idx = torch.cat([idx, idx_next], dim=1)if _check_eos_and_update(idx_next):breakcontinue22 unmodified linesprobs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)if eos_token_id is not None and finished.any():pad_eos = next(iter(eos_token_id)) if isinstance(eos_token_id, (list, tuple, set)) else eos_token_ididx_next = torch.where(finished.unsqueeze(-1), torch.full_like(idx_next, pad_eos), idx_next)idx = torch.cat([idx, idx_next], dim=1)if _check_eos_and_update(idx_next):breakreturn idx
code/model.py+56-41