Text Generation
Transformers
Safetensors
Korean
English
perdix
custom_code
base-model
differential-attention
polynorm
Instructions to use prismdata/Perdix-1.1B-Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use prismdata/Perdix-1.1B-Base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="prismdata/Perdix-1.1B-Base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("prismdata/Perdix-1.1B-Base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use prismdata/Perdix-1.1B-Base 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-Base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/prismdata/Perdix-1.1B-Base
- SGLang
How to use prismdata/Perdix-1.1B-Base 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-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'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-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "prismdata/Perdix-1.1B-Base", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use prismdata/Perdix-1.1B-Base with Docker Model Runner:
docker model run hf.co/prismdata/Perdix-1.1B-Base
Perdix-1.1B-Base 최초 업로드
Browse files- README.md +95 -0
- config.json +25 -0
- configuration_perdix.py +27 -0
- generation_config.json +8 -0
- model.safetensors +3 -0
- modeling_perdix.py +214 -0
- special_tokens_map.json +5 -0
- tokenizer.json +0 -0
- tokenizer_config.json +27 -0
README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- ko
|
| 5 |
+
- en
|
| 6 |
+
library_name: transformers
|
| 7 |
+
pipeline_tag: text-generation
|
| 8 |
+
tags:
|
| 9 |
+
- custom_code
|
| 10 |
+
- base-model
|
| 11 |
+
- differential-attention
|
| 12 |
+
- polynorm
|
| 13 |
+
datasets:
|
| 14 |
+
- mlfoundations/dclm-baseline-1.0
|
| 15 |
+
- HuggingFaceFW/fineweb-2
|
| 16 |
+
- HuggingFaceTB/finemath
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# Perdix-1.1B-Base
|
| 20 |
+
|
| 21 |
+
작은 수준의 LLM으로 이름은 그리스 신화의 페르딕스에서 따왔습니다. 다이달로스의 어린 제자였고 톱과 컴퍼스를 발명했는데, 탑에서 떨어지다 자고새가 되는 바람에 그 뒤로는 낮게만 날아다닌다고 합니다. 지금 이 모델 수준이 딱 그렇습니다.
|
| 22 |
+
|
| 23 |
+
A 1.1B-parameter Korean/English base language model pretrained from scratch on a single machine. It only continues text; it has not been trained to chat or follow instructions.
|
| 24 |
+
|
| 25 |
+
## 무엇을 할 수 있고 무엇을 못 하나
|
| 26 |
+
|
| 27 |
+
**베이스 모델**입니다. 문장 앞부분을 주면 뒤를 잇는 것만 합니다. 질문에 답하거나 지시를 따르도록 학습시킨 적이 없어서, 대화용으로 쓰면 엉뚱한 글이 나옵니다.
|
| 28 |
+
|
| 29 |
+
이어 쓴 글은 문장으로는 그럴듯하지만 **내용은 자주 틀립니다.** 아래는 실제 출력입니다(temperature 0.8, top-k 50). 굵은 부분이 입력입니다.
|
| 30 |
+
|
| 31 |
+
> **대한민국의 수도 서울은** 세계 4대 문명 발상지이자 최대 도시이자 민주주의의 중심지로 알려져 있다. 그만큼 서울의 역사도 오래되었는데, 1905년 1월 4일 일본 제국이 서울에 신사·불각과 함께 …
|
| 32 |
+
|
| 33 |
+
> **The capital city of France is** Cannes, a city of the seas. And now, in Cannes, in this particular place, I'm going to speak about the culture of the city. …
|
| 34 |
+
|
| 35 |
+
> **김치는 한국의 전통 음식으로**, 다양한 재료를 사용해 김치를 담그는 문화와 식문화를 경험해 볼 수 있습니다. Q: 김치는 어떤 재료로 만들어지나요? A: 김치는 다양한 재료를 사용하여 만들어집니다. 주로 고춧가루, 마늘, 생강 등이 사용되며 …
|
| 36 |
+
|
| 37 |
+
사실 확인이 필요한 용도에는 쓰면 안 됩니다. 학습 데이터가 웹 문서라 편향되거나 부적절한 내용이 나올 수 있습니다.
|
| 38 |
+
|
| 39 |
+
## 사용법
|
| 40 |
+
|
| 41 |
+
모델 코드가 저장소에 들어 있어서 `trust_remote_code=True`가 필요합니다.
|
| 42 |
+
|
| 43 |
+
```python
|
| 44 |
+
import torch
|
| 45 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 46 |
+
|
| 47 |
+
repo = "prismdata/Perdix-1.1B-Base"
|
| 48 |
+
tok = AutoTokenizer.from_pretrained(repo)
|
| 49 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 50 |
+
repo, trust_remote_code=True, torch_dtype=torch.bfloat16).to("cuda").eval()
|
| 51 |
+
|
| 52 |
+
ids = tok("대한민국의 수도 서울은", return_tensors="pt").input_ids.to("cuda")
|
| 53 |
+
out = model.generate(ids, max_new_tokens=100, do_sample=True, temperature=0.8, top_k=50)
|
| 54 |
+
print(tok.decode(out[0], skip_special_tokens=True))
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
알아 둘 점이 있습니다.
|
| 58 |
+
|
| 59 |
+
- 문맥 길이는 2,048토큰입니다.
|
| 60 |
+
- KV 캐시를 구현하지 않아 생성할 때마다 전체 시퀀스를 다시 계산합니다. 길게 생성하면 느립니다.
|
| 61 |
+
- 패딩 마스크가 없습니다. `attention_mask`는 무시되므로, 길이가 다른 문장을 패딩해서 한 배치로 생성하면 결과가 틀어집니다. 한 문장씩 넣으세요.
|
| 62 |
+
|
| 63 |
+
## 모델
|
| 64 |
+
|
| 65 |
+
| 항목 | 값 |
|
| 66 |
+
|---|---|
|
| 67 |
+
| 파라미터 | 1,107M |
|
| 68 |
+
| 구조 | decoder-only, pre-RMSNorm, RoPE, 입출력 임베딩 공유 |
|
| 69 |
+
| 층 / 차원 / 헤드 | 20 / 2048 / 16 |
|
| 70 |
+
| FFN 차원 | 8192 |
|
| 71 |
+
| 문맥 길이 | 2,048 |
|
| 72 |
+
| 어휘 | 49,152 (BPE) |
|
| 73 |
+
| 가중치 형식 | float32 safetensors |
|
| 74 |
+
|
| 75 |
+
일반 트랜스포머와 다른 점은 두 가지입니다.
|
| 76 |
+
|
| 77 |
+
- **Differential Attention.** 어텐션 맵을 두 개 만들어 하나에서 다른 하나를 뺍니다. 양쪽에 공통으로 끼는 잡음을 상쇄하려는 아이디어입니다.
|
| 78 |
+
- **PolyNorm.** 활성 함수 자리에 x, x², x³을 각각 정규화해서 학습되는 가중치로 섞어 씁니다.
|
| 79 |
+
|
| 80 |
+
둘 다 제가 고안한 게 아니고 Motif-2.6B 기술보고서([arXiv:2508.09148](https://arxiv.org/abs/2508.09148))와 Differential Transformer(Ye et al., 2024)를 읽고 직접 구현해 본 것입니다. 원 저자들과는 관계없는 개인 구현이라, 틀린 부분이 있다면 제 실수입니다.
|
| 81 |
+
|
| 82 |
+
## 학습
|
| 83 |
+
|
| 84 |
+
- **데이터**: 30B 토큰. 영어 웹([DCLM-baseline](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0), CC-BY-4.0), 한국어 웹([FineWeb2](https://huggingface.co/datasets/HuggingFaceFW/fineweb-2) kor_Hang, ODC-By), 수학([FineMath](https://huggingface.co/datasets/HuggingFaceTB/finemath) 4+, ODC-By)
|
| 85 |
+
- **믹싱**: 영어 65% / 한국어 30% / 수학 5%에서 시작해 25% / 50% / 25%로 서서히 바꿨습니다.
|
| 86 |
+
- **학습률**: 최고 3e-4. 1B 토큰 워밍업 뒤 유지하다 마지막 20% 구간에서 최고값의 25%까지 내렸습니다.
|
| 87 |
+
- **배치**: 스텝당 약 1M 토큰, 시퀀스 길이 2,048, bf16
|
| 88 |
+
- **결과**: loss 10.7 → 2.3 근처
|
| 89 |
+
- **장비**: DGX Spark 한 대
|
| 90 |
+
|
| 91 |
+
학습 코드는 [github.com/theprismdata/Perdix](https://github.com/theprismdata/Perdix)에 있습니다.
|
| 92 |
+
|
| 93 |
+
## 라이선스
|
| 94 |
+
|
| 95 |
+
Apache-2.0. 학습 데이터의 출처와 라이선스는 위에 적었습니다.
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"PerdixForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_perdix.PerdixConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_perdix.PerdixForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"bos_token_id": 0,
|
| 10 |
+
"dim": 2048,
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"eos_token_id": 0,
|
| 13 |
+
"ffn_dim": 8192,
|
| 14 |
+
"init_std": 0.02,
|
| 15 |
+
"max_seq_len": 2048,
|
| 16 |
+
"model_type": "perdix",
|
| 17 |
+
"n_heads": 16,
|
| 18 |
+
"n_layers": 20,
|
| 19 |
+
"norm_eps": 1e-05,
|
| 20 |
+
"pad_token_id": 1,
|
| 21 |
+
"rope_theta": 10000.0,
|
| 22 |
+
"transformers_version": "4.57.6",
|
| 23 |
+
"use_cache": false,
|
| 24 |
+
"vocab_size": 49152
|
| 25 |
+
}
|
configuration_perdix.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Perdix 설정 (transformers 연동용)."""
|
| 2 |
+
from transformers import PretrainedConfig
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class PerdixConfig(PretrainedConfig):
|
| 6 |
+
model_type = "perdix"
|
| 7 |
+
attribute_map = {"hidden_size": "dim", "num_hidden_layers": "n_layers",
|
| 8 |
+
"num_attention_heads": "n_heads",
|
| 9 |
+
"max_position_embeddings": "max_seq_len"}
|
| 10 |
+
|
| 11 |
+
def __init__(self, vocab_size=49152, dim=2048, n_layers=20, n_heads=16,
|
| 12 |
+
ffn_dim=8192, max_seq_len=2048, rope_theta=10000.0,
|
| 13 |
+
norm_eps=1e-5, init_std=0.02, bos_token_id=0, eos_token_id=0,
|
| 14 |
+
pad_token_id=1, tie_word_embeddings=True, **kwargs):
|
| 15 |
+
self.vocab_size = vocab_size
|
| 16 |
+
self.dim = dim
|
| 17 |
+
self.n_layers = n_layers
|
| 18 |
+
self.n_heads = n_heads # differential attention은 head_dim을 반으로 나눠 2쌍 사용
|
| 19 |
+
self.ffn_dim = ffn_dim
|
| 20 |
+
self.max_seq_len = max_seq_len
|
| 21 |
+
self.rope_theta = rope_theta
|
| 22 |
+
self.norm_eps = norm_eps
|
| 23 |
+
self.init_std = init_std
|
| 24 |
+
kwargs.setdefault("use_cache", False) # KV 캐시 미구현
|
| 25 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id,
|
| 26 |
+
pad_token_id=pad_token_id,
|
| 27 |
+
tie_word_embeddings=tie_word_embeddings, **kwargs)
|
generation_config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 0,
|
| 4 |
+
"eos_token_id": 0,
|
| 5 |
+
"pad_token_id": 1,
|
| 6 |
+
"transformers_version": "4.57.6",
|
| 7 |
+
"use_cache": false
|
| 8 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:373834a202dd03b04b9ce476c9bc277c0e296081fd15a0612584ff9972eb88b9
|
| 3 |
+
size 4429581264
|
modeling_perdix.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Perdix: Differential Attention + PolyNorm 기반 decoder-only LM (transformers 연동용).
|
| 2 |
+
|
| 3 |
+
학습 코드(model.py)의 PerdixSLM과 모듈 이름이 같아 state_dict가 그대로 호환된다.
|
| 4 |
+
KV 캐시는 구현하지 않았다(생성 시 매 스텝 전체 시퀀스를 다시 계산).
|
| 5 |
+
패딩 마스크도 없다: attention_mask는 무시되며 causal 마스크만 적용된다.
|
| 6 |
+
"""
|
| 7 |
+
import math
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from transformers import GenerationMixin, PreTrainedModel
|
| 13 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 14 |
+
|
| 15 |
+
from .configuration_perdix import PerdixConfig
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RMSNorm(nn.Module):
|
| 19 |
+
def __init__(self, dim, eps=1e-5):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 22 |
+
self.eps = eps
|
| 23 |
+
|
| 24 |
+
def forward(self, x):
|
| 25 |
+
dtype = x.dtype
|
| 26 |
+
x = x.float()
|
| 27 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 28 |
+
return (x * self.weight.float()).to(dtype)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class PolyNorm(nn.Module):
|
| 32 |
+
"""poly_norm(x) = w1*rms(x) + w2*rms(x^2) + w3*rms(x^3) + b"""
|
| 33 |
+
|
| 34 |
+
def __init__(self):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.weight = nn.Parameter(torch.full((3,), 1.0 / 3.0))
|
| 37 |
+
self.bias = nn.Parameter(torch.zeros(1))
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _rms(x, eps=1e-6):
|
| 41 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
xf = x.float()
|
| 45 |
+
out = (self.weight[0] * self._rms(xf)
|
| 46 |
+
+ self.weight[1] * self._rms(xf ** 2)
|
| 47 |
+
+ self.weight[2] * self._rms(xf ** 3)
|
| 48 |
+
+ self.bias)
|
| 49 |
+
return out.to(x.dtype)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def precompute_rope(head_dim, max_seq_len, theta):
|
| 53 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 54 |
+
t = torch.arange(max_seq_len).float()
|
| 55 |
+
freqs = torch.outer(t, inv_freq)
|
| 56 |
+
return torch.cos(freqs), torch.sin(freqs)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def apply_rope(x, cos, sin):
|
| 60 |
+
# x: (B, H, T, D) -> 짝/홀 성분 회전
|
| 61 |
+
x1, x2 = x[..., 0::2], x[..., 1::2]
|
| 62 |
+
T = x.shape[-2]
|
| 63 |
+
cos, sin = cos[:T].to(x.dtype), sin[:T].to(x.dtype)
|
| 64 |
+
out = torch.empty_like(x)
|
| 65 |
+
out[..., 0::2] = x1 * cos - x2 * sin
|
| 66 |
+
out[..., 1::2] = x1 * sin + x2 * cos
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class DifferentialAttention(nn.Module):
|
| 71 |
+
"""두 개의 어텐션 맵 차이로 노이즈를 상쇄하는 어텐션.
|
| 72 |
+
|
| 73 |
+
표준 어텐션과 동일한 파라미터 수: head_dim을 반으로 나눠
|
| 74 |
+
(Q1,K1), (Q2,K2) 두 쌍을 만들고 softmax 맵을 lambda 가중으로 뺀다.
|
| 75 |
+
각 항이 표준 softmax(QK^T)V 꼴이므로 SDPA(flash attention) 2회로 계산.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, cfg, layer_idx: int):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.n_heads = cfg.n_heads
|
| 81 |
+
self.head_dim = cfg.dim // cfg.n_heads // 2 # 반으로 쪼개 2쌍
|
| 82 |
+
self.wq = nn.Linear(cfg.dim, cfg.dim, bias=False)
|
| 83 |
+
self.wk = nn.Linear(cfg.dim, cfg.dim, bias=False)
|
| 84 |
+
self.wv = nn.Linear(cfg.dim, cfg.dim, bias=False)
|
| 85 |
+
self.wo = nn.Linear(cfg.dim, cfg.dim, bias=False)
|
| 86 |
+
|
| 87 |
+
# lambda 재파라미터화 (Differential Transformer eq.2)
|
| 88 |
+
self.lambda_init = 0.8 - 0.6 * math.exp(-0.3 * layer_idx)
|
| 89 |
+
d = self.head_dim
|
| 90 |
+
self.lambda_q1 = nn.Parameter(torch.randn(d) * 0.1)
|
| 91 |
+
self.lambda_k1 = nn.Parameter(torch.randn(d) * 0.1)
|
| 92 |
+
self.lambda_q2 = nn.Parameter(torch.randn(d) * 0.1)
|
| 93 |
+
self.lambda_k2 = nn.Parameter(torch.randn(d) * 0.1)
|
| 94 |
+
|
| 95 |
+
# 헤드별 RMSNorm (논문의 GroupNorm 역할)
|
| 96 |
+
self.subln = RMSNorm(2 * self.head_dim, eps=cfg.norm_eps)
|
| 97 |
+
|
| 98 |
+
def forward(self, x, cos, sin):
|
| 99 |
+
B, T, C = x.shape
|
| 100 |
+
H, D = self.n_heads, self.head_dim
|
| 101 |
+
|
| 102 |
+
# (B, T, C) -> (B, 2H, T, D): 헤드당 (Q1,Q2), (K1,K2) 쌍
|
| 103 |
+
q = self.wq(x).view(B, T, 2 * H, D).transpose(1, 2)
|
| 104 |
+
k = self.wk(x).view(B, T, 2 * H, D).transpose(1, 2)
|
| 105 |
+
# V(head_dim 2D)를 D짜리 두 헤드로 펼침 — Q/K/V head_dim을 맞춰야
|
| 106 |
+
# flash attention 커널 자격이 되고(math 폴백 방지), 결과는 수학적으로 동일
|
| 107 |
+
v = self.wv(x).view(B, T, 2 * H, D).transpose(1, 2)
|
| 108 |
+
|
| 109 |
+
q = apply_rope(q, cos, sin)
|
| 110 |
+
k = apply_rope(k, cos, sin)
|
| 111 |
+
|
| 112 |
+
q1, q2 = q[:, 0::2], q[:, 1::2] # 각 (B, H, T, D)
|
| 113 |
+
k1, k2 = k[:, 0::2], k[:, 1::2]
|
| 114 |
+
|
| 115 |
+
# 같은 어텐션 맵을 V의 두 반쪽에 적용하도록 헤드 축으로 복제
|
| 116 |
+
q1r = q1.repeat_interleave(2, dim=1) # (B, 2H, T, D)
|
| 117 |
+
k1r = k1.repeat_interleave(2, dim=1)
|
| 118 |
+
q2r = q2.repeat_interleave(2, dim=1)
|
| 119 |
+
k2r = k2.repeat_interleave(2, dim=1)
|
| 120 |
+
|
| 121 |
+
a1 = F.scaled_dot_product_attention(q1r, k1r, v, is_causal=True)
|
| 122 |
+
a2 = F.scaled_dot_product_attention(q2r, k2r, v, is_causal=True)
|
| 123 |
+
# (B, 2H, T, D) -> (B, H, T, 2D) 복원
|
| 124 |
+
a1 = a1.view(B, H, 2, T, D).permute(0, 1, 3, 2, 4).reshape(B, H, T, 2 * D)
|
| 125 |
+
a2 = a2.view(B, H, 2, T, D).permute(0, 1, 3, 2, 4).reshape(B, H, T, 2 * D)
|
| 126 |
+
|
| 127 |
+
lam1 = torch.exp((self.lambda_q1 * self.lambda_k1).sum().float())
|
| 128 |
+
lam2 = torch.exp((self.lambda_q2 * self.lambda_k2).sum().float())
|
| 129 |
+
lam = (lam1 - lam2 + self.lambda_init).to(x.dtype)
|
| 130 |
+
|
| 131 |
+
attn = a1 - lam * a2 # (B, H, T, 2D)
|
| 132 |
+
attn = self.subln(attn) * (1.0 - self.lambda_init)
|
| 133 |
+
attn = attn.transpose(1, 2).reshape(B, T, C)
|
| 134 |
+
return self.wo(attn)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class FeedForward(nn.Module):
|
| 138 |
+
"""Linear -> PolyNorm -> Linear (Motif 그림 1의 비게이트 FFN)"""
|
| 139 |
+
|
| 140 |
+
def __init__(self, cfg):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.up = nn.Linear(cfg.dim, cfg.ffn_dim, bias=False)
|
| 143 |
+
self.act = PolyNorm()
|
| 144 |
+
self.down = nn.Linear(cfg.ffn_dim, cfg.dim, bias=False)
|
| 145 |
+
|
| 146 |
+
def forward(self, x):
|
| 147 |
+
return self.down(self.act(self.up(x)))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Block(nn.Module):
|
| 151 |
+
def __init__(self, cfg, layer_idx: int):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.attn_norm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 154 |
+
self.attn = DifferentialAttention(cfg, layer_idx)
|
| 155 |
+
self.ffn_norm = RMSNorm(cfg.dim, cfg.norm_eps)
|
| 156 |
+
self.ffn = FeedForward(cfg)
|
| 157 |
+
|
| 158 |
+
def forward(self, x, cos, sin):
|
| 159 |
+
x = x + self.attn(self.attn_norm(x), cos, sin)
|
| 160 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 161 |
+
return x
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class PerdixForCausalLM(PreTrainedModel, GenerationMixin):
|
| 165 |
+
config_class = PerdixConfig
|
| 166 |
+
base_model_prefix = ""
|
| 167 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 168 |
+
_supports_cache_class = False
|
| 169 |
+
|
| 170 |
+
def __init__(self, config: PerdixConfig):
|
| 171 |
+
super().__init__(config)
|
| 172 |
+
self.tok_emb = nn.Embedding(config.vocab_size, config.dim)
|
| 173 |
+
self.blocks = nn.ModuleList(
|
| 174 |
+
[Block(config, i) for i in range(config.n_layers)])
|
| 175 |
+
self.final_norm = RMSNorm(config.dim, config.norm_eps)
|
| 176 |
+
self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 177 |
+
|
| 178 |
+
head_dim = config.dim // config.n_heads // 2
|
| 179 |
+
cos, sin = precompute_rope(head_dim, config.max_seq_len, config.rope_theta)
|
| 180 |
+
self.register_buffer("rope_cos", cos, persistent=False)
|
| 181 |
+
self.register_buffer("rope_sin", sin, persistent=False)
|
| 182 |
+
self.post_init()
|
| 183 |
+
|
| 184 |
+
def _init_weights(self, m):
|
| 185 |
+
if isinstance(m, (nn.Linear, nn.Embedding)):
|
| 186 |
+
nn.init.normal_(m.weight, mean=0.0, std=self.config.init_std)
|
| 187 |
+
|
| 188 |
+
def get_input_embeddings(self):
|
| 189 |
+
return self.tok_emb
|
| 190 |
+
|
| 191 |
+
def set_input_embeddings(self, value):
|
| 192 |
+
self.tok_emb = value
|
| 193 |
+
|
| 194 |
+
def get_output_embeddings(self):
|
| 195 |
+
return self.lm_head
|
| 196 |
+
|
| 197 |
+
def set_output_embeddings(self, value):
|
| 198 |
+
self.lm_head = value
|
| 199 |
+
|
| 200 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
|
| 201 |
+
x = self.tok_emb(input_ids)
|
| 202 |
+
for blk in self.blocks:
|
| 203 |
+
x = blk(x, self.rope_cos, self.rope_sin)
|
| 204 |
+
logits = self.lm_head(self.final_norm(x))
|
| 205 |
+
loss = None
|
| 206 |
+
if labels is not None:
|
| 207 |
+
loss = F.cross_entropy(
|
| 208 |
+
logits[:, :-1].float().reshape(-1, logits.size(-1)),
|
| 209 |
+
labels[:, 1:].reshape(-1), ignore_index=-100)
|
| 210 |
+
return CausalLMOutput(loss=loss, logits=logits)
|
| 211 |
+
|
| 212 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 213 |
+
# 캐시가 없으므로 매 스텝 최근 max_seq_len 토큰 전체를 다시 넣는다
|
| 214 |
+
return {"input_ids": input_ids[:, -self.config.max_seq_len:]}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": "<|endoftext|>",
|
| 3 |
+
"eos_token": "<|endoftext|>",
|
| 4 |
+
"pad_token": "<|pad|>"
|
| 5 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "<|endoftext|>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "<|pad|>",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
}
|
| 19 |
+
},
|
| 20 |
+
"bos_token": "<|endoftext|>",
|
| 21 |
+
"clean_up_tokenization_spaces": false,
|
| 22 |
+
"eos_token": "<|endoftext|>",
|
| 23 |
+
"extra_special_tokens": {},
|
| 24 |
+
"model_max_length": 2048,
|
| 25 |
+
"pad_token": "<|pad|>",
|
| 26 |
+
"tokenizer_class": "PreTrainedTokenizerFast"
|
| 27 |
+
}
|