Upload 4 files
Browse filesFiles changed (4)
- model/__init__.pyAdded+15
- model/attention.pyAdded+204
- model/lora.pyAdded+174
- model/transformer.pyAdded+359
123456789101112131415"""Shulker Code β Model Package"""from model.transformer import ShulkerCodeModel, ShulkerConfigfrom model.attention import GroupedQueryAttention, RotaryEmbeddingfrom model.lora import LoRAConfig, apply_lora, save_lora_weights, load_lora_weights
__all__ = [ "ShulkerCodeModel", "ShulkerConfig", "GroupedQueryAttention", "RotaryEmbedding", "LoRAConfig", "apply_lora", "save_lora_weights", "load_lora_weights",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204"""===================================== Shulker Code β Attention Module Multi-Head Attention + GQA + RoPE Developed by @kopeedev / CyeroX====================================="""
import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Optional, Tuple
# βββββββββββββββββββββββββββββββββββββββββββββ# Rotary Positional Encoding (RoPE)# Used in modern LLMs (LLaMA, Mistral, etc.)# βββββββββββββββββββββββββββββββββββββββββββββclass RotaryEmbedding(nn.Module): """ RoPE: Rotary Position Embedding. Encodes position by rotating query/key vectors in pairs. Naturally handles long contexts better than absolute PE. """
def __init__(self, dim: int, max_seq_len: int = 8192, theta: float = 10000.0): super().__init__() self.dim = dim self.max_seq_len = max_seq_len self.theta = theta
# Precompute inverse frequencies inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False)
# Cache cos/sin for fast inference self._build_cache(max_seq_len)
def _build_cache(self, seq_len: int): """Precompute and cache the rotation matrices.""" t = torch.arange(seq_len, device=self.inv_freq.device).float() freqs = torch.outer(t, self.inv_freq) # [seq_len, dim/2] emb = torch.cat([freqs, freqs], dim=-1) # [seq_len, dim] self.register_buffer("cos_cached", emb.cos(), persistent=False) self.register_buffer("sin_cached", emb.sin(), persistent=False)
def _rotate_half(self, x: torch.Tensor) -> torch.Tensor: """Rotate the second half of the last dimension.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat([-x2, x1], dim=-1)
def forward( self, q: torch.Tensor, k: torch.Tensor, seq_len: int, offset: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """ Apply rotary embeddings to query and key tensors. Args: q: Query tensor [batch, heads, seq, dim] k: Key tensor [batch, kv_heads, seq, dim] seq_len: Current sequence length offset: KV cache offset for incremental decoding """ # Extend cache if needed if offset + seq_len > self.max_seq_len: self._build_cache(offset + seq_len)
cos = self.cos_cached[offset : offset + seq_len].unsqueeze(0).unsqueeze(0) sin = self.sin_cached[offset : offset + seq_len].unsqueeze(0).unsqueeze(0)
q_rot = q * cos + self._rotate_half(q) * sin k_rot = k * cos + self._rotate_half(k) * sin return q_rot, k_rot
# βββββββββββββββββββββββββββββββββββββββββββββ# Grouped Query Attention (GQA)# Efficient variant: fewer KV heads = less VRAM# βββββββββββββββββββββββββββββββββββββββββββββclass GroupedQueryAttention(nn.Module): """ Grouped Query Attention (GQA) as used in LLaMA 2, Mistral, etc.
- num_heads: number of query heads - num_kv_heads: number of key/value heads (β€ num_heads) - When num_kv_heads == num_heads β standard MHA - When num_kv_heads == 1 β Multi-Query Attention (MQA) - Otherwise β GQA (balanced efficiency/quality) """
def __init__( self, hidden_size: int, num_heads: int, num_kv_heads: int, max_seq_len: int = 8192, dropout: float = 0.0, rope_theta: float = 10000.0, use_flash_attn: bool = False, ): super().__init__() assert hidden_size % num_heads == 0, "hidden_size must be divisible by num_heads" assert num_heads % num_kv_heads == 0, "num_heads must be divisible by num_kv_heads"
self.hidden_size = hidden_size self.num_heads = num_heads self.num_kv_heads = num_kv_heads self.head_dim = hidden_size // num_heads self.groups = num_heads // num_kv_heads # How many Q heads share each KV head self.scale = self.head_dim ** -0.5 self.use_flash_attn = use_flash_attn
# Projection layers self.q_proj = nn.Linear(hidden_size, num_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(hidden_size, num_kv_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(num_heads * self.head_dim, hidden_size, bias=False)
self.attn_dropout = nn.Dropout(dropout)
# Rotary embeddings self.rotary = RotaryEmbedding(self.head_dim, max_seq_len, rope_theta)
def forward( self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: """ Forward pass for GQA. Args: x: Input hidden states [batch, seq, hidden] attention_mask: Causal or padding mask past_kv: Cached K/V tensors for fast generation use_cache: Whether to return updated KV cache Returns: output: Attended output [batch, seq, hidden] new_kv: Updated KV cache (or None) """ B, T, C = x.shape offset = past_kv[0].shape[2] if past_kv is not None else 0
# Project to Q, K, V q = self.q_proj(x).view(B, T, self.num_heads, self.head_dim).transpose(1, 2) k = self.k_proj(x).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2) v = self.v_proj(x).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)
# Apply RoPE q, k = self.rotary(q, k, T, offset)
# Append to KV cache if using incremental decoding if past_kv is not None: k = torch.cat([past_kv[0], k], dim=2) v = torch.cat([past_kv[1], v], dim=2)
new_kv = (k, v) if use_cache else None kv_seq_len = k.shape[2]
# Expand KV heads to match Q heads (GQA expansion) if self.groups > 1: k = k.unsqueeze(2).expand(B, self.num_kv_heads, self.groups, kv_seq_len, self.head_dim) k = k.reshape(B, self.num_heads, kv_seq_len, self.head_dim) v = v.unsqueeze(2).expand(B, self.num_kv_heads, self.groups, kv_seq_len, self.head_dim) v = v.reshape(B, self.num_heads, kv_seq_len, self.head_dim)
# Scaled dot-product attention # Try Flash Attention (PyTorch 2.0+) for speed if self.use_flash_attn and hasattr(F, "scaled_dot_product_attention"): # Flash Attention: handles masking internally attn_output = F.scaled_dot_product_attention( q, k, v, attn_mask=attention_mask, dropout_p=self.attn_dropout.p if self.training else 0.0, is_causal=(attention_mask is None), ) else: # Manual attention computation attn_scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale # [B, H, T, kv_T]
# Causal mask: prevent attending to future tokens if attention_mask is None: causal_mask = torch.triu( torch.full((T, kv_seq_len), float("-inf"), device=x.device), diagonal=1 + offset ) attn_scores = attn_scores + causal_mask else: attn_scores = attn_scores + attention_mask
attn_weights = F.softmax(attn_scores, dim=-1) attn_weights = self.attn_dropout(attn_weights) attn_output = torch.matmul(attn_weights, v)
# Reshape and project output attn_output = attn_output.transpose(1, 2).contiguous().view(B, T, self.hidden_size) output = self.o_proj(attn_output)
return output, new_kv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""===================================== Shulker Code β LoRA / PEFT Module Low-Rank Adaptation for fine-tuning Developed by @kopeedev / CyeroX=====================================
LoRA: Instead of updating all weights W, we learn two small matrices: W' = W + Ξ± * (A @ B)where A β R^{dΓr} and B β R^{rΓk}, rank r << d,k
This makes fine-tuning with minimal parameters possible!"""
import mathfrom typing import Optional, List, Dict, Anyimport torchimport torch.nn as nnimport torch.nn.functional as F
class LoRALinear(nn.Module): """ A Linear layer augmented with LoRA adapters. Wraps an existing nn.Linear and adds low-rank update matrices. """
def __init__( self, original_layer: nn.Linear, rank: int = 8, alpha: float = 16.0, dropout: float = 0.05, enabled: bool = True, ): super().__init__()
self.rank = rank self.alpha = alpha self.scaling = alpha / rank self.enabled = enabled
in_features = original_layer.in_features out_features = original_layer.out_features
# Keep the original frozen weights self.weight = original_layer.weight self.bias = original_layer.bias
if enabled and rank > 0: # LoRA matrices: A (init with Kaiming), B (init with zeros) self.lora_A = nn.Parameter(torch.empty(rank, in_features)) self.lora_B = nn.Parameter(torch.zeros(out_features, rank)) self.lora_dropout = nn.Dropout(dropout)
# Initialize A with kaiming uniform (standard) nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) else: self.lora_A = None self.lora_B = None self.lora_dropout = None
def forward(self, x: torch.Tensor) -> torch.Tensor: # Base frozen forward pass base_out = F.linear(x, self.weight, self.bias)
# Add LoRA delta (if enabled) if self.enabled and self.rank > 0: lora_out = self.lora_dropout(x) @ self.lora_A.T @ self.lora_B.T return base_out + lora_out * self.scaling
return base_out
def merge_weights(self): """ Merge LoRA weights into the base weights permanently. Call before exporting/deploying to remove LoRA overhead. """ if self.enabled and self.rank > 0: delta = (self.lora_B @ self.lora_A) * self.scaling self.weight.data += delta self.lora_A = None self.lora_B = None self.enabled = False print("β
LoRA weights merged into base layer.")
class LoRAConfig: """Configuration for LoRA fine-tuning.""" def __init__( self, rank: int = 8, alpha: float = 16.0, dropout: float = 0.05, # Which modules to apply LoRA to target_modules: Optional[List[str]] = None, ): self.rank = rank self.alpha = alpha self.dropout = dropout # Default: apply to attention projection layers self.target_modules = target_modules or ["q_proj", "v_proj", "o_proj"]
def apply_lora(model: nn.Module, lora_config: LoRAConfig) -> nn.Module: """ Apply LoRA adapters to a model's target linear layers.
Steps: 1. Freeze ALL base model parameters 2. Replace target Linear layers with LoRALinear wrappers 3. Only LoRA parameters (A, B) are trainable
Args: model: The base ShulkerCodeModel lora_config: LoRA configuration
Returns: Modified model with LoRA applied """ # Step 1: Freeze everything for param in model.parameters(): param.requires_grad = False
# Step 2: Replace target layers replaced = 0 for name, module in model.named_modules(): for target in lora_config.target_modules: if name.endswith(target) and isinstance(module, nn.Linear): # Navigate to parent module parent_name, child_name = name.rsplit(".", 1) parent = dict(model.named_modules())[parent_name]
# Replace with LoRA wrapper lora_layer = LoRALinear( original_layer=module, rank=lora_config.rank, alpha=lora_config.alpha, dropout=lora_config.dropout, ) setattr(parent, child_name, lora_layer) replaced += 1 break
# Step 3: Count trainable params trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) total = sum(p.numel() for p in model.parameters()) print(f"β
LoRA applied to {replaced} layers") print(f" Trainable params: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)")
return model
def save_lora_weights(model: nn.Module, path: str): """Save only LoRA adapter weights (very small files!).""" import os os.makedirs(path, exist_ok=True) lora_state = { name: param for name, param in model.named_parameters() if "lora_" in name } torch.save(lora_state, os.path.join(path, "lora_weights.pt")) print(f"β
LoRA weights saved to {path} ({len(lora_state)} tensors)")
def load_lora_weights(model: nn.Module, path: str, device: str = "cpu"): """Load LoRA adapter weights back into a model.""" import os weights_path = os.path.join(path, "lora_weights.pt") lora_state = torch.load(weights_path, map_location=device) missing, unexpected = model.load_state_dict(lora_state, strict=False) print(f"β
LoRA weights loaded. Missing: {len(missing)}, Unexpected: {len(unexpected)}") return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359"""===================================== Shulker Code β Transformer Model GPT-style Decoder with SwiGLU FFN Developed by @kopeedev / CyeroX====================================="""
import mathfrom dataclasses import dataclass, fieldfrom typing import Optional, Tuple, List, Dict, Any
import torchimport torch.nn as nnimport torch.nn.functional as F
from model.attention import GroupedQueryAttention
# βββββββββββββββββββββββββββββββββββββββββββββ# Model Configuration Dataclass# βββββββββββββββββββββββββββββββββββββββββββββ@dataclassclass ShulkerConfig: """Complete configuration for a Shulker Code model."""
# Identity name: str = "shulker-nano" version: str = "1.0.0"
# Vocabulary vocab_size: int = 32000 pad_token_id: int = 0 bos_token_id: int = 1 eos_token_id: int = 2
# Architecture hidden_size: int = 256 num_layers: int = 4 num_heads: int = 4 num_kv_heads: int = 4 # Set < num_heads for GQA intermediate_size: int = 1024 # FFN hidden size max_seq_len: int = 1024 dropout: float = 0.1 rope_theta: float = 10000.0 tie_embeddings: bool = True # Tie input/output embeddings
# Normalization rms_norm_eps: float = 1e-6
@classmethod def from_dict(cls, d: Dict[str, Any]) -> "ShulkerConfig": """Load config from a dict (e.g. parsed from YAML).""" return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})
def to_dict(self) -> Dict[str, Any]: """Serialize config to dict.""" import dataclasses return dataclasses.asdict(self)
@property def head_dim(self) -> int: return self.hidden_size // self.num_heads
def num_parameters(self) -> int: """Estimate total parameter count.""" # Embeddings params = self.vocab_size * self.hidden_size # Each layer: attention + FFN + norms layer_params = ( # Attention projections self.hidden_size * self.hidden_size + # Q self.hidden_size * (self.num_kv_heads * self.head_dim) * 2 + # K + V self.hidden_size * self.hidden_size + # O # FFN (SwiGLU has 3 matrices) self.hidden_size * self.intermediate_size * 3 + # RMS Norms (2 per layer) self.hidden_size * 2 ) params += layer_params * self.num_layers # Final norm + LM head params += self.hidden_size + (0 if self.tie_embeddings else self.vocab_size * self.hidden_size) return params
# βββββββββββββββββββββββββββββββββββββββββββββ# RMS Layer Normalization# Simpler and faster than LayerNorm# βββββββββββββββββββββββββββββββββββββββββββββclass RMSNorm(nn.Module): """ Root Mean Square Layer Normalization. Omits the mean-centering for efficiency. """ def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: # Compute RMS rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt() return x / rms * self.weight
# βββββββββββββββββββββββββββββββββββββββββββββ# SwiGLU Feed-Forward Network# Used in LLaMA, PaLM, etc. β better than GELU FFN# βββββββββββββββββββββββββββββββββββββββββββββclass SwiGLUFFN(nn.Module): """ SwiGLU Feed-Forward Network. FFN(x) = (Swish(xW1) β xW3) W2 Three weight matrices instead of two. """ def __init__(self, hidden_size: int, intermediate_size: int, dropout: float = 0.0): super().__init__() self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) # W1 self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) # W3 self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) # W2 self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor: # SwiGLU: gate * swish activation gate = F.silu(self.gate_proj(x)) # Swish(xW1) up = self.up_proj(x) # xW3 return self.down_proj(self.dropout(gate * up))
# βββββββββββββββββββββββββββββββββββββββββββββ# Transformer Decoder Layer# Pre-normalization (like LLaMA)# ββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββclass ShulkerDecoderLayer(nn.Module): """ Single Transformer decoder layer. Uses pre-normalization (norm before attention/FFN). Architecture: LayerNorm β Attention β Residual β LayerNorm β FFN β Residual """ def __init__(self, config: ShulkerConfig, layer_idx: int = 0): super().__init__() self.layer_idx = layer_idx
# Self-attention (with GQA + RoPE) self.self_attn = GroupedQueryAttention( hidden_size=config.hidden_size, num_heads=config.num_heads, num_kv_heads=config.num_kv_heads, max_seq_len=config.max_seq_len, dropout=config.dropout, rope_theta=config.rope_theta, )
# Feed-forward network (SwiGLU) self.ffn = SwiGLUFFN( hidden_size=config.hidden_size, intermediate_size=config.intermediate_size, dropout=config.dropout, )
# Pre-normalization self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attn_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
def forward( self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[Tuple]]: """ Forward pass of one decoder layer. Returns updated hidden states and optional KV cache. """ # Pre-norm β Attention β Residual residual = x x_norm = self.input_layernorm(x) attn_out, new_kv = self.self_attn( x_norm, attention_mask=attention_mask, past_kv=past_kv, use_cache=use_cache ) x = residual + attn_out
# Pre-norm β FFN β Residual residual = x x = residual + self.ffn(self.post_attn_layernorm(x))
return x, new_kv
# βββββββββββββββββββββββββββββββββββββββββββββ# Shulker Code β Main Model# βββββββββββββββββββββββββββββββββββββββββββββclass ShulkerCodeModel(nn.Module): """ Shulker Code: A GPT-style autoregressive language model optimized for code generation tasks.
Features: - GQA (Grouped Query Attention) for memory efficiency - RoPE positional embeddings for long context - SwiGLU FFN for better performance - RMSNorm for stability - KV caching for fast inference - Configurable size: 5M to 80B+ parameters
Developed by @kopeedev / CyeroX Development """
def __init__(self, config: ShulkerConfig): super().__init__() self.config = config
# Token embeddings self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
# Embedding dropout self.embed_dropout = nn.Dropout(config.dropout)
# Decoder layers self.layers = nn.ModuleList([ ShulkerDecoderLayer(config, layer_idx=i) for i in range(config.num_layers) ])
# Final normalization self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
# Language model head (projects to vocab) if config.tie_embeddings: # Reuse embedding weights β reduces params, improves generalization self.lm_head = None else: self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights self.apply(self._init_weights)
def _init_weights(self, module: nn.Module): """Initialize weights following GPT conventions.""" if isinstance(module, nn.Linear): std = 0.02 / math.sqrt(2 * self.config.num_layers) nn.init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=0.02)
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def num_parameters(self, trainable_only: bool = False) -> int: """Count actual model parameters.""" params = self.parameters() if not trainable_only else filter(lambda p: p.requires_grad, self.parameters()) return sum(p.numel() for p in params)
def forward( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None, use_cache: bool = False, labels: Optional[torch.Tensor] = None, ) -> Dict[str, Any]: """ Forward pass of the Shulker Code model.
Args: input_ids: Token IDs [batch, seq_len] attention_mask: Optional mask [batch, seq_len] past_key_values: KV cache from previous forward passes use_cache: Whether to cache K/V tensors labels: Target token IDs for computing loss
Returns: dict with keys: 'logits', 'loss' (if labels given), 'past_key_values' (if caching) """ B, T = input_ids.shape device = input_ids.device
# Initialize past KV cache if past_key_values is None: past_key_values = [None] * self.config.num_layers
# Token embeddings x = self.embed_dropout(self.embed_tokens(input_ids)) # [B, T, hidden]
# Pass through all decoder layers new_past_key_values = [] if use_cache else None
for i, layer in enumerate(self.layers): x, new_kv = layer( x, attention_mask=attention_mask, past_kv=past_key_values[i], use_cache=use_cache, ) if use_cache: new_past_key_values.append(new_kv)
# Final layer norm x = self.norm(x) # [B, T, hidden]
# Project to vocabulary if self.config.tie_embeddings: logits = F.linear(x, self.embed_tokens.weight) # [B, T, vocab] else: logits = self.lm_head(x) # [B, T, vocab]
# Compute cross-entropy loss if training loss = None if labels is not None: # Shift logits and labels for next-token prediction shift_logits = logits[:, :-1, :].contiguous() shift_labels = labels[:, 1:].contiguous()
loss = F.cross_entropy( shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1), ignore_index=self.config.pad_token_id, )
return { "logits": logits, "loss": loss, "past_key_values": new_past_key_values, "hidden_states": x, }
@classmethod def from_pretrained(cls, path: str, device: str = "cpu") -> "ShulkerCodeModel": """Load a pretrained Shulker Code model from a checkpoint.""" import json, os config_path = os.path.join(path, "config.json") weights_path = os.path.join(path, "model.pt")
with open(config_path) as f: config_dict = json.load(f)
config = ShulkerConfig.from_dict(config_dict) model = cls(config)
state_dict = torch.load(weights_path, map_location=device) model.load_state_dict(state_dict) model.eval() print(f"β
Loaded {config.name} ({model.num_parameters():,} params) from {path}") return model.to(device)
def save_pretrained(self, path: str): """Save model weights and config to a directory.""" import json, os os.makedirs(path, exist_ok=True)
with open(os.path.join(path, "config.json"), "w") as f: json.dump(self.config.to_dict(), f, indent=2)
torch.save(self.state_dict(), os.path.join(path, "model.pt")) print(f"β
Model saved to {path}")model/__init__.pyAdded+15
model/attention.pyAdded+204
model/lora.pyAdded+174
model/transformer.pyAdded+359