Download model.py from Logn001/odpe-progressive-quantization: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/model.py
- Command line
-
hf download hf://Logn001/odpe-progressive-quantization/model.py
-
curl -L -o model.py https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/model.py
11.7 kB
| """Compact bilingual Transformer NLI model for controlled quantization comparison.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from progressive_quant import Granularity, ProgressiveLinear, iter_progressive_layers | |
| class BilingualNLIConfig: | |
| vocab_size: int = 10_000 | |
| max_len: int = 128 | |
| d_model: int = 320 | |
| n_heads: int = 8 | |
| n_layers: int = 6 | |
| d_ff: int = 1280 | |
| dropout: float = 0.1 | |
| num_labels: int = 3 | |
| pad_id: int = 0 | |
| initial_bits: int = 1 | |
| granularity: Granularity = "neuron" | |
| use_block_execution: bool = True | |
| protect_attention_and_head: bool = False | |
| attn_init_bits: int = 2 | |
| head_init_bits: int = 4 | |
| ste_clip: bool = False | |
| use_tier_scales: bool = False | |
| attn_bit_cost_scale: float = 1.0 | |
| ffn_bit_cost_scale: float = 1.0 | |
| head_bit_cost_scale: float = 1.0 | |
| group_size: int = 0 | |
| precision_tenths: bool = False | |
| backbone_max_bits: int | None = None | |
| head_max_bits: int | None = None | |
| use_rms_norm: bool = False | |
| use_rope: bool = False | |
| use_qk_norm: bool = False | |
| use_swiglu: bool = False | |
| class RMSNorm(nn.Module): | |
| """Root-mean-square layer normalization without mean centering or bias shift.""" | |
| def __init__(self, dim: int, eps: float = 1e-6) -> None: | |
| super().__init__() | |
| self.eps = eps | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| norm = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) | |
| return norm * self.weight | |
| def _make_norm(dim: int, use_rms_norm: bool) -> nn.Module: | |
| return RMSNorm(dim) if use_rms_norm else nn.LayerNorm(dim) | |
| class RotaryEmbedding(nn.Module): | |
| """Rotary position embedding (RoPE) for multi-head self-attention.""" | |
| def __init__(self, dim: int, max_len: int = 512, base: float = 10000.0) -> None: | |
| super().__init__() | |
| if dim % 2 != 0: | |
| raise ValueError("head_dim must be even for RoPE") | |
| self.dim = dim | |
| self.base = base | |
| inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) | |
| self.register_buffer("inv_freq", inv_freq, persistent=False) | |
| self.register_buffer("cos_cached", torch.empty(0), persistent=False) | |
| self.register_buffer("sin_cached", torch.empty(0), persistent=False) | |
| self._build_cache(max_len, inv_freq.device) | |
| def _build_cache(self, seq_len: int, device: torch.device) -> None: | |
| t = torch.arange(seq_len, device=device, dtype=torch.float32) | |
| freqs = torch.outer(t, self.inv_freq.to(device)) | |
| emb = torch.cat([freqs, freqs], dim=-1) | |
| self.cos_cached = emb.cos()[None, None, :, :] | |
| self.sin_cached = emb.sin()[None, None, :, :] | |
| def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: | |
| if self.cos_cached.numel() == 0 or self.cos_cached.shape[2] < seq_len or self.cos_cached.device != device: | |
| self._build_cache(max(seq_len, int(self.cos_cached.shape[2]) if self.cos_cached.numel() else seq_len), device) | |
| return self.cos_cached[:, :, :seq_len, :].to(dtype), self.sin_cached[:, :, :seq_len, :].to(dtype) | |
| def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| half = x.shape[-1] // 2 | |
| x1, x2 = x[..., :half], x[..., half:] | |
| rotated = torch.cat((-x2, x1), dim=-1) | |
| return x * cos + rotated * sin | |
| class TransformerEncoderBlock(nn.Module): | |
| """Pre-LN Transformer block using ProgressiveLinear (classical FP32 or progressive).""" | |
| def __init__(self, cfg: BilingualNLIConfig, use_quantization: bool) -> None: | |
| super().__init__() | |
| if cfg.d_model % cfg.n_heads != 0: | |
| raise ValueError("d_model must be divisible by n_heads") | |
| self.n_heads = cfg.n_heads | |
| self.head_dim = cfg.d_model // cfg.n_heads | |
| self.dropout = cfg.dropout | |
| self.use_swiglu = cfg.use_swiglu | |
| attn_bits = cfg.attn_init_bits if cfg.protect_attention_and_head else cfg.initial_bits | |
| attn_kw = dict( | |
| initial_bits=attn_bits, | |
| use_quantization=use_quantization, | |
| granularity=cfg.granularity, | |
| use_block_execution=cfg.use_block_execution, | |
| ste_clip=cfg.ste_clip, | |
| use_tier_scales=cfg.use_tier_scales, | |
| bit_cost_scale=cfg.attn_bit_cost_scale, | |
| group_size=cfg.group_size, | |
| precision_tenths=cfg.precision_tenths, | |
| max_bits=cfg.backbone_max_bits, | |
| ) | |
| ffn_kw = dict( | |
| initial_bits=cfg.initial_bits, | |
| use_quantization=use_quantization, | |
| granularity=cfg.granularity, | |
| use_block_execution=cfg.use_block_execution, | |
| ste_clip=cfg.ste_clip, | |
| use_tier_scales=cfg.use_tier_scales, | |
| bit_cost_scale=cfg.ffn_bit_cost_scale, | |
| group_size=cfg.group_size, | |
| precision_tenths=cfg.precision_tenths, | |
| max_bits=cfg.backbone_max_bits, | |
| ) | |
| self.norm1 = _make_norm(cfg.d_model, cfg.use_rms_norm) | |
| self.q_proj = ProgressiveLinear(cfg.d_model, cfg.d_model, **attn_kw) | |
| self.k_proj = ProgressiveLinear(cfg.d_model, cfg.d_model, **attn_kw) | |
| self.v_proj = ProgressiveLinear(cfg.d_model, cfg.d_model, **attn_kw) | |
| self.out_proj = ProgressiveLinear(cfg.d_model, cfg.d_model, **attn_kw) | |
| self.q_norm = RMSNorm(self.head_dim) if cfg.use_qk_norm else None | |
| self.k_norm = RMSNorm(self.head_dim) if cfg.use_qk_norm else None | |
| self.rope = RotaryEmbedding(self.head_dim, max_len=cfg.max_len) if cfg.use_rope else None | |
| self.norm2 = _make_norm(cfg.d_model, cfg.use_rms_norm) | |
| if cfg.use_swiglu: | |
| self.ffn_gate = ProgressiveLinear(cfg.d_model, cfg.d_ff, bias=False, **ffn_kw) | |
| self.ffn_in = ProgressiveLinear(cfg.d_model, cfg.d_ff, bias=False, **ffn_kw) | |
| self.ffn_out = ProgressiveLinear(cfg.d_ff, cfg.d_model, bias=False, **ffn_kw) | |
| else: | |
| self.ffn_gate = None | |
| self.ffn_in = ProgressiveLinear(cfg.d_model, cfg.d_ff, **ffn_kw) | |
| self.ffn_out = ProgressiveLinear(cfg.d_ff, cfg.d_model, **ffn_kw) | |
| self.drop = nn.Dropout(cfg.dropout) | |
| def forward(self, x: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: | |
| bsz, seq_len, _ = x.shape | |
| h = self.norm1(x) | |
| q = self.q_proj(h).view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2) | |
| k = self.k_proj(h).view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2) | |
| v = self.v_proj(h).view(bsz, seq_len, self.n_heads, self.head_dim).transpose(1, 2) | |
| if self.q_norm is not None: | |
| q = self.q_norm(q) | |
| k = self.k_norm(k) | |
| if self.rope is not None: | |
| cos, sin = self.rope(seq_len, q.device, q.dtype) | |
| q = _apply_rope(q, cos, sin) | |
| k = _apply_rope(k, cos, sin) | |
| attn_mask = attention_mask[:, None, None, :] # (B, 1, 1, L), True = attend | |
| attn_out = F.scaled_dot_product_attention( | |
| q, | |
| k, | |
| v, | |
| attn_mask=attn_mask, | |
| dropout_p=self.dropout if self.training else 0.0, | |
| ) | |
| attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, seq_len, -1) | |
| x = x + self.drop(self.out_proj(attn_out)) | |
| h2 = self.norm2(x) | |
| if self.ffn_gate is not None: | |
| ffn_hidden = F.silu(self.ffn_gate(h2)) * self.ffn_in(h2) | |
| else: | |
| ffn_hidden = F.gelu(self.ffn_in(h2)) | |
| ffn_out = self.ffn_out(self.drop(ffn_hidden)) | |
| return x + self.drop(ffn_out) | |
| class BilingualNLITransformer(nn.Module): | |
| """Identical Transformer Cross-Encoder supporting FP32 baseline and progressive mode.""" | |
| def __init__(self, cfg: BilingualNLIConfig, use_quantization: bool) -> None: | |
| super().__init__() | |
| self.cfg = cfg | |
| self.use_quantization = use_quantization | |
| self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model, padding_idx=cfg.pad_id) | |
| self.pos_emb = None if cfg.use_rope else nn.Embedding(cfg.max_len, cfg.d_model) | |
| self.seg_emb = nn.Embedding(2, cfg.d_model) | |
| self.emb_norm = _make_norm(cfg.d_model, cfg.use_rms_norm) | |
| self.emb_drop = nn.Dropout(cfg.dropout) | |
| self.blocks = nn.ModuleList( | |
| [TransformerEncoderBlock(cfg, use_quantization=use_quantization) for _ in range(cfg.n_layers)] | |
| ) | |
| self.final_norm = _make_norm(cfg.d_model, cfg.use_rms_norm) | |
| head_proj_bits = cfg.attn_init_bits if cfg.protect_attention_and_head else cfg.initial_bits | |
| head_out_bits = cfg.head_init_bits if cfg.protect_attention_and_head else cfg.initial_bits | |
| self.head_proj = ProgressiveLinear( | |
| cfg.d_model * 2, | |
| cfg.d_model, | |
| initial_bits=head_proj_bits, | |
| use_quantization=use_quantization, | |
| granularity=cfg.granularity, | |
| use_block_execution=cfg.use_block_execution, | |
| ste_clip=cfg.ste_clip, | |
| use_tier_scales=cfg.use_tier_scales, | |
| bit_cost_scale=cfg.head_bit_cost_scale, | |
| group_size=cfg.group_size, | |
| precision_tenths=cfg.precision_tenths, | |
| max_bits=cfg.head_max_bits, | |
| ) | |
| self.head_out = ProgressiveLinear( | |
| cfg.d_model, | |
| cfg.num_labels, | |
| initial_bits=head_out_bits, | |
| use_quantization=use_quantization, | |
| granularity=cfg.granularity, | |
| use_block_execution=cfg.use_block_execution, | |
| ste_clip=cfg.ste_clip, | |
| use_tier_scales=cfg.use_tier_scales, | |
| bit_cost_scale=cfg.head_bit_cost_scale, | |
| group_size=cfg.group_size, | |
| precision_tenths=cfg.precision_tenths, | |
| max_bits=cfg.head_max_bits, | |
| ) | |
| self.apply(self._init_weights) | |
| def _init_weights(self, module: nn.Module) -> None: | |
| if isinstance(module, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(module.weight, mean=0.0, std=0.02) | |
| if isinstance(module, nn.Linear) and module.bias is not None: | |
| nn.init.zeros_(module.bias) | |
| elif isinstance(module, nn.LayerNorm): | |
| nn.init.ones_(module.weight) | |
| nn.init.zeros_(module.bias) | |
| elif isinstance(module, RMSNorm): | |
| nn.init.ones_(module.weight) | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| token_type_ids: torch.Tensor, | |
| attention_mask: torch.Tensor, | |
| ) -> torch.Tensor: | |
| bsz, seq_len = input_ids.shape | |
| x = self.tok_emb(input_ids) + self.seg_emb(token_type_ids) | |
| if self.pos_emb is not None: | |
| pos_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(bsz, -1) | |
| x = x + self.pos_emb(pos_ids) | |
| x = self.emb_drop(self.emb_norm(x)) | |
| for block in self.blocks: | |
| x = block(x, attention_mask) | |
| x = self.final_norm(x) | |
| cls_repr = x[:, 0] | |
| mask_f = attention_mask.unsqueeze(-1).float() | |
| mean_repr = (x * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp_min(1.0) | |
| combined = torch.cat([cls_repr, mean_repr], dim=-1) | |
| hidden = self.emb_drop(F.gelu(self.head_proj(combined))) | |
| return self.head_out(hidden) | |
| def count_parameters(model: nn.Module) -> dict[str, int]: | |
| total = sum(p.numel() for p in model.parameters()) | |
| quant_managed = sum(layer.weight.numel() for layer in iter_progressive_layers(model)) | |
| return {"total_params": total, "adaptive_linear_params": quant_managed} | |