File size: 9,655 Bytes
6a96fe3 | 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | """
Bhaari AI Model Architecture
Llama-style transformer with agentic enhancements
"""
import torch
import torch.nn as nn
import math
from typing import Optional, Tuple
from dataclasses import dataclass
class RotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE)"""
def __init__(self, dim, max_seq_len=4096, base=500000):
super().__init__()
self.dim = dim
self.max_seq_len = max_seq_len
self.base = base
# Compute inverse frequencies
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
def forward(self, seq_len, device):
# Create position indices
t = torch.arange(seq_len, device=device).unsqueeze(-1) * self.inv_freq.unsqueeze(0)
# Stack sin and cos
emb = torch.cat([t.sin(), t.cos()], dim=-1)
return emb
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
"""Apply rotary embeddings to query and key"""
cos = cos[position_ids].unsqueeze(1)
sin = sin[position_ids].unsqueeze(1)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def rotate_half(x):
"""Rotate half the hidden dims"""
x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
return torch.cat([-x2, x1], dim=-1)
class RMSNorm(nn.Module):
"""Root Mean Square Normalization"""
def __init__(self, dim, eps=1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
norm = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
return x / norm * self.weight
class SwiGLU(nn.Module):
"""SwiGLU activation function"""
def __init__(self, dim, hidden_dim):
super().__init__()
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
def forward(self, x):
return self.w2(torch.nn.functional.silu(self.w1(x)) * self.w3(x))
class Attention(nn.Module):
"""Multi-head attention with Grouped Query Attention (GQA)"""
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.num_heads = config.num_heads
self.kv_heads = config.kv_heads
self.head_dim = self.hidden_size // self.num_heads
self.max_seq_len = config.max_seq_length
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
self.k_proj = nn.Linear(self.hidden_size, self.kv_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(self.hidden_size, self.kv_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
self.rope = RotaryEmbedding(self.head_dim, config.max_seq_length, config.rope_theta)
def forward(self, x, position_ids=None, kv_cache=None, use_cache=True):
batch_size, seq_len, _ = x.shape
# Project to Q, K, V
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
# Reshape for multi-head
q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.kv_heads, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.kv_heads, self.head_dim).transpose(1, 2)
# Apply RoPE
cos, sin = self.rope(seq_len, x.device)
q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids if position_ids is not None else torch.arange(seq_len, device=x.device))
# Handle KV cache
if kv_cache is not None:
k_cache, v_cache = kv_cache
k = torch.cat([k_cache, k], dim=2)
v = torch.cat([v_cache, v], dim=2)
if use_cache:
kv_cache = (k, v)
# Expand KV heads to match Q heads for attention
num_kv_groups = self.num_heads // self.kv_heads
k = k.repeat_interleave(num_kv_groups, dim=1)
v = v.repeat_interleave(num_kv_groups, dim=1)
# Attention
attn_weights = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(self.head_dim)
# Causal mask
mask = torch.triu(torch.ones(seq_len, seq_len, device=x.device), diagonal=1).bool()
attn_weights = attn_weights.masked_fill(mask, float('-inf'))
attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
out = torch.matmul(attn_weights, v)
# Reshape and project
out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, self.hidden_size)
out = self.o_proj(out)
return out, kv_cache
class TransformerBlock(nn.Module):
"""Transformer block with attention and feed-forward"""
def __init__(self, config):
super().__init__()
self.config = config
self.attention = Attention(config)
self.feed_forward = SwiGLU(config.hidden_size, config.intermediate_size)
self.attention_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
self.ffn_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
def forward(self, x, position_ids=None, kv_cache=None, use_cache=True):
# Attention with pre-norm
residual = x
x = self.attention_norm(x)
attn_out, kv_cache = self.attention(x, position_ids, kv_cache, use_cache)
x = residual + attn_out
# Feed-forward with pre-norm
residual = x
x = self.ffn_norm(x)
x = residual + self.feed_forward(x)
return x, kv_cache
class BhaariModel(nn.Module):
"""
Bhaari AI - Agentic Coding LLM
Llama-style transformer with progressive scaling
"""
def __init__(self, config):
super().__init__()
self.config = config
# Token embeddings
self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
# Transformer blocks
self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_layers)])
# Output
self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Tie weights
self.lm_head.weight = self.token_embedding.weight
# Position embeddings are handled by RoPE in attention
def forward(self, input_ids, position_ids=None, kv_cache=None, use_cache=False):
"""
Forward pass
Args:
input_ids: Token IDs [batch, seq_len]
position_ids: Position indices for RoPE
kv_cache: KV cache for generation
use_cache: Whether to use/declare cache
"""
# Get embeddings
x = self.token_embedding(input_ids)
# Pass through transformer blocks
new_kv_cache = []
for i, layer in enumerate(self.layers):
cache = kv_cache[i] if kv_cache is not None else None
x, block_cache = layer(x, position_ids, cache, use_cache)
new_kv_cache.append(block_cache)
# Final norm and project
x = self.norm(x)
logits = self.lm_head(x)
return logits, new_kv_cache if use_cache else None
def generate(self, input_ids, max_new_tokens=100, temperature=1.0, top_p=0.9):
"""Generate new tokens"""
self.eval()
with torch.no_grad():
for _ in range(max_new_tokens):
# Crop context if too long
input_ids_cond = input_ids if input_ids.size(1) <= self.config.max_seq_length else input_ids[:, -self.config.max_seq_length:]
# Forward
logits, _ = self.forward(input_ids_cond)
logits = logits[:, -1, :] / temperature
# Top-p sampling
probs = torch.nn.functional.softmax(logits, dim=-1)
sorted_probs, indices = torch.sort(probs, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
top_p_mask = cumulative_probs > top_p
sorted_probs[top_p_mask] = 0
sorted_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)
# Sample
next_token = torch.multinomial(sorted_probs, num_samples=1)
next_token = indices.gather(-1, next_token)
input_ids = torch.cat([input_ids, next_token], dim=1)
if next_token.item() == 2: # EOS token
break
return input_ids
def create_model(config):
"""Create model from config"""
model = BhaariModel(config)
return model
# Model parameter count estimation
def estimate_params(config):
"""Estimate model parameters"""
# Embedding
params = config.vocab_size * config.hidden_size * 2 # embeddings + lm_head
# Each layer
per_layer = (
config.hidden_size * config.hidden_size * 12 + # Q, K, V, O projections
config.hidden_size * config.intermediate_size * 6 + # FFN
config.hidden_size * 4 # 2 RMSNorms
)
params += config.num_layers * per_layer
return params |