Text Generation
Transformers
Safetensors
Russian
rugpt3xl
gpt3
russian
causal-lm
conversational
custom_code
Instructions to use evilfreelancer/ruGPT3XL with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use evilfreelancer/ruGPT3XL with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="evilfreelancer/ruGPT3XL", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("evilfreelancer/ruGPT3XL", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use evilfreelancer/ruGPT3XL with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "evilfreelancer/ruGPT3XL" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "evilfreelancer/ruGPT3XL", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/evilfreelancer/ruGPT3XL
- SGLang
How to use evilfreelancer/ruGPT3XL 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 "evilfreelancer/ruGPT3XL" \ --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": "evilfreelancer/ruGPT3XL", "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 "evilfreelancer/ruGPT3XL" \ --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": "evilfreelancer/ruGPT3XL", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use evilfreelancer/ruGPT3XL with Docker Model Runner:
docker model run hf.co/evilfreelancer/ruGPT3XL
Upload folder using huggingface_hub
Browse files- README.md +293 -3
- config.json +30 -0
- configuration_rugpt3xl.py +60 -0
- generation_config.json +13 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_rugpt3xl.py +503 -0
- tokenizer_config.json +13 -0
- vocab.json +0 -0
README.md
CHANGED
|
@@ -1,3 +1,293 @@
|
|
| 1 |
-
---
|
| 2 |
-
|
| 3 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- ru
|
| 4 |
+
library_name: transformers
|
| 5 |
+
tags:
|
| 6 |
+
- text-generation
|
| 7 |
+
- gpt3
|
| 8 |
+
- russian
|
| 9 |
+
- causal-lm
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
pipeline_tag: text-generation
|
| 12 |
+
base_model: ai-forever/rugpt3xl
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# ruGPT-3 XL (HuggingFace format)
|
| 16 |
+
|
| 17 |
+
A 1.3B-parameter GPT-3-style language model for Russian, converted from the original
|
| 18 |
+
[ai-forever/rugpt3xl](https://huggingface.co/ai-forever/rugpt3xl) Megatron-LM checkpoint
|
| 19 |
+
into a native HuggingFace `transformers` format.
|
| 20 |
+
|
| 21 |
+
This is a **base (pretrained) model**, not instruction-tuned. It performs text completion
|
| 22 |
+
and can be fine-tuned for downstream tasks.
|
| 23 |
+
|
| 24 |
+
## Model Details
|
| 25 |
+
|
| 26 |
+
| Parameter | Value |
|
| 27 |
+
|---|---|
|
| 28 |
+
| Parameters | 1.3B |
|
| 29 |
+
| Architecture | GPT-3 (decoder-only transformer) |
|
| 30 |
+
| Hidden size | 2048 |
|
| 31 |
+
| Layers | 24 |
|
| 32 |
+
| Attention heads | 16 |
|
| 33 |
+
| FFN intermediate size | 8192 |
|
| 34 |
+
| Max sequence length | 2048 |
|
| 35 |
+
| Vocabulary | 50,264 tokens (BPE) |
|
| 36 |
+
| Activation | GELU |
|
| 37 |
+
| Normalization | Pre-LayerNorm |
|
| 38 |
+
| Position encoding | Learned absolute |
|
| 39 |
+
| Precision | float16 |
|
| 40 |
+
| Training data | 80B tokens of Russian text (4 epochs) |
|
| 41 |
+
| Test perplexity | 12.05 |
|
| 42 |
+
|
| 43 |
+
## Quick Start
|
| 44 |
+
|
| 45 |
+
```python
|
| 46 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 47 |
+
|
| 48 |
+
model_name = "your-username/rugpt3xl-hf" # replace with actual repo name
|
| 49 |
+
|
| 50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 51 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 52 |
+
model_name, trust_remote_code=True, device_map="auto"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
inputs = tokenizer("Москва - столица", return_tensors="pt").to(model.device)
|
| 56 |
+
outputs = model.generate(
|
| 57 |
+
**inputs,
|
| 58 |
+
max_new_tokens=100,
|
| 59 |
+
do_sample=True,
|
| 60 |
+
temperature=0.7,
|
| 61 |
+
top_p=0.9,
|
| 62 |
+
repetition_penalty=1.2,
|
| 63 |
+
)
|
| 64 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Loading Options
|
| 68 |
+
|
| 69 |
+
**GPU (float16, recommended):**
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 73 |
+
model_name, trust_remote_code=True, device_map="auto"
|
| 74 |
+
)
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
**CPU (float32):**
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
import torch
|
| 81 |
+
|
| 82 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 83 |
+
model_name, trust_remote_code=True, dtype=torch.float32, device_map="cpu"
|
| 84 |
+
)
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## Chat Template
|
| 88 |
+
|
| 89 |
+
The tokenizer includes a simple chat template for question-answering:
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
messages = [
|
| 93 |
+
{"role": "user", "content": "Какая столица России?"},
|
| 94 |
+
]
|
| 95 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 96 |
+
# Output: "Вопрос: Какая столица России?\n\nОтвет: "
|
| 97 |
+
|
| 98 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 99 |
+
outputs = model.generate(**inputs, max_new_tokens=100)
|
| 100 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
> **Note:** This is a base model, not an instruction-tuned chatbot. The chat template provides
|
| 104 |
+
> a basic structure, but the model may not always follow instructions precisely. For reliable
|
| 105 |
+
> conversational behavior, fine-tune the model on instruction/chat data.
|
| 106 |
+
|
| 107 |
+
## Fine-tuning
|
| 108 |
+
|
| 109 |
+
The model is fully compatible with standard HuggingFace training workflows.
|
| 110 |
+
|
| 111 |
+
### Full Fine-tuning with Trainer
|
| 112 |
+
|
| 113 |
+
```python
|
| 114 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 115 |
+
|
| 116 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 117 |
+
model_name, trust_remote_code=True, device_map="auto"
|
| 118 |
+
)
|
| 119 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 120 |
+
|
| 121 |
+
args = TrainingArguments(
|
| 122 |
+
output_dir="./rugpt3xl-finetuned",
|
| 123 |
+
num_train_epochs=3,
|
| 124 |
+
per_device_train_batch_size=4,
|
| 125 |
+
gradient_accumulation_steps=4,
|
| 126 |
+
learning_rate=2e-5,
|
| 127 |
+
fp16=True,
|
| 128 |
+
save_strategy="epoch",
|
| 129 |
+
logging_steps=10,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
trainer = Trainer(
|
| 133 |
+
model=model,
|
| 134 |
+
args=args,
|
| 135 |
+
train_dataset=your_dataset, # dataset with input_ids, attention_mask, labels
|
| 136 |
+
)
|
| 137 |
+
trainer.train()
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
### LoRA Fine-tuning with PEFT
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 144 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 145 |
+
|
| 146 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 147 |
+
model_name, trust_remote_code=True, device_map="auto"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
lora_config = LoraConfig(
|
| 151 |
+
task_type=TaskType.CAUSAL_LM,
|
| 152 |
+
r=16,
|
| 153 |
+
lora_alpha=32,
|
| 154 |
+
lora_dropout=0.05,
|
| 155 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "up_proj", "down_proj"],
|
| 156 |
+
)
|
| 157 |
+
model = get_peft_model(model, lora_config)
|
| 158 |
+
model.print_trainable_parameters()
|
| 159 |
+
# trainable params: ~14M || all params: 1.4B || trainable%: ~1.0%
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
### SFT with TRL
|
| 163 |
+
|
| 164 |
+
```python
|
| 165 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 166 |
+
from trl import SFTTrainer, SFTConfig
|
| 167 |
+
from peft import LoraConfig, TaskType
|
| 168 |
+
from datasets import Dataset
|
| 169 |
+
|
| 170 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 171 |
+
model_name, trust_remote_code=True, device_map="auto"
|
| 172 |
+
)
|
| 173 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 174 |
+
|
| 175 |
+
lora_config = LoraConfig(
|
| 176 |
+
task_type=TaskType.CAUSAL_LM,
|
| 177 |
+
r=16,
|
| 178 |
+
lora_alpha=32,
|
| 179 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# Dataset with chat messages format
|
| 183 |
+
train_data = [
|
| 184 |
+
{"messages": [
|
| 185 |
+
{"role": "user", "content": "Какая столица России?"},
|
| 186 |
+
{"role": "assistant", "content": "Москва - столица Российской Федерации."},
|
| 187 |
+
]},
|
| 188 |
+
# ... more examples
|
| 189 |
+
]
|
| 190 |
+
dataset = Dataset.from_list(train_data)
|
| 191 |
+
|
| 192 |
+
sft_config = SFTConfig(
|
| 193 |
+
output_dir="./rugpt3xl-sft",
|
| 194 |
+
max_steps=1000,
|
| 195 |
+
per_device_train_batch_size=4,
|
| 196 |
+
learning_rate=2e-5,
|
| 197 |
+
logging_steps=10,
|
| 198 |
+
max_length=512,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
trainer = SFTTrainer(
|
| 202 |
+
model=model,
|
| 203 |
+
args=sft_config,
|
| 204 |
+
train_dataset=dataset,
|
| 205 |
+
peft_config=lora_config,
|
| 206 |
+
processing_class=tokenizer,
|
| 207 |
+
)
|
| 208 |
+
trainer.train()
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
### Supported Fine-tuning Features
|
| 212 |
+
|
| 213 |
+
| Feature | Status |
|
| 214 |
+
|---|---|
|
| 215 |
+
| Full parameter training | Supported |
|
| 216 |
+
| Gradient checkpointing | Supported |
|
| 217 |
+
| LoRA / PEFT | Supported |
|
| 218 |
+
| TRL SFTTrainer | Supported |
|
| 219 |
+
| DeepSpeed ZeRO | Supported |
|
| 220 |
+
| FSDP | Supported |
|
| 221 |
+
| KV cache during generation | Supported |
|
| 222 |
+
| `labels` argument for loss computation | Supported |
|
| 223 |
+
|
| 224 |
+
**LoRA target modules:** `q_proj`, `k_proj`, `v_proj`, `o_proj`, `up_proj`, `down_proj`
|
| 225 |
+
|
| 226 |
+
## Architecture Details
|
| 227 |
+
|
| 228 |
+
The model implements a custom `RuGPT3XLForCausalLM` class (loaded via `trust_remote_code=True`):
|
| 229 |
+
|
| 230 |
+
```
|
| 231 |
+
RuGPT3XLForCausalLM
|
| 232 |
+
├── model (RuGPT3XLModel)
|
| 233 |
+
│ ├── embed_tokens (Embedding: 50264 x 2048)
|
| 234 |
+
│ ├── embed_positions (Embedding: 2048 x 2048)
|
| 235 |
+
│ ├── embed_dropout (Dropout: 0.1)
|
| 236 |
+
│ ├── layers (x24) (RuGPT3XLDecoderLayer)
|
| 237 |
+
│ │ ├── input_layernorm (LayerNorm: 2048)
|
| 238 |
+
│ │ ├── self_attn (RuGPT3XLAttention)
|
| 239 |
+
│ │ │ ├── q_proj (Linear: 2048 -> 2048)
|
| 240 |
+
│ │ │ ├── k_proj (Linear: 2048 -> 2048)
|
| 241 |
+
│ │ │ ├── v_proj (Linear: 2048 -> 2048)
|
| 242 |
+
│ │ │ ├── o_proj (Linear: 2048 -> 2048)
|
| 243 |
+
│ │ │ ├── attn_dropout (Dropout: 0.1)
|
| 244 |
+
│ │ │ └── resid_dropout (Dropout: 0.1)
|
| 245 |
+
│ │ ├── post_attention_layernorm (LayerNorm: 2048)
|
| 246 |
+
│ │ └── mlp (RuGPT3XMLP)
|
| 247 |
+
│ │ ├── up_proj (Linear: 2048 -> 8192)
|
| 248 |
+
│ │ ├── down_proj (Linear: 8192 -> 2048)
|
| 249 |
+
│ │ ├── act_fn (GELU)
|
| 250 |
+
│ │ └── dropout (Dropout: 0.1)
|
| 251 |
+
│ └── norm (LayerNorm: 2048)
|
| 252 |
+
└── lm_head (Linear: 2048 -> 50264, no bias)
|
| 253 |
+
```
|
| 254 |
+
|
| 255 |
+
## Conversion
|
| 256 |
+
|
| 257 |
+
This model was converted from the original Megatron-LM checkpoint using a custom script.
|
| 258 |
+
The conversion performs the following transformations:
|
| 259 |
+
|
| 260 |
+
1. Strips the `module.` prefix from parameter names (FP16 / DDP wrappers)
|
| 261 |
+
2. Remaps Megatron-LM naming to HuggingFace convention
|
| 262 |
+
3. Splits the fused QKV projection (`[6144, 2048]`) into separate Q, K, V (`[2048, 2048]` each)
|
| 263 |
+
4. Saves weights in safetensors format
|
| 264 |
+
|
| 265 |
+
For full conversion details and the script, see the
|
| 266 |
+
[rugpt3xl-convert](https://github.com/your-username/rugpt3xl-convert) repository.
|
| 267 |
+
|
| 268 |
+
## Limitations
|
| 269 |
+
|
| 270 |
+
- This is a **base model** trained on Russian internet text. It may generate biased, factually
|
| 271 |
+
incorrect, or offensive content.
|
| 272 |
+
- The model was trained primarily on Russian text. It has limited capability in other languages.
|
| 273 |
+
- Maximum context length is 2048 tokens. Inputs longer than this will be truncated.
|
| 274 |
+
- The model is not instruction-tuned and works best for text completion rather than
|
| 275 |
+
following specific instructions.
|
| 276 |
+
|
| 277 |
+
## Citation
|
| 278 |
+
|
| 279 |
+
```bibtex
|
| 280 |
+
@misc{rugpt3xl,
|
| 281 |
+
title={ruGPT-3 XL},
|
| 282 |
+
author={SberDevices Team},
|
| 283 |
+
year={2021},
|
| 284 |
+
publisher={Hugging Face},
|
| 285 |
+
url={https://huggingface.co/ai-forever/rugpt3xl}
|
| 286 |
+
}
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
## Links
|
| 290 |
+
|
| 291 |
+
- [ai-forever/rugpt3xl](https://huggingface.co/ai-forever/rugpt3xl) - original model
|
| 292 |
+
- [ai-forever/ru-gpts](https://github.com/ai-forever/ru-gpts) - original training codebase
|
| 293 |
+
- [GPT-3 Paper](https://arxiv.org/abs/2005.14165) - "Language Models are Few-Shot Learners" (Brown et al., 2020)
|
config.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"RuGPT3XLForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_rugpt3xl.RuGPT3XLConfig",
|
| 7 |
+
"AutoModel": "modeling_rugpt3xl.RuGPT3XLModel",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_rugpt3xl.RuGPT3XLForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"model_type": "rugpt3xl",
|
| 11 |
+
"vocab_size": 50264,
|
| 12 |
+
"hidden_size": 2048,
|
| 13 |
+
"num_hidden_layers": 24,
|
| 14 |
+
"num_attention_heads": 16,
|
| 15 |
+
"intermediate_size": 8192,
|
| 16 |
+
"hidden_act": "gelu_new",
|
| 17 |
+
"max_position_embeddings": 2048,
|
| 18 |
+
"initializer_range": 0.02,
|
| 19 |
+
"layer_norm_eps": 1e-5,
|
| 20 |
+
"embedding_dropout": 0.1,
|
| 21 |
+
"attention_dropout": 0.1,
|
| 22 |
+
"output_dropout": 0.1,
|
| 23 |
+
"use_cache": true,
|
| 24 |
+
"bos_token_id": 2,
|
| 25 |
+
"eos_token_id": 1,
|
| 26 |
+
"pad_token_id": 0,
|
| 27 |
+
"tie_word_embeddings": false,
|
| 28 |
+
"torch_dtype": "float16",
|
| 29 |
+
"transformers_version": "5.3.0"
|
| 30 |
+
}
|
configuration_rugpt3xl.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 2 |
+
from transformers.utils import logging
|
| 3 |
+
|
| 4 |
+
logger = logging.get_logger(__name__)
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RuGPT3XLConfig(PretrainedConfig):
|
| 8 |
+
"""Configuration class for the RuGPT-3 XL model (1.3B parameters).
|
| 9 |
+
|
| 10 |
+
This is a GPT-3-style decoder-only transformer trained on Russian text by
|
| 11 |
+
SberDevices. Architecture: learned absolute position embeddings, pre-norm
|
| 12 |
+
transformer layers with GELU activation, and tied word embeddings for the
|
| 13 |
+
language modeling head.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
model_type = "rugpt3xl"
|
| 17 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
vocab_size=50264,
|
| 22 |
+
hidden_size=2048,
|
| 23 |
+
num_hidden_layers=24,
|
| 24 |
+
num_attention_heads=16,
|
| 25 |
+
intermediate_size=8192,
|
| 26 |
+
hidden_act="gelu_new",
|
| 27 |
+
max_position_embeddings=2048,
|
| 28 |
+
initializer_range=0.02,
|
| 29 |
+
layer_norm_eps=1e-5,
|
| 30 |
+
embedding_dropout=0.1,
|
| 31 |
+
attention_dropout=0.1,
|
| 32 |
+
output_dropout=0.1,
|
| 33 |
+
use_cache=True,
|
| 34 |
+
bos_token_id=2,
|
| 35 |
+
eos_token_id=1,
|
| 36 |
+
pad_token_id=0,
|
| 37 |
+
tie_word_embeddings=False,
|
| 38 |
+
**kwargs,
|
| 39 |
+
):
|
| 40 |
+
self.vocab_size = vocab_size
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.num_hidden_layers = num_hidden_layers
|
| 43 |
+
self.num_attention_heads = num_attention_heads
|
| 44 |
+
self.intermediate_size = intermediate_size
|
| 45 |
+
self.hidden_act = hidden_act
|
| 46 |
+
self.max_position_embeddings = max_position_embeddings
|
| 47 |
+
self.initializer_range = initializer_range
|
| 48 |
+
self.layer_norm_eps = layer_norm_eps
|
| 49 |
+
self.embedding_dropout = embedding_dropout
|
| 50 |
+
self.attention_dropout = attention_dropout
|
| 51 |
+
self.output_dropout = output_dropout
|
| 52 |
+
self.use_cache = use_cache
|
| 53 |
+
|
| 54 |
+
super().__init__(
|
| 55 |
+
bos_token_id=bos_token_id,
|
| 56 |
+
eos_token_id=eos_token_id,
|
| 57 |
+
pad_token_id=pad_token_id,
|
| 58 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 59 |
+
**kwargs,
|
| 60 |
+
)
|
generation_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 2,
|
| 4 |
+
"eos_token_id": 1,
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"do_sample": true,
|
| 7 |
+
"temperature": 0.7,
|
| 8 |
+
"top_k": 50,
|
| 9 |
+
"top_p": 0.9,
|
| 10 |
+
"repetition_penalty": 1.2,
|
| 11 |
+
"max_new_tokens": 256,
|
| 12 |
+
"transformers_version": "5.3.0"
|
| 13 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:98a74e6d57c584e1192ff058be2efcab720c318481c4212e92d4d427abe52140
|
| 3 |
+
size 2837399976
|
modeling_rugpt3xl.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PyTorch RuGPT-3 XL model.
|
| 2 |
+
|
| 3 |
+
GPT-3-style decoder-only transformer (1.3B) trained on Russian text.
|
| 4 |
+
Architecture: absolute position embeddings, pre-norm layers, GELU activation,
|
| 5 |
+
tied LM head.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
from typing import List, Optional, Tuple, Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
import torch.utils.checkpoint
|
| 15 |
+
|
| 16 |
+
from transformers.activations import ACT2FN
|
| 17 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 18 |
+
from transformers.modeling_outputs import (
|
| 19 |
+
BaseModelOutputWithPast,
|
| 20 |
+
CausalLMOutputWithPast,
|
| 21 |
+
)
|
| 22 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 23 |
+
from transformers.utils import logging
|
| 24 |
+
|
| 25 |
+
from .configuration_rugpt3xl import RuGPT3XLConfig
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class RuGPT3XLAttention(nn.Module):
|
| 31 |
+
def __init__(self, config: RuGPT3XLConfig, layer_idx: int):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.config = config
|
| 34 |
+
self.layer_idx = layer_idx
|
| 35 |
+
self.hidden_size = config.hidden_size
|
| 36 |
+
self.num_heads = config.num_attention_heads
|
| 37 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 38 |
+
self.scale = self.head_dim ** -0.5
|
| 39 |
+
|
| 40 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size)
|
| 41 |
+
self.k_proj = nn.Linear(self.hidden_size, self.hidden_size)
|
| 42 |
+
self.v_proj = nn.Linear(self.hidden_size, self.hidden_size)
|
| 43 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size)
|
| 44 |
+
|
| 45 |
+
self.attn_dropout = nn.Dropout(config.attention_dropout)
|
| 46 |
+
self.resid_dropout = nn.Dropout(config.output_dropout)
|
| 47 |
+
|
| 48 |
+
def forward(
|
| 49 |
+
self,
|
| 50 |
+
hidden_states: torch.Tensor,
|
| 51 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 52 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 53 |
+
past_key_value: Optional[Cache] = None,
|
| 54 |
+
output_attentions: bool = False,
|
| 55 |
+
use_cache: bool = False,
|
| 56 |
+
**kwargs,
|
| 57 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 58 |
+
bsz, q_len, _ = hidden_states.size()
|
| 59 |
+
|
| 60 |
+
query = self.q_proj(hidden_states)
|
| 61 |
+
key = self.k_proj(hidden_states)
|
| 62 |
+
value = self.v_proj(hidden_states)
|
| 63 |
+
|
| 64 |
+
query = query.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 65 |
+
key = key.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 66 |
+
value = value.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 67 |
+
|
| 68 |
+
if past_key_value is not None:
|
| 69 |
+
key, value = past_key_value.update(key, value, self.layer_idx)
|
| 70 |
+
|
| 71 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * self.scale
|
| 72 |
+
|
| 73 |
+
if attention_mask is not None:
|
| 74 |
+
attn_weights = attn_weights + attention_mask
|
| 75 |
+
|
| 76 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
|
| 77 |
+
query.dtype
|
| 78 |
+
)
|
| 79 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 80 |
+
|
| 81 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 82 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 83 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 84 |
+
|
| 85 |
+
attn_output = self.o_proj(attn_output)
|
| 86 |
+
attn_output = self.resid_dropout(attn_output)
|
| 87 |
+
|
| 88 |
+
return (
|
| 89 |
+
attn_output,
|
| 90 |
+
attn_weights if output_attentions else None,
|
| 91 |
+
past_key_value,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class RuGPT3XMLP(nn.Module):
|
| 96 |
+
def __init__(self, config: RuGPT3XLConfig):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 99 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 100 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 101 |
+
self.dropout = nn.Dropout(config.output_dropout)
|
| 102 |
+
|
| 103 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 104 |
+
return self.dropout(self.down_proj(self.act_fn(self.up_proj(hidden_states))))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class RuGPT3XLDecoderLayer(nn.Module):
|
| 108 |
+
def __init__(self, config: RuGPT3XLConfig, layer_idx: int):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.input_layernorm = nn.LayerNorm(
|
| 111 |
+
config.hidden_size, eps=config.layer_norm_eps
|
| 112 |
+
)
|
| 113 |
+
self.self_attn = RuGPT3XLAttention(config, layer_idx)
|
| 114 |
+
self.post_attention_layernorm = nn.LayerNorm(
|
| 115 |
+
config.hidden_size, eps=config.layer_norm_eps
|
| 116 |
+
)
|
| 117 |
+
self.mlp = RuGPT3XMLP(config)
|
| 118 |
+
|
| 119 |
+
def forward(
|
| 120 |
+
self,
|
| 121 |
+
hidden_states: torch.Tensor,
|
| 122 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 123 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 124 |
+
past_key_value: Optional[Cache] = None,
|
| 125 |
+
output_attentions: bool = False,
|
| 126 |
+
use_cache: bool = False,
|
| 127 |
+
**kwargs,
|
| 128 |
+
) -> Tuple[torch.Tensor, ...]:
|
| 129 |
+
# Pre-norm: LayerNorm -> Attention -> Residual
|
| 130 |
+
residual = hidden_states
|
| 131 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 132 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 133 |
+
hidden_states=hidden_states,
|
| 134 |
+
attention_mask=attention_mask,
|
| 135 |
+
position_ids=position_ids,
|
| 136 |
+
past_key_value=past_key_value,
|
| 137 |
+
output_attentions=output_attentions,
|
| 138 |
+
use_cache=use_cache,
|
| 139 |
+
**kwargs,
|
| 140 |
+
)
|
| 141 |
+
hidden_states = residual + hidden_states
|
| 142 |
+
|
| 143 |
+
# Pre-norm: LayerNorm -> MLP -> Residual
|
| 144 |
+
residual = hidden_states
|
| 145 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 146 |
+
hidden_states = self.mlp(hidden_states)
|
| 147 |
+
hidden_states = residual + hidden_states
|
| 148 |
+
|
| 149 |
+
outputs = (hidden_states,)
|
| 150 |
+
if output_attentions:
|
| 151 |
+
outputs += (self_attn_weights,)
|
| 152 |
+
if use_cache:
|
| 153 |
+
outputs += (present_key_value,)
|
| 154 |
+
return outputs
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class RuGPT3XLPreTrainedModel(PreTrainedModel):
|
| 158 |
+
config_class = RuGPT3XLConfig
|
| 159 |
+
base_model_prefix = "model"
|
| 160 |
+
supports_gradient_checkpointing = True
|
| 161 |
+
_no_split_modules = ["RuGPT3XLDecoderLayer"]
|
| 162 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 163 |
+
_supports_cache_class = True
|
| 164 |
+
|
| 165 |
+
def _init_weights(self, module):
|
| 166 |
+
std = self.config.initializer_range
|
| 167 |
+
if isinstance(module, nn.Linear):
|
| 168 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 169 |
+
if module.bias is not None:
|
| 170 |
+
module.bias.data.zero_()
|
| 171 |
+
elif isinstance(module, nn.Embedding):
|
| 172 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 173 |
+
if module.padding_idx is not None:
|
| 174 |
+
module.weight.data[module.padding_idx].zero_()
|
| 175 |
+
elif isinstance(module, nn.LayerNorm):
|
| 176 |
+
module.bias.data.zero_()
|
| 177 |
+
module.weight.data.fill_(1.0)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class RuGPT3XLModel(RuGPT3XLPreTrainedModel):
|
| 181 |
+
"""Bare RuGPT-3 XL transformer outputting raw hidden states."""
|
| 182 |
+
|
| 183 |
+
def __init__(self, config: RuGPT3XLConfig):
|
| 184 |
+
super().__init__(config)
|
| 185 |
+
self.padding_idx = config.pad_token_id
|
| 186 |
+
self.vocab_size = config.vocab_size
|
| 187 |
+
|
| 188 |
+
self.embed_tokens = nn.Embedding(
|
| 189 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
| 190 |
+
)
|
| 191 |
+
self.embed_positions = nn.Embedding(
|
| 192 |
+
config.max_position_embeddings, config.hidden_size
|
| 193 |
+
)
|
| 194 |
+
self.embed_dropout = nn.Dropout(config.embedding_dropout)
|
| 195 |
+
|
| 196 |
+
self.layers = nn.ModuleList(
|
| 197 |
+
[
|
| 198 |
+
RuGPT3XLDecoderLayer(config, layer_idx)
|
| 199 |
+
for layer_idx in range(config.num_hidden_layers)
|
| 200 |
+
]
|
| 201 |
+
)
|
| 202 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 203 |
+
|
| 204 |
+
self.gradient_checkpointing = False
|
| 205 |
+
self.post_init()
|
| 206 |
+
|
| 207 |
+
def get_input_embeddings(self):
|
| 208 |
+
return self.embed_tokens
|
| 209 |
+
|
| 210 |
+
def set_input_embeddings(self, value):
|
| 211 |
+
self.embed_tokens = value
|
| 212 |
+
|
| 213 |
+
def forward(
|
| 214 |
+
self,
|
| 215 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 216 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 217 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 218 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 219 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 220 |
+
use_cache: Optional[bool] = None,
|
| 221 |
+
output_attentions: Optional[bool] = None,
|
| 222 |
+
output_hidden_states: Optional[bool] = None,
|
| 223 |
+
return_dict: Optional[bool] = None,
|
| 224 |
+
**kwargs,
|
| 225 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 226 |
+
output_attentions = (
|
| 227 |
+
output_attentions
|
| 228 |
+
if output_attentions is not None
|
| 229 |
+
else self.config.output_attentions
|
| 230 |
+
)
|
| 231 |
+
output_hidden_states = (
|
| 232 |
+
output_hidden_states
|
| 233 |
+
if output_hidden_states is not None
|
| 234 |
+
else self.config.output_hidden_states
|
| 235 |
+
)
|
| 236 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 237 |
+
return_dict = (
|
| 238 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 242 |
+
raise ValueError(
|
| 243 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
| 244 |
+
)
|
| 245 |
+
if input_ids is not None:
|
| 246 |
+
batch_size, seq_length = input_ids.shape[:2]
|
| 247 |
+
elif inputs_embeds is not None:
|
| 248 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 249 |
+
else:
|
| 250 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 251 |
+
|
| 252 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 253 |
+
logger.warning_once(
|
| 254 |
+
"`use_cache=True` is incompatible with gradient checkpointing. "
|
| 255 |
+
"Setting `use_cache=False`."
|
| 256 |
+
)
|
| 257 |
+
use_cache = False
|
| 258 |
+
|
| 259 |
+
past_key_values_length = 0
|
| 260 |
+
if use_cache:
|
| 261 |
+
if past_key_values is None:
|
| 262 |
+
past_key_values = DynamicCache()
|
| 263 |
+
past_key_values_length = past_key_values.get_seq_length()
|
| 264 |
+
|
| 265 |
+
if position_ids is None:
|
| 266 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 267 |
+
position_ids = torch.arange(
|
| 268 |
+
past_key_values_length,
|
| 269 |
+
seq_length + past_key_values_length,
|
| 270 |
+
dtype=torch.long,
|
| 271 |
+
device=device,
|
| 272 |
+
)
|
| 273 |
+
position_ids = position_ids.unsqueeze(0)
|
| 274 |
+
|
| 275 |
+
if inputs_embeds is None:
|
| 276 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 277 |
+
|
| 278 |
+
position_embeds = self.embed_positions(position_ids)
|
| 279 |
+
hidden_states = self.embed_dropout(inputs_embeds + position_embeds)
|
| 280 |
+
|
| 281 |
+
# Build causal 4D attention mask
|
| 282 |
+
causal_mask = self._build_causal_mask(
|
| 283 |
+
batch_size,
|
| 284 |
+
seq_length,
|
| 285 |
+
past_key_values_length,
|
| 286 |
+
hidden_states.dtype,
|
| 287 |
+
hidden_states.device,
|
| 288 |
+
attention_mask,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
all_hidden_states = () if output_hidden_states else None
|
| 292 |
+
all_self_attns = () if output_attentions else None
|
| 293 |
+
next_decoder_cache = None
|
| 294 |
+
|
| 295 |
+
for decoder_layer in self.layers:
|
| 296 |
+
if output_hidden_states:
|
| 297 |
+
all_hidden_states += (hidden_states,)
|
| 298 |
+
|
| 299 |
+
if self.gradient_checkpointing and self.training:
|
| 300 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 301 |
+
decoder_layer.__call__,
|
| 302 |
+
hidden_states,
|
| 303 |
+
causal_mask,
|
| 304 |
+
position_ids,
|
| 305 |
+
past_key_values,
|
| 306 |
+
output_attentions,
|
| 307 |
+
use_cache,
|
| 308 |
+
)
|
| 309 |
+
else:
|
| 310 |
+
layer_outputs = decoder_layer(
|
| 311 |
+
hidden_states,
|
| 312 |
+
attention_mask=causal_mask,
|
| 313 |
+
position_ids=position_ids,
|
| 314 |
+
past_key_value=past_key_values,
|
| 315 |
+
output_attentions=output_attentions,
|
| 316 |
+
use_cache=use_cache,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
hidden_states = layer_outputs[0]
|
| 320 |
+
if use_cache:
|
| 321 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 322 |
+
if output_attentions:
|
| 323 |
+
all_self_attns += (layer_outputs[1],)
|
| 324 |
+
|
| 325 |
+
hidden_states = self.norm(hidden_states)
|
| 326 |
+
|
| 327 |
+
if output_hidden_states:
|
| 328 |
+
all_hidden_states += (hidden_states,)
|
| 329 |
+
|
| 330 |
+
next_cache = None
|
| 331 |
+
if use_cache:
|
| 332 |
+
next_cache = next_decoder_cache
|
| 333 |
+
|
| 334 |
+
if not return_dict:
|
| 335 |
+
return tuple(
|
| 336 |
+
v
|
| 337 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
| 338 |
+
if v is not None
|
| 339 |
+
)
|
| 340 |
+
return BaseModelOutputWithPast(
|
| 341 |
+
last_hidden_state=hidden_states,
|
| 342 |
+
past_key_values=next_cache,
|
| 343 |
+
hidden_states=all_hidden_states,
|
| 344 |
+
attentions=all_self_attns,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
@staticmethod
|
| 348 |
+
def _build_causal_mask(
|
| 349 |
+
batch_size: int,
|
| 350 |
+
seq_length: int,
|
| 351 |
+
past_length: int,
|
| 352 |
+
dtype: torch.dtype,
|
| 353 |
+
device: torch.device,
|
| 354 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 355 |
+
) -> torch.Tensor:
|
| 356 |
+
total_length = past_length + seq_length
|
| 357 |
+
causal = torch.full(
|
| 358 |
+
(seq_length, total_length), torch.finfo(dtype).min, device=device
|
| 359 |
+
)
|
| 360 |
+
causal = causal.masked_fill(
|
| 361 |
+
torch.arange(total_length, device=device).unsqueeze(0)
|
| 362 |
+
<= torch.arange(past_length, past_length + seq_length, device=device).unsqueeze(1),
|
| 363 |
+
0.0,
|
| 364 |
+
)
|
| 365 |
+
causal = causal.unsqueeze(0).unsqueeze(0)
|
| 366 |
+
|
| 367 |
+
if attention_mask is not None:
|
| 368 |
+
pad_mask = (1 - attention_mask[:, None, None, :].to(dtype)) * torch.finfo(
|
| 369 |
+
dtype
|
| 370 |
+
).min
|
| 371 |
+
causal = causal + pad_mask
|
| 372 |
+
|
| 373 |
+
return causal
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class RuGPT3XLForCausalLM(RuGPT3XLPreTrainedModel):
|
| 377 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 378 |
+
|
| 379 |
+
def __init__(self, config: RuGPT3XLConfig):
|
| 380 |
+
super().__init__(config)
|
| 381 |
+
self.model = RuGPT3XLModel(config)
|
| 382 |
+
self.vocab_size = config.vocab_size
|
| 383 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 384 |
+
self.post_init()
|
| 385 |
+
|
| 386 |
+
def get_input_embeddings(self):
|
| 387 |
+
return self.model.embed_tokens
|
| 388 |
+
|
| 389 |
+
def set_input_embeddings(self, value):
|
| 390 |
+
self.model.embed_tokens = value
|
| 391 |
+
|
| 392 |
+
def get_output_embeddings(self):
|
| 393 |
+
return self.lm_head
|
| 394 |
+
|
| 395 |
+
def set_output_embeddings(self, new_embeddings):
|
| 396 |
+
self.lm_head = new_embeddings
|
| 397 |
+
|
| 398 |
+
def get_decoder(self):
|
| 399 |
+
return self.model
|
| 400 |
+
|
| 401 |
+
def set_decoder(self, decoder):
|
| 402 |
+
self.model = decoder
|
| 403 |
+
|
| 404 |
+
def forward(
|
| 405 |
+
self,
|
| 406 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 407 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 408 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 409 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 410 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 411 |
+
labels: Optional[torch.LongTensor] = None,
|
| 412 |
+
use_cache: Optional[bool] = None,
|
| 413 |
+
output_attentions: Optional[bool] = None,
|
| 414 |
+
output_hidden_states: Optional[bool] = None,
|
| 415 |
+
return_dict: Optional[bool] = None,
|
| 416 |
+
**kwargs,
|
| 417 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 418 |
+
output_attentions = (
|
| 419 |
+
output_attentions
|
| 420 |
+
if output_attentions is not None
|
| 421 |
+
else self.config.output_attentions
|
| 422 |
+
)
|
| 423 |
+
output_hidden_states = (
|
| 424 |
+
output_hidden_states
|
| 425 |
+
if output_hidden_states is not None
|
| 426 |
+
else self.config.output_hidden_states
|
| 427 |
+
)
|
| 428 |
+
return_dict = (
|
| 429 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
outputs = self.model(
|
| 433 |
+
input_ids=input_ids,
|
| 434 |
+
attention_mask=attention_mask,
|
| 435 |
+
position_ids=position_ids,
|
| 436 |
+
past_key_values=past_key_values,
|
| 437 |
+
inputs_embeds=inputs_embeds,
|
| 438 |
+
use_cache=use_cache,
|
| 439 |
+
output_attentions=output_attentions,
|
| 440 |
+
output_hidden_states=output_hidden_states,
|
| 441 |
+
return_dict=return_dict,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
hidden_states = outputs[0]
|
| 445 |
+
logits = self.lm_head(hidden_states).float()
|
| 446 |
+
|
| 447 |
+
loss = None
|
| 448 |
+
if labels is not None:
|
| 449 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 450 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 451 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 452 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 453 |
+
shift_labels = shift_labels.view(-1).to(shift_logits.device)
|
| 454 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 455 |
+
|
| 456 |
+
if not return_dict:
|
| 457 |
+
output = (logits,) + outputs[1:]
|
| 458 |
+
return (loss,) + output if loss is not None else output
|
| 459 |
+
|
| 460 |
+
return CausalLMOutputWithPast(
|
| 461 |
+
loss=loss,
|
| 462 |
+
logits=logits,
|
| 463 |
+
past_key_values=outputs.past_key_values,
|
| 464 |
+
hidden_states=outputs.hidden_states,
|
| 465 |
+
attentions=outputs.attentions,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
def prepare_inputs_for_generation(
|
| 469 |
+
self,
|
| 470 |
+
input_ids,
|
| 471 |
+
past_key_values=None,
|
| 472 |
+
attention_mask=None,
|
| 473 |
+
inputs_embeds=None,
|
| 474 |
+
**kwargs,
|
| 475 |
+
):
|
| 476 |
+
if past_key_values is not None:
|
| 477 |
+
past_length = past_key_values.get_seq_length()
|
| 478 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
| 479 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
|
| 480 |
+
elif past_length < input_ids.shape[1]:
|
| 481 |
+
input_ids = input_ids[:, past_length:]
|
| 482 |
+
|
| 483 |
+
position_ids = kwargs.get("position_ids", None)
|
| 484 |
+
if attention_mask is not None and position_ids is None:
|
| 485 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 486 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 487 |
+
if position_ids is not None and past_key_values is not None:
|
| 488 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
| 489 |
+
|
| 490 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 491 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 492 |
+
else:
|
| 493 |
+
model_inputs = {"input_ids": input_ids}
|
| 494 |
+
|
| 495 |
+
model_inputs.update(
|
| 496 |
+
{
|
| 497 |
+
"position_ids": position_ids,
|
| 498 |
+
"past_key_values": past_key_values,
|
| 499 |
+
"use_cache": kwargs.get("use_cache"),
|
| 500 |
+
"attention_mask": attention_mask,
|
| 501 |
+
}
|
| 502 |
+
)
|
| 503 |
+
return model_inputs
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"add_prefix_space": false,
|
| 5 |
+
"bos_token": "<s>",
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"pad_token": "<pad>",
|
| 8 |
+
"unk_token": "<unk>",
|
| 9 |
+
"model_max_length": 2048,
|
| 10 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 11 |
+
"clean_up_tokenization_spaces": true,
|
| 12 |
+
"chat_template": "{% for message in messages %}{% if message['role'] == 'system' %}{{ message['content'] + '\n\n' }}{% elif message['role'] == 'user' %}{{ 'Вопрос: ' + message['content'] + '\n\nОтвет: ' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token }}{% endif %}{% endfor %}{% if add_generation_prompt %}{% endif %}"
|
| 13 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|