implement foundation model in python
- User
implement foundation model in python
Assistant
implement foundation model in python
I'll help you implement a foundation model in Python. Since "foundation model" is a broad term, I'll show you how to build a transformer-based language model from scratch, which is a common type of foundation model.
Here's a complete implementation of a small transformer model:
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads, dropout=0.1):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
self.W_q = nn.Linear(d_model, d_model)
self.W_k = nn.Linear(d_model, d_model)
self.W_v = nn.Linear(d_model, d_model)
self.W_o = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, query, key, value, mask=None):
batch_size = query.size(0)
# Linear transformations and reshape for multi-head
Q = self.W_q(query).view(batch_size, -1, self.n_heads, self.d_k).transpose(1, 2)
K = self.W_k(key).view(batch_size, -1, self.n_heads, self.d_k).transpose(1, 2)
V = self.W_v(value).view(batch_size, -1, self.n_heads, self.d_k).transpose(1, 2)
# Attention scores
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
attention_weights = self.dropout(attention_weights)
# Apply attention to values
context = torch.matmul(attention_weights, V)
# Concatenate heads
context = context.transpose(1, 2).contiguous().view(
batch_size, -1, self.d_model
)
output = self.W_o(context)
return output
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.linear2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = F.relu(self.linear1(x))
x = self.dropout(x)
x = self.linear2(x)
return x
class TransformerBlock(nn.Module):
def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
super().__init__()
self.attention = MultiHeadAttention(d_model, n_heads, dropout)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.feed_forward = FeedForward(d_model, d_ff, dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
# Self-attention with residual connection
attn_output = self.attention(x, x, x, mask)
x = self.norm1(x + self.dropout(attn_output))
# Feed-forward with residual connection
ff_output = self.feed_forward(x)
x = self.norm2(x + self.dropout(ff_output))
return x
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1).float()
div_term = torch.exp(torch.arange(0, d_model, 2).float() *
-(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe.unsqueeze(0))
def forward(self, x):
return x + self.pe[:, :x.size(1)]
class FoundationModel(nn.Module):
def __init__(self, vocab_size, d_model=512, n_heads=8, n_layers=6,
d_ff=2048, max_len=5000, dropout=0.1):
super().__init__()
self.d_model = d_model
self.embedding = nn.Embedding(vocab_size, d_model)
self.pos_encoding = PositionalEncoding(d_model, max_len)
self.transformer_blocks = nn.ModuleList([
TransformerBlock(d_model, n_heads, d_ff, dropout)
for _ in range(n_layers)
])
self.ln_f = nn.LayerNorm(d_model)
self.fc_out = nn.Linear(d_model, vocab_size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
# Token embeddings and positional encoding
x = self.embedding(x) * math.sqrt(self.d_model)
x = self.pos_encoding(x)
x = self.dropout(x)
# Pass through transformer blocks
for transformer in self.transformer_blocks:
x = transformer(x, mask)
# Final layer norm and output projection
x = self.ln_f(x)
output = self.fc_out(x)
return output
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
"""Generate new tokens autoregressively"""
self.eval()
with torch.no_grad():
for _ in range(max_new_tokens):
# Get predictions for current sequence
logits = self(idx)
# Focus on last token
logits = logits[:, -1, :] / temperature
# Apply top-k filtering if specified
if top_k is not None:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = -float('Inf')
# Sample from distribution
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
# Append to sequence
idx = torch.cat((idx, idx_next), dim=1)
return idx
# Example usage and training setup
def create_model(vocab_size=10000):
model = FoundationModel(
vocab_size=vocab_size,
d_model=512,
n_heads=8,
n_layers=6,
d_ff=2048,
dropout=0.1
)
return model
def train_step(model, data, labels, optimizer, criterion):
"""Single training step"""
model.train()
optimizer.zero_grad()
# Create causal mask
seq_len = data.size(1)
mask = torch.tril(torch.ones(seq_len, seq_len)).unsqueeze(0).unsqueeze(0)
# Forward pass
output = model(data, mask)
loss = criterion(output.view(-1, output.size(-1)), labels.view(-1))
# Backward pass
loss.backward()
optimizer.step()
return loss.item()
# Example training loop
def train_model(model, train_loader, epochs=10, lr=0.0001):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss(ignore_index=-100)
for epoch in range(epochs):
total_loss = 0
for batch_idx, (data, labels) in enumerate(train_loader):
loss = train_step(model, data, labels, optimizer, criterion)
total_loss += loss
if batch_idx % 100 == 0:
print(f'Epoch {epoch}, Batch {batch_idx}, Loss: {loss:.4f}')
avg_loss = total_loss / len(train_loader)
print(f'Epoch {epoch} completed. Average Loss: {avg_loss:.4f}')
# Create and initialize model
if __name__ == "__main__":
# Example initialization
vocab_size = 10000
model = create_model(vocab_size)
# Count parameters
total_params = sum(p.numel() for p in model.parameters())
print(f"Total parameters: {total_params:,}")
# Example forward pass
batch_size = 2
seq_len = 100
dummy_input = torch.randint(0, vocab_size, (batch_size, seq_len))
output = model(dummy_input)
print(f"Output shape: {output.shape}")
# Example generation
start_tokens = torch.tensor([[1, 2, 3]]) # Starting sequence
generated = model.generate(start_tokens, max_new_tokens=50, temperature=0.8, top_k=50)
print(f"Generated sequence shape: {generated.shape}")
This implementation includes:
To use this model, you would need to:
For a production-ready foundation model, you might also want to add:
Would you like me to expand on any particular aspect of the implementation or show how to prepare data for training?