Text Generation
Transformers
Safetensors
Korean
English
perdix
custom_code
conversational
instruct
differential-attention
polynorm
Instructions to use prismdata/Perdix-1.1B-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use prismdata/Perdix-1.1B-Instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="prismdata/Perdix-1.1B-Instruct", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("prismdata/Perdix-1.1B-Instruct", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use prismdata/Perdix-1.1B-Instruct with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "prismdata/Perdix-1.1B-Instruct" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/prismdata/Perdix-1.1B-Instruct
- SGLang
How to use prismdata/Perdix-1.1B-Instruct with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "prismdata/Perdix-1.1B-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "prismdata/Perdix-1.1B-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use prismdata/Perdix-1.1B-Instruct with Docker Model Runner:
docker model run hf.co/prismdata/Perdix-1.1B-Instruct
Download modeling_perdix.py from prismdata/Perdix-1.1B-Instruct: direct link, hf CLI and curl.
- Browser
- Download file 8.68 kB
-
https://huggingface.co/prismdata/Perdix-1.1B-Instruct/resolve/main/modeling_perdix.py
- Command line
-
hf download hf://prismdata/Perdix-1.1B-Instruct/modeling_perdix.py
-
curl -L -o modeling_perdix.py https://huggingface.co/prismdata/Perdix-1.1B-Instruct/resolve/main/modeling_perdix.py
8.68 kB
| """Perdix: Differential Attention + PolyNorm ๊ธฐ๋ฐ decoder-only LM (transformers ์ฐ๋์ฉ). | |
| ํ์ต ์ฝ๋(model.py)์ PerdixSLM๊ณผ ๋ชจ๋ ์ด๋ฆ์ด ๊ฐ์ state_dict๊ฐ ๊ทธ๋๋ก ํธํ๋๋ค. | |
| KV ์บ์๋ ๊ตฌํํ์ง ์์๋ค(์์ฑ ์ ๋งค ์คํ ์ ์ฒด ์ํ์ค๋ฅผ ๋ค์ ๊ณ์ฐ). | |
| ํจ๋ฉ ๋ง์คํฌ๋ ์๋ค: attention_mask๋ ๋ฌด์๋๋ฉฐ causal ๋ง์คํฌ๋ง ์ ์ฉ๋๋ค. | |
| """ | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import GenerationMixin, PreTrainedModel | |
| from transformers.modeling_outputs import CausalLMOutput | |
| from .configuration_perdix import PerdixConfig | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim, eps=1e-5): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| self.eps = eps | |
| def forward(self, x): | |
| dtype = x.dtype | |
| x = x.float() | |
| x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) | |
| return (x * self.weight.float()).to(dtype) | |
| class PolyNorm(nn.Module): | |
| """poly_norm(x) = w1*rms(x) + w2*rms(x^2) + w3*rms(x^3) + b""" | |
| def __init__(self): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.full((3,), 1.0 / 3.0)) | |
| self.bias = nn.Parameter(torch.zeros(1)) | |
| def _rms(x, eps=1e-6): | |
| return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) | |
| def forward(self, x): | |
| xf = x.float() | |
| out = (self.weight[0] * self._rms(xf) | |
| + self.weight[1] * self._rms(xf ** 2) | |
| + self.weight[2] * self._rms(xf ** 3) | |
| + self.bias) | |
| return out.to(x.dtype) | |
| def precompute_rope(head_dim, max_seq_len, theta): | |
| inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim)) | |
| t = torch.arange(max_seq_len).float() | |
| freqs = torch.outer(t, inv_freq) | |
| return torch.cos(freqs), torch.sin(freqs) | |
| def apply_rope(x, cos, sin): | |
| # x: (B, H, T, D) -> ์ง/ํ ์ฑ๋ถ ํ์ | |
| x1, x2 = x[..., 0::2], x[..., 1::2] | |
| T = x.shape[-2] | |
| cos, sin = cos[:T].to(x.dtype), sin[:T].to(x.dtype) | |
| out = torch.empty_like(x) | |
| out[..., 0::2] = x1 * cos - x2 * sin | |
| out[..., 1::2] = x1 * sin + x2 * cos | |
| return out | |
| class DifferentialAttention(nn.Module): | |
| """๋ ๊ฐ์ ์ดํ ์ ๋งต ์ฐจ์ด๋ก ๋ ธ์ด์ฆ๋ฅผ ์์ํ๋ ์ดํ ์ . | |
| ํ์ค ์ดํ ์ ๊ณผ ๋์ผํ ํ๋ผ๋ฏธํฐ ์: head_dim์ ๋ฐ์ผ๋ก ๋๋ | |
| (Q1,K1), (Q2,K2) ๋ ์์ ๋ง๋ค๊ณ softmax ๋งต์ lambda ๊ฐ์ค์ผ๋ก ๋บ๋ค. | |
| ๊ฐ ํญ์ด ํ์ค softmax(QK^T)V ๊ผด์ด๋ฏ๋ก SDPA(flash attention) 2ํ๋ก ๊ณ์ฐ. | |
| """ | |
| def __init__(self, cfg, layer_idx: int): | |
| super().__init__() | |
| self.n_heads = cfg.n_heads | |
| self.head_dim = cfg.dim // cfg.n_heads // 2 # ๋ฐ์ผ๋ก ์ชผ๊ฐ 2์ | |
| self.wq = nn.Linear(cfg.dim, cfg.dim, bias=False) | |
| self.wk = nn.Linear(cfg.dim, cfg.dim, bias=False) | |
| self.wv = nn.Linear(cfg.dim, cfg.dim, bias=False) | |
| self.wo = nn.Linear(cfg.dim, cfg.dim, bias=False) | |
| # lambda ์ฌํ๋ผ๋ฏธํฐํ (Differential Transformer eq.2) | |
| self.lambda_init = 0.8 - 0.6 * math.exp(-0.3 * layer_idx) | |
| d = self.head_dim | |
| self.lambda_q1 = nn.Parameter(torch.randn(d) * 0.1) | |
| self.lambda_k1 = nn.Parameter(torch.randn(d) * 0.1) | |
| self.lambda_q2 = nn.Parameter(torch.randn(d) * 0.1) | |
| self.lambda_k2 = nn.Parameter(torch.randn(d) * 0.1) | |
| # ํค๋๋ณ RMSNorm (๋ ผ๋ฌธ์ GroupNorm ์ญํ ) | |
| self.subln = RMSNorm(2 * self.head_dim, eps=cfg.norm_eps) | |
| def forward(self, x, cos, sin): | |
| B, T, C = x.shape | |
| H, D = self.n_heads, self.head_dim | |
| # (B, T, C) -> (B, 2H, T, D): ํค๋๋น (Q1,Q2), (K1,K2) ์ | |
| q = self.wq(x).view(B, T, 2 * H, D).transpose(1, 2) | |
| k = self.wk(x).view(B, T, 2 * H, D).transpose(1, 2) | |
| # V(head_dim 2D)๋ฅผ D์ง๋ฆฌ ๋ ํค๋๋ก ํผ์นจ โ Q/K/V head_dim์ ๋ง์ถฐ์ผ | |
| # flash attention ์ปค๋ ์๊ฒฉ์ด ๋๊ณ (math ํด๋ฐฑ ๋ฐฉ์ง), ๊ฒฐ๊ณผ๋ ์ํ์ ์ผ๋ก ๋์ผ | |
| v = self.wv(x).view(B, T, 2 * H, D).transpose(1, 2) | |
| q = apply_rope(q, cos, sin) | |
| k = apply_rope(k, cos, sin) | |
| q1, q2 = q[:, 0::2], q[:, 1::2] # ๊ฐ (B, H, T, D) | |
| k1, k2 = k[:, 0::2], k[:, 1::2] | |
| # ๊ฐ์ ์ดํ ์ ๋งต์ V์ ๋ ๋ฐ์ชฝ์ ์ ์ฉํ๋๋ก ํค๋ ์ถ์ผ๋ก ๋ณต์ | |
| q1r = q1.repeat_interleave(2, dim=1) # (B, 2H, T, D) | |
| k1r = k1.repeat_interleave(2, dim=1) | |
| q2r = q2.repeat_interleave(2, dim=1) | |
| k2r = k2.repeat_interleave(2, dim=1) | |
| a1 = F.scaled_dot_product_attention(q1r, k1r, v, is_causal=True) | |
| a2 = F.scaled_dot_product_attention(q2r, k2r, v, is_causal=True) | |
| # (B, 2H, T, D) -> (B, H, T, 2D) ๋ณต์ | |
| a1 = a1.view(B, H, 2, T, D).permute(0, 1, 3, 2, 4).reshape(B, H, T, 2 * D) | |
| a2 = a2.view(B, H, 2, T, D).permute(0, 1, 3, 2, 4).reshape(B, H, T, 2 * D) | |
| lam1 = torch.exp((self.lambda_q1 * self.lambda_k1).sum().float()) | |
| lam2 = torch.exp((self.lambda_q2 * self.lambda_k2).sum().float()) | |
| lam = (lam1 - lam2 + self.lambda_init).to(x.dtype) | |
| attn = a1 - lam * a2 # (B, H, T, 2D) | |
| attn = self.subln(attn) * (1.0 - self.lambda_init) | |
| attn = attn.transpose(1, 2).reshape(B, T, C) | |
| return self.wo(attn) | |
| class FeedForward(nn.Module): | |
| """Linear -> PolyNorm -> Linear (Motif ๊ทธ๋ฆผ 1์ ๋น๊ฒ์ดํธ FFN)""" | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.up = nn.Linear(cfg.dim, cfg.ffn_dim, bias=False) | |
| self.act = PolyNorm() | |
| self.down = nn.Linear(cfg.ffn_dim, cfg.dim, bias=False) | |
| def forward(self, x): | |
| return self.down(self.act(self.up(x))) | |
| class Block(nn.Module): | |
| def __init__(self, cfg, layer_idx: int): | |
| super().__init__() | |
| self.attn_norm = RMSNorm(cfg.dim, cfg.norm_eps) | |
| self.attn = DifferentialAttention(cfg, layer_idx) | |
| self.ffn_norm = RMSNorm(cfg.dim, cfg.norm_eps) | |
| self.ffn = FeedForward(cfg) | |
| def forward(self, x, cos, sin): | |
| x = x + self.attn(self.attn_norm(x), cos, sin) | |
| x = x + self.ffn(self.ffn_norm(x)) | |
| return x | |
| class PerdixForCausalLM(PreTrainedModel, GenerationMixin): | |
| config_class = PerdixConfig | |
| base_model_prefix = "" | |
| # transformers 5.x๋ {๋ฌถ์ด๋ ํค: ์๋ณธ ํค} dict, 4.x๋ ํค ๋ชฉ๋ก์ ๊ธฐ๋ํ๋ค. dict๋ ์์ชฝ ๋ค ๋์. | |
| _tied_weights_keys = {"lm_head.weight": "tok_emb.weight"} | |
| _supports_cache_class = False | |
| def __init__(self, config: PerdixConfig): | |
| super().__init__(config) | |
| self.tok_emb = nn.Embedding(config.vocab_size, config.dim) | |
| self.blocks = nn.ModuleList( | |
| [Block(config, i) for i in range(config.n_layers)]) | |
| self.final_norm = RMSNorm(config.dim, config.norm_eps) | |
| self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False) | |
| # RoPE ํ๋ buffer๋ก ๋์ง ์๊ณ ์ฒซ forward์์ ๋ง๋ ๋ค. transformers 5.x๋ ๋ชจ๋ธ์ meta ์ฅ์น์์ | |
| # ๋ง๋ ๋ค ๊ฐ์ค์น๋ง ์ฑ์ฐ๋ฏ๋ก, ์ ์ฅ๋์ง ์๋(non-persistent) buffer๋ ๋ด์ฉ์ด ๋ ์๊ฐ๋ค. | |
| self._rope = None | |
| self.post_init() | |
| def _init_weights(self, m): | |
| if isinstance(m, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(m.weight, mean=0.0, std=self.config.init_std) | |
| def get_input_embeddings(self): | |
| return self.tok_emb | |
| def set_input_embeddings(self, value): | |
| self.tok_emb = value | |
| def get_output_embeddings(self): | |
| return self.lm_head | |
| def set_output_embeddings(self, value): | |
| self.lm_head = value | |
| def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs): | |
| x = self.tok_emb(input_ids) | |
| if self._rope is None or self._rope[0].device != x.device: | |
| head_dim = self.config.dim // self.config.n_heads // 2 | |
| cos, sin = precompute_rope(head_dim, self.config.max_seq_len, self.config.rope_theta) | |
| self._rope = (cos.to(x.device), sin.to(x.device)) | |
| for blk in self.blocks: | |
| x = blk(x, *self._rope) | |
| logits = self.lm_head(self.final_norm(x)) | |
| loss = None | |
| if labels is not None: | |
| loss = F.cross_entropy( | |
| logits[:, :-1].float().reshape(-1, logits.size(-1)), | |
| labels[:, 1:].reshape(-1), ignore_index=-100) | |
| return CausalLMOutput(loss=loss, logits=logits) | |
| def prepare_inputs_for_generation(self, input_ids, **kwargs): | |
| # ์บ์๊ฐ ์์ผ๋ฏ๋ก ๋งค ์คํ ์ต๊ทผ max_seq_len ํ ํฐ ์ ์ฒด๋ฅผ ๋ค์ ๋ฃ๋๋ค | |
| return {"input_ids": input_ids[:, -self.config.max_seq_len:]} | |