Upload code/model.py with huggingface_hub
Browse files22 unmodified lines23242526272829303132333435363720 unmodified lines585960616263646566676869707172737475767778798081828384858687888915 unmodified lines10510610710810911011111211328 unmodified lines1421431441451461471481491501511521531541551561575 unmodified lines16316416516616716816917017117217317417517617720 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222239 unmodified lines2332342352362372382398 unmodified lines24824925025125225325425525625725822 unmodified linesfreqs = torch.outer(t, freqs)return torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin):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[:T][None, None, :, :]sin = sin[:T][None, None, :, :]rotated = torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)return rotated.flatten(-2)20 unmodified linesself.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.attn_dropout = cfg.attn_dropoutdef forward(self, x, cos, sin, attn_mask=None):B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)q, k = self.q_norm(q), self.k_norm(k)q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)dropout_p = self.attn_dropout if self.training else 0.0try: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)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p, enable_gqa=True)except TypeError:if self.n_rep > 1:k = repeat_kv(k, self.n_rep)v = repeat_kv(v, self.n_rep)if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p)out = out.transpose(1, 2).contiguous().view(B, T, -1)return self.o_proj(out)class SwiGLU(nn.Module):def __init__(self, cfg: ViuAIConfig):15 unmodified linesself.ffn = SwiGLU(cfg)self.resid_dropout = nn.Dropout(cfg.resid_dropout) if cfg.resid_dropout > 0 else nn.Identity()def forward(self, x, cos, sin, attn_mask=None):x = x + self.resid_dropout(self.attn(self.attn_norm(x), cos, sin, attn_mask))x = x + self.resid_dropout(self.ffn(self.ffn_norm(x)))return xclass ViuAI(nn.Module):28 unmodified lineselif isinstance(module, nn.Embedding):nn.init.normal_(module.weight, mean=0.0, std=0.02)def forward(self, idx, targets=None, pad_id=None, shift_labels=False):B, T = idx.shapeassert T <= self.cfg.context_length, f"Sequence length {T} exceeds context_length {self.cfg.context_length}"x = self.tok_emb(idx)# NEFTune: Noisy Embedding Fine-Tuning for conversational quality boostif self.training and getattr(self.cfg, "neftune_alpha", 0.0) > 0.0:dims = x.size(1) * x.size(2)mag = self.cfg.neftune_alpha / math.sqrt(max(1, dims))noise = torch.zeros_like(x).uniform_(-1.0, 1.0) * magx = x + noisecos = self.rope_cos.to(x.device)5 unmodified lines# to attend to in-prompt <|endofturn|> delimiters.# Keeping attn_mask=None also enables PyTorch's native FlashAttention-2 kernel.attn_mask = Nonefor block in self.blocks:if 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:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)# =====================================================================20 unmodified linesfor 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.reshape(-1, V), chunk_tgt.reshape(-1),ignore_index=-100, reduction="sum")total_loss = total_loss + chunk_lossloss = total_loss / total_active# z-loss: fused inside CE loop if enabled (avoids redundant self.head pass)if self.cfg.z_loss_weight > 0:pass # Already handled or zero for stable pretraining# 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):9 unmodified lines@torch.no_grad()def generate(self, idx, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9,eos_token_id=None, repetition_penalty=1.0, presence_penalty=0.0,frequency_penalty=0.0, no_repeat_ngram_size=0):self.eval()idx = idx.to(next(self.parameters()).device)prompt_len = idx.shape[1]8 unmodified linesreturn is_eos.all().item()return (next_tokens == eos_token_id).all().item()for _ in range(max_new_tokens):# Crop to context windowidx_cond = idx if idx.size(1) <= self.cfg.context_length else idx[:, -self.cfg.context_length:]logits, _ = self(idx_cond)logits = logits[:, -1, :] # only last position# 1. Repetition penalty (Standard Hugging Face formulation)if repetition_penalty != 1.0:22 unmodified lines23242526272829303132333435363720 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810915 unmodified lines12512612712812913013113213313413513613713813914028 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901915 unmodified lines19719819920020120220320420520620720820921021121221321421521621720 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642652662679 unmodified lines2772782792802812822838 unmodified lines29229329429529629729829930030130230330430530630730830931031131231331431522 unmodified linesfreqs = torch.outer(t, freqs)return 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)20 unmodified linesself.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.attn_dropout = cfg.attn_dropoutdef forward(self, x, cos, sin, attn_mask=None, start_pos=0, kv_cache=None):B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)q, k = self.q_norm(q), self.k_norm(k)q = apply_rope(q, cos, sin, start_pos=start_pos)k = apply_rope(k, cos, sin, start_pos=start_pos)if kv_cache is not None:cached_k, cached_v = kv_cacheif cached_k is not None:k = torch.cat([cached_k, k], dim=2)v = torch.cat([cached_v, v], dim=2)new_cache = (k, v)else:new_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)elif is_causal:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p, enable_gqa=True)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=False, dropout_p=dropout_p, enable_gqa=True)except TypeError:if self.n_rep > 1:k_rep = repeat_kv(k, self.n_rep)v_rep = repeat_kv(v, self.n_rep)else:k_rep, v_rep = k, vif attn_mask is not None:out = F.scaled_dot_product_attention(q, k_rep, v_rep, attn_mask=attn_mask, dropout_p=dropout_p)elif is_causal:out = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=True, dropout_p=dropout_p)else:out = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=False, dropout_p=dropout_p)out = out.transpose(1, 2).contiguous().view(B, T, -1)out = self.o_proj(out)if kv_cache is not None:return out, new_cachereturn outclass SwiGLU(nn.Module):def __init__(self, cfg: ViuAIConfig):15 unmodified linesself.ffn = SwiGLU(cfg)self.resid_dropout = nn.Dropout(cfg.resid_dropout) if cfg.resid_dropout > 0 else nn.Identity()def forward(self, x, cos, sin, attn_mask=None, start_pos=0, kv_cache=None):if kv_cache is not None:attn_out, new_cache = self.attn(self.attn_norm(x), cos, sin, attn_mask, start_pos=start_pos, kv_cache=kv_cache)else:attn_out = self.attn(self.attn_norm(x), cos, sin, attn_mask, start_pos=start_pos)new_cache = Nonex = x + self.resid_dropout(attn_out)x = x + self.resid_dropout(self.ffn(self.ffn_norm(x)))if kv_cache is not None:return x, new_cachereturn xclass ViuAI(nn.Module):28 unmodified lineselif isinstance(module, nn.Embedding):nn.init.normal_(module.weight, mean=0.0, std=0.02)def forward(self, idx, targets=None, pad_id=None, shift_labels=False, start_pos=0, kv_caches=None):B, T = idx.shapeassert (start_pos + T) <= self.cfg.context_length, f"Sequence length {start_pos + T} exceeds context_length {self.cfg.context_length}"x = self.tok_emb(idx)# NEFTune: Noisy Embedding Fine-Tuning for conversational quality boostif self.training and getattr(self.cfg, "neftune_alpha", 0.0) > 0.0:if pad_id is not None:non_pad_mask = (idx != pad_id).unsqueeze(-1) # [B, T, 1]seq_lens = non_pad_mask.sum(dim=1, keepdim=True).clamp(min=1).float()dims = seq_lens * x.size(2)mag = (self.cfg.neftune_alpha / torch.sqrt(dims)).to(x.dtype)noise = torch.zeros_like(x).uniform_(-1.0, 1.0) * mag * non_pad_maskelse:dims = x.size(1) * x.size(2)mag = self.cfg.neftune_alpha / math.sqrt(max(1, dims))noise = torch.zeros_like(x).uniform_(-1.0, 1.0) * magx = x + noisecos = self.rope_cos.to(x.device)5 unmodified lines# 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)x = self.final_norm(x)# =====================================================================20 unmodified linesfor i in range(0, seq_len, ce_chunk):end = min(i + ce_chunk, seq_len)chunk_logits = self.head(hidden[:, i:end, :]).float() # FP32 cast for exact CE & Z-loss precisionchunk_tgt = tgt[:, i:end] # [B, chunk]chunk_loss = F.cross_entropy(chunk_logits.reshape(-1, V), chunk_tgt.reshape(-1),ignore_index=-100, reduction="sum")if self.cfg.z_loss_weight > 0.0:valid_mask = (chunk_tgt != -100)if valid_mask.any():lse = torch.logsumexp(chunk_logits[valid_mask], dim=-1)chunk_loss = chunk_loss + self.cfg.z_loss_weight * (lse ** 2).sum()total_loss = total_loss + chunk_lossloss = total_loss / total_active# 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)if kv_caches is not None:return logits, new_kv_cachesreturn logits, lossdef num_params(self):9 unmodified lines@torch.no_grad()def generate(self, idx, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9,eos_token_id=None, repetition_penalty=1.0, presence_penalty=0.0,frequency_penalty=0.0, no_repeat_ngram_size=0, use_cache=True):self.eval()idx = idx.to(next(self.parameters()).device)prompt_len = idx.shape[1]8 unmodified linesreturn 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):if idx.size(1) >= self.cfg.context_length:breakif use_cache:if cur_step == 0:logits, kv_caches = self(idx, start_pos=0, kv_caches=kv_caches)else:logits, kv_caches = self(idx_next, start_pos=idx.size(1) - 1, kv_caches=kv_caches)logits = logits[:, -1, :]else:# Crop to context windowidx_cond = idx if idx.size(1) <= self.cfg.context_length else idx[:, -self.cfg.context_length:]logits, _ = self(idx_cond)logits = logits[:, -1, :] # only last position# 1. Repetition penalty (Standard Hugging Face formulation)if repetition_penalty != 1.0:
code/model.py+88-31