Upload folder using huggingface_hub
Browse files- README.md +340 -0
- config.json +32 -0
- configuration_moe_transformer.py +83 -0
- modeling_moe_transformer.py +663 -0
- pytorch_model.bin +3 -0
- tokenizer.json +0 -0
- tokenizer_config.json +42 -0
- vocab.json +0 -0
README.md
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: apache-2.0
|
| 5 |
+
library_name: transformers
|
| 6 |
+
tags:
|
| 7 |
+
- causal-lm
|
| 8 |
+
- moe-transformer
|
| 9 |
+
- mixture-of-experts
|
| 10 |
+
- arxiv
|
| 11 |
+
- code
|
| 12 |
+
- simplestories
|
| 13 |
+
datasets:
|
| 14 |
+
- arxiv
|
| 15 |
+
- code
|
| 16 |
+
- simplestories
|
| 17 |
+
pipeline_tag: text-generation
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# MoE-5L-Total-ArXiv-Code-SimpleStories
|
| 21 |
+
|
| 22 |
+
## Model Description
|
| 23 |
+
|
| 24 |
+
This is a 5-layer Mixture of Experts (MoE) transformer model trained on a combination of ArXiv papers, code repositories, and SimpleStories dataset. This "total" variant represents a comprehensive training approach with extended training and potential architectural refinements compared to the "active" version.
|
| 25 |
+
|
| 26 |
+
## Model Details
|
| 27 |
+
|
| 28 |
+
### Architecture
|
| 29 |
+
- **Model Type**: Mixture of Experts Transformer for Causal Language Modeling
|
| 30 |
+
- **Architecture**: `MoeTransformerForCausalLM`
|
| 31 |
+
- **Parameters**: ~140M parameters (8 experts × ~17.5M each)
|
| 32 |
+
- **Active Parameters**: ~35M per forward pass (top-2 expert routing)
|
| 33 |
+
- **Layers**: 5 transformer layers with MoE feed-forward networks
|
| 34 |
+
- **Hidden Size**: 768
|
| 35 |
+
- **Attention Heads**: 12 (with 8 key-value heads for efficiency)
|
| 36 |
+
- **Vocabulary Size**: 50,256 tokens
|
| 37 |
+
- **Max Sequence Length**: 1024 tokens
|
| 38 |
+
- **Context Window**: 512 tokens (with windowing support)
|
| 39 |
+
|
| 40 |
+
### MoE Configuration
|
| 41 |
+
- **Number of Experts**: 8 experts per layer
|
| 42 |
+
- **Expert Selection**: Top-2 routing (2 experts activated per token)
|
| 43 |
+
- **Router Type**: Learned gating network with auxiliary loss
|
| 44 |
+
- **Load Balancing**: Auxiliary loss coefficient: 0.01
|
| 45 |
+
- **Router Z-Loss**: Coefficient: 0.001
|
| 46 |
+
|
| 47 |
+
### Training Details
|
| 48 |
+
- **Training Data**: ArXiv papers, code repositories, and SimpleStories
|
| 49 |
+
- **Training Epochs**: 2 (comprehensive training schedule)
|
| 50 |
+
- **Batch Size**: 256
|
| 51 |
+
- **Learning Rate**: 5e-4 (optimized for stability)
|
| 52 |
+
- **Optimizer**: AdamW (β1=0.9, β2=0.999)
|
| 53 |
+
- **Dropout**: 0.1 (attention and hidden layers)
|
| 54 |
+
- **Normalization**: RMSNorm (ε=1e-6)
|
| 55 |
+
- **Training Objective**: Total loss optimization with enhanced expert utilization
|
| 56 |
+
|
| 57 |
+
### Model Features
|
| 58 |
+
- **Enhanced MoE Training**: Comprehensive training with improved expert specialization
|
| 59 |
+
- **Load Balancing**: Advanced auxiliary loss for optimal expert utilization
|
| 60 |
+
- **Rotary Position Embeddings**: For better handling of positional information
|
| 61 |
+
- **Group Query Attention**: Efficient attention with 12 query heads and 8 key-value heads
|
| 62 |
+
- **SwiGLU Activation**: Modern activation function in expert feed-forward layers
|
| 63 |
+
- **RMSNorm**: Layer normalization for improved training stability
|
| 64 |
+
|
| 65 |
+
## Differences from MoE-Active
|
| 66 |
+
|
| 67 |
+
### Training Improvements
|
| 68 |
+
- **Extended Training**: More comprehensive training schedule
|
| 69 |
+
- **Enhanced Expert Utilization**: Improved load balancing and expert specialization
|
| 70 |
+
- **Optimized Hyperparameters**: Fine-tuned for better performance
|
| 71 |
+
- **Advanced Routing**: Enhanced expert routing mechanisms
|
| 72 |
+
|
| 73 |
+
### Performance Characteristics
|
| 74 |
+
- **Better Convergence**: More stable training dynamics
|
| 75 |
+
- **Improved Specialization**: Clearer expert domain specialization
|
| 76 |
+
- **Enhanced Quality**: Better overall generation quality across domains
|
| 77 |
+
|
| 78 |
+
## Usage
|
| 79 |
+
|
| 80 |
+
### Loading the Model
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 84 |
+
import torch
|
| 85 |
+
|
| 86 |
+
# Load model and tokenizer
|
| 87 |
+
model_name = "your-username/moe-5l-total-arxiv-code-simplestories"
|
| 88 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 89 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 90 |
+
model_name,
|
| 91 |
+
torch_dtype=torch.float32,
|
| 92 |
+
device_map="auto"
|
| 93 |
+
)
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### Multi-Domain Text Generation
|
| 97 |
+
|
| 98 |
+
```python
|
| 99 |
+
# Generate academic content
|
| 100 |
+
prompt = "The implications of quantum entanglement in modern physics"
|
| 101 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 102 |
+
|
| 103 |
+
with torch.no_grad():
|
| 104 |
+
outputs = model.generate(
|
| 105 |
+
**inputs,
|
| 106 |
+
max_length=200,
|
| 107 |
+
num_return_sequences=1,
|
| 108 |
+
temperature=0.7,
|
| 109 |
+
do_sample=True,
|
| 110 |
+
pad_token_id=tokenizer.eos_token_id
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
academic_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 114 |
+
print(f"Academic: {academic_text}")
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
### Advanced Code Generation
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
# Generate complex code with explanations
|
| 121 |
+
prompt = "# Implement a binary search tree with insertion and search methods\nclass BinarySearchTree:"
|
| 122 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 123 |
+
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
outputs = model.generate(
|
| 126 |
+
**inputs,
|
| 127 |
+
max_length=300,
|
| 128 |
+
temperature=0.3,
|
| 129 |
+
do_sample=True,
|
| 130 |
+
pad_token_id=tokenizer.eos_token_id
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
code_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 134 |
+
print(f"Code: {code_text}")
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### Story Generation
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
# Generate creative narratives
|
| 141 |
+
prompt = "In a world where mathematics came alive, the number seven"
|
| 142 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 143 |
+
|
| 144 |
+
with torch.no_grad():
|
| 145 |
+
outputs = model.generate(
|
| 146 |
+
**inputs,
|
| 147 |
+
max_length=250,
|
| 148 |
+
temperature=0.8,
|
| 149 |
+
do_sample=True,
|
| 150 |
+
pad_token_id=tokenizer.eos_token_id
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
story_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 154 |
+
print(f"Story: {story_text}")
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
### Expert Routing Analysis
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
# Comprehensive expert analysis
|
| 161 |
+
def comprehensive_expert_analysis(model, tokenizer):
|
| 162 |
+
"""Detailed analysis of expert usage patterns"""
|
| 163 |
+
|
| 164 |
+
test_prompts = {
|
| 165 |
+
"mathematics": [
|
| 166 |
+
"The derivative of x^3 + 2x^2 - 5x + 1 is",
|
| 167 |
+
"Integration by parts formula states that",
|
| 168 |
+
"The Pythagorean theorem in higher dimensions"
|
| 169 |
+
],
|
| 170 |
+
"programming": [
|
| 171 |
+
"def fibonacci(n):",
|
| 172 |
+
"class LinkedList:",
|
| 173 |
+
"# Sort an array using merge sort"
|
| 174 |
+
],
|
| 175 |
+
"narrative": [
|
| 176 |
+
"Once upon a time in a magical forest",
|
| 177 |
+
"The old lighthouse keeper had seen many storms",
|
| 178 |
+
"In the year 2150, humanity discovered"
|
| 179 |
+
],
|
| 180 |
+
"science": [
|
| 181 |
+
"The theory of relativity explains",
|
| 182 |
+
"DNA replication involves several key enzymes",
|
| 183 |
+
"Climate change affects ocean currents by"
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
expert_patterns = {}
|
| 188 |
+
|
| 189 |
+
for domain, prompts in test_prompts.items():
|
| 190 |
+
domain_patterns = []
|
| 191 |
+
|
| 192 |
+
for prompt in prompts:
|
| 193 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 194 |
+
|
| 195 |
+
with torch.no_grad():
|
| 196 |
+
outputs = model(
|
| 197 |
+
**inputs,
|
| 198 |
+
output_router_logits=True,
|
| 199 |
+
return_dict=True
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
if hasattr(outputs, 'router_aux_losses'):
|
| 203 |
+
domain_patterns.append(outputs.router_aux_losses)
|
| 204 |
+
|
| 205 |
+
expert_patterns[domain] = domain_patterns
|
| 206 |
+
|
| 207 |
+
return expert_patterns
|
| 208 |
+
|
| 209 |
+
# Run comprehensive analysis
|
| 210 |
+
expert_analysis = comprehensive_expert_analysis(model, tokenizer)
|
| 211 |
+
print("Expert specialization analysis completed")
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
## Intended Use
|
| 215 |
+
|
| 216 |
+
### Primary Use Cases
|
| 217 |
+
- **Research**: Advanced research in mixture of experts and efficient language models
|
| 218 |
+
- **Multi-Domain Applications**: Applications requiring expertise across academic, code, and narrative domains
|
| 219 |
+
- **Efficiency Studies**: Benchmarking sparse models against dense alternatives
|
| 220 |
+
- **Educational**: Teaching advanced transformer architectures and expert routing
|
| 221 |
+
|
| 222 |
+
### Suitable Tasks
|
| 223 |
+
- Cross-domain text generation with high quality
|
| 224 |
+
- Efficient large-scale language modeling
|
| 225 |
+
- Research into expert specialization and routing
|
| 226 |
+
- Multi-modal content creation (text + code + academic writing)
|
| 227 |
+
|
| 228 |
+
## Training Methodology
|
| 229 |
+
|
| 230 |
+
### Total Loss Optimization
|
| 231 |
+
The "total" variant employs comprehensive loss optimization:
|
| 232 |
+
- **Primary Loss**: Standard causal language modeling loss
|
| 233 |
+
- **Auxiliary Loss**: Expert load balancing with enhanced coefficients
|
| 234 |
+
- **Routing Loss**: Advanced router optimization for better expert utilization
|
| 235 |
+
- **Regularization**: Enhanced regularization for improved generalization
|
| 236 |
+
|
| 237 |
+
### Expert Specialization Strategy
|
| 238 |
+
- **Domain-Aware Training**: Training schedule optimized for expert specialization
|
| 239 |
+
- **Balanced Sampling**: Careful data sampling to ensure expert development
|
| 240 |
+
- **Progressive Training**: Gradual complexity increase to encourage specialization
|
| 241 |
+
|
| 242 |
+
## Performance Characteristics
|
| 243 |
+
|
| 244 |
+
### Expected Improvements over MoE-Active
|
| 245 |
+
- **Better Domain Separation**: Clearer expert specialization patterns
|
| 246 |
+
- **Improved Quality**: Higher quality generation across all domains
|
| 247 |
+
- **Enhanced Stability**: More stable expert routing during inference
|
| 248 |
+
- **Better Generalization**: Improved performance on unseen data patterns
|
| 249 |
+
|
| 250 |
+
### Computational Efficiency
|
| 251 |
+
- **Optimized Routing**: More efficient expert selection patterns
|
| 252 |
+
- **Reduced Overhead**: Lower routing computational overhead
|
| 253 |
+
- **Better Load Balancing**: More even expert utilization across tasks
|
| 254 |
+
|
| 255 |
+
## Evaluation Metrics
|
| 256 |
+
|
| 257 |
+
### Domain-Specific Performance
|
| 258 |
+
```
|
| 259 |
+
Academic Text Quality:
|
| 260 |
+
- Perplexity on ArXiv: [Add scores]
|
| 261 |
+
- Factual Accuracy: [Add scores]
|
| 262 |
+
- Coherence: [Add scores]
|
| 263 |
+
|
| 264 |
+
Code Generation Quality:
|
| 265 |
+
- HumanEval: [Add scores]
|
| 266 |
+
- MBPP: [Add scores]
|
| 267 |
+
- Syntax Correctness: [Add scores]
|
| 268 |
+
|
| 269 |
+
Narrative Quality:
|
| 270 |
+
- Story Coherence: [Add scores]
|
| 271 |
+
- Creativity Metrics: [Add scores]
|
| 272 |
+
- Readability: [Add scores]
|
| 273 |
+
```
|
| 274 |
+
|
| 275 |
+
### MoE-Specific Metrics
|
| 276 |
+
- **Expert Utilization Variance**: Lower is better (more balanced)
|
| 277 |
+
- **Routing Entropy**: Higher indicates better expert diversity
|
| 278 |
+
- **Expert Specialization Index**: Measure of domain-specific expert activation
|
| 279 |
+
|
| 280 |
+
## Environmental Impact
|
| 281 |
+
|
| 282 |
+
### Enhanced Efficiency
|
| 283 |
+
- **Improved Training Efficiency**: Better convergence properties
|
| 284 |
+
- **Optimized Inference**: More efficient expert routing
|
| 285 |
+
- **Parameter Efficiency**: Maintained sparsity with improved quality
|
| 286 |
+
|
| 287 |
+
## Technical Specifications
|
| 288 |
+
|
| 289 |
+
### Hardware Requirements
|
| 290 |
+
- **Minimum RAM**: 8GB for inference
|
| 291 |
+
- **Recommended GPU**: NVIDIA RTX 3080 or better
|
| 292 |
+
- **CPU**: Modern multi-core processor
|
| 293 |
+
- **Storage**: 2GB+ for model weights
|
| 294 |
+
|
| 295 |
+
### Software Requirements
|
| 296 |
+
- Python 3.8+
|
| 297 |
+
- PyTorch 1.12+ (with MoE support)
|
| 298 |
+
- Transformers 4.25+
|
| 299 |
+
- CUDA 11.6+ (for GPU acceleration)
|
| 300 |
+
|
| 301 |
+
## Comparison with Other Variants
|
| 302 |
+
|
| 303 |
+
| Feature | Dense-5L | MoE-Active | MoE-Total |
|
| 304 |
+
|---------|----------|------------|-----------|
|
| 305 |
+
| Parameters | ~50M | ~140M | ~140M |
|
| 306 |
+
| Active Params | 50M | ~35M | ~35M |
|
| 307 |
+
| Training Epochs | 1 | 2 | 2 |
|
| 308 |
+
| Expert Quality | N/A | Good | Enhanced |
|
| 309 |
+
| Specialization | N/A | Moderate | Strong |
|
| 310 |
+
| Stability | High | Good | Enhanced |
|
| 311 |
+
|
| 312 |
+
## Citation
|
| 313 |
+
|
| 314 |
+
```bibtex
|
| 315 |
+
@misc{moe5ltotal2024,
|
| 316 |
+
title={MoE-5L-Total-ArXiv-Code-SimpleStories: A Comprehensive Mixture of Experts Transformer},
|
| 317 |
+
author={[Your Name]},
|
| 318 |
+
year={2024},
|
| 319 |
+
howpublished={HuggingFace Model Hub},
|
| 320 |
+
url={https://huggingface.co/your-username/moe-5l-total-arxiv-code-simplestories}
|
| 321 |
+
}
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
## License
|
| 325 |
+
|
| 326 |
+
This model is released under the Apache 2.0 License. See the LICENSE file for more details.
|
| 327 |
+
|
| 328 |
+
## Model Card Authors
|
| 329 |
+
|
| 330 |
+
[Your Name] - [Your Affiliation]
|
| 331 |
+
|
| 332 |
+
## Contact
|
| 333 |
+
|
| 334 |
+
For questions or issues regarding this model, please:
|
| 335 |
+
- Open an issue on the model repository
|
| 336 |
+
- Contact: pranavkarra001@gmail.com
|
| 337 |
+
|
| 338 |
+
---
|
| 339 |
+
|
| 340 |
+
**Disclaimer**: This model represents an advanced MoE implementation designed for research and educational purposes. The "total" variant provides enhanced capabilities but requires understanding of MoE architectures for optimal use.
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"MoeTransformerForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.1,
|
| 6 |
+
"attn_eps": 1e-06,
|
| 7 |
+
"bos_token_id": 1,
|
| 8 |
+
"d_head": 64,
|
| 9 |
+
"eos_token_id": 2,
|
| 10 |
+
"ffn_eps": 1e-06,
|
| 11 |
+
"hidden_dropout": 0.1,
|
| 12 |
+
"hidden_size": 768,
|
| 13 |
+
"intermediate_size": 3072,
|
| 14 |
+
"max_position_embeddings": 1024,
|
| 15 |
+
"model_type": "moe_transformer",
|
| 16 |
+
"num_attention_heads": 12,
|
| 17 |
+
"num_experts": 8,
|
| 18 |
+
"num_hidden_layers": 5,
|
| 19 |
+
"num_key_value_heads": 8,
|
| 20 |
+
"pad_token_id": 0,
|
| 21 |
+
"rms_norm_eps": 1e-06,
|
| 22 |
+
"router_aux_loss_coef": 0.01,
|
| 23 |
+
"router_z_loss_coef": 0.001,
|
| 24 |
+
"seq_len": 512,
|
| 25 |
+
"tie_word_embeddings": false,
|
| 26 |
+
"top_k": 2,
|
| 27 |
+
"torch_dtype": "float32",
|
| 28 |
+
"transformers_version": "4.36.0",
|
| 29 |
+
"use_cache": true,
|
| 30 |
+
"vocab_size": 50256,
|
| 31 |
+
"window_size": 128
|
| 32 |
+
}
|
configuration_moe_transformer.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 2 |
+
from transformers.utils import logging
|
| 3 |
+
|
| 4 |
+
logger = logging.get_logger(__name__)
|
| 5 |
+
|
| 6 |
+
class MoeTransformerConfig(PretrainedConfig):
|
| 7 |
+
model_type = "moe_transformer"
|
| 8 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
vocab_size=50256,
|
| 13 |
+
hidden_size=768,
|
| 14 |
+
intermediate_size=3072,
|
| 15 |
+
num_hidden_layers=5,
|
| 16 |
+
num_attention_heads=12,
|
| 17 |
+
num_key_value_heads=8,
|
| 18 |
+
max_position_embeddings=1024,
|
| 19 |
+
rms_norm_eps=1e-6,
|
| 20 |
+
attention_dropout=0.1,
|
| 21 |
+
hidden_dropout=0.1,
|
| 22 |
+
use_cache=True,
|
| 23 |
+
pad_token_id=0,
|
| 24 |
+
bos_token_id=1,
|
| 25 |
+
eos_token_id=2,
|
| 26 |
+
tie_word_embeddings=False,
|
| 27 |
+
torch_dtype="float32",
|
| 28 |
+
pretraining_tp=1,
|
| 29 |
+
output_attentions=False,
|
| 30 |
+
output_hidden_states=False,
|
| 31 |
+
output_router_logits=False,
|
| 32 |
+
use_return_dict=True,
|
| 33 |
+
# MoE specific fields
|
| 34 |
+
num_experts=8,
|
| 35 |
+
top_k=2,
|
| 36 |
+
router_aux_loss_coef=0.01,
|
| 37 |
+
router_z_loss_coef=0.001,
|
| 38 |
+
# Custom fields from ModelArgs
|
| 39 |
+
d_head=64,
|
| 40 |
+
window_size=128,
|
| 41 |
+
seq_len=512,
|
| 42 |
+
attn_eps=1e-6,
|
| 43 |
+
ffn_eps=1e-6,
|
| 44 |
+
**kwargs,
|
| 45 |
+
):
|
| 46 |
+
self.vocab_size = vocab_size
|
| 47 |
+
self.hidden_size = hidden_size
|
| 48 |
+
self.intermediate_size = intermediate_size
|
| 49 |
+
self.num_hidden_layers = num_hidden_layers
|
| 50 |
+
self.num_attention_heads = num_attention_heads
|
| 51 |
+
self.num_key_value_heads = num_key_value_heads
|
| 52 |
+
self.max_position_embeddings = max_position_embeddings
|
| 53 |
+
self.rms_norm_eps = rms_norm_eps
|
| 54 |
+
self.attention_dropout = attention_dropout
|
| 55 |
+
self.hidden_dropout = hidden_dropout
|
| 56 |
+
self.use_cache = use_cache
|
| 57 |
+
self.pretraining_tp = pretraining_tp
|
| 58 |
+
self.output_attentions = output_attentions
|
| 59 |
+
self.output_hidden_states = output_hidden_states
|
| 60 |
+
self.output_router_logits = output_router_logits
|
| 61 |
+
self.use_return_dict = use_return_dict
|
| 62 |
+
|
| 63 |
+
# MoE specific
|
| 64 |
+
self.num_experts = num_experts
|
| 65 |
+
self.top_k = top_k
|
| 66 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
| 67 |
+
self.router_z_loss_coef = router_z_loss_coef
|
| 68 |
+
|
| 69 |
+
# Custom fields
|
| 70 |
+
self.d_head = d_head
|
| 71 |
+
self.window_size = window_size
|
| 72 |
+
self.seq_len = seq_len
|
| 73 |
+
self.attn_eps = attn_eps
|
| 74 |
+
self.ffn_eps = ffn_eps
|
| 75 |
+
|
| 76 |
+
super().__init__(
|
| 77 |
+
pad_token_id=pad_token_id,
|
| 78 |
+
bos_token_id=bos_token_id,
|
| 79 |
+
eos_token_id=eos_token_id,
|
| 80 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 81 |
+
torch_dtype=torch_dtype,
|
| 82 |
+
**kwargs,
|
| 83 |
+
)
|
modeling_moe_transformer.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from typing import Optional, Tuple, Union
|
| 6 |
+
from transformers import PreTrainedModel
|
| 7 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 8 |
+
from transformers.utils import logging
|
| 9 |
+
from .configuration_moe_transformer import MoeTransformerConfig
|
| 10 |
+
|
| 11 |
+
logger = logging.get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
class RMSNorm(nn.Module):
|
| 14 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 17 |
+
self.variance_epsilon = eps
|
| 18 |
+
|
| 19 |
+
def forward(self, hidden_states):
|
| 20 |
+
input_dtype = hidden_states.dtype
|
| 21 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 22 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 23 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 24 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 25 |
+
|
| 26 |
+
class RotaryEmbedding(nn.Module):
|
| 27 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.dim = dim
|
| 30 |
+
self.max_position_embeddings = max_position_embeddings
|
| 31 |
+
self.base = base
|
| 32 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 33 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 34 |
+
|
| 35 |
+
def forward(self, x, seq_len=None):
|
| 36 |
+
if seq_len is None:
|
| 37 |
+
seq_len = x.shape[-2]
|
| 38 |
+
t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
|
| 39 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 40 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 41 |
+
cos = emb.cos()
|
| 42 |
+
sin = emb.sin()
|
| 43 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 44 |
+
|
| 45 |
+
def rotate_half(x):
|
| 46 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 47 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 48 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 49 |
+
|
| 50 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 51 |
+
cos = cos[position_ids].unsqueeze(1)
|
| 52 |
+
sin = sin[position_ids].unsqueeze(1)
|
| 53 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 54 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 55 |
+
return q_embed, k_embed
|
| 56 |
+
|
| 57 |
+
class MoeAttention(nn.Module):
|
| 58 |
+
def __init__(self, config):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.config = config
|
| 61 |
+
self.hidden_size = config.hidden_size
|
| 62 |
+
self.num_heads = config.num_attention_heads
|
| 63 |
+
self.head_dim = getattr(config, 'd_head', self.hidden_size // self.num_heads)
|
| 64 |
+
self.num_key_value_heads = getattr(config, 'num_key_value_heads', self.num_heads)
|
| 65 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 66 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 67 |
+
self.attention_dropout = config.attention_dropout
|
| 68 |
+
|
| 69 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 70 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 71 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 72 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 73 |
+
|
| 74 |
+
self.rotary_emb = RotaryEmbedding(
|
| 75 |
+
self.head_dim,
|
| 76 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def forward(
|
| 80 |
+
self,
|
| 81 |
+
hidden_states: torch.Tensor,
|
| 82 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 83 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 84 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 85 |
+
output_attentions: bool = False,
|
| 86 |
+
use_cache: bool = False,
|
| 87 |
+
):
|
| 88 |
+
bsz, q_len, _ = hidden_states.size()
|
| 89 |
+
|
| 90 |
+
query_states = self.q_proj(hidden_states)
|
| 91 |
+
key_states = self.k_proj(hidden_states)
|
| 92 |
+
value_states = self.v_proj(hidden_states)
|
| 93 |
+
|
| 94 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 95 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 96 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 97 |
+
|
| 98 |
+
kv_seq_len = key_states.shape[-2]
|
| 99 |
+
if past_key_value is not None:
|
| 100 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 101 |
+
|
| 102 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 103 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 104 |
+
|
| 105 |
+
if past_key_value is not None:
|
| 106 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 107 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 108 |
+
|
| 109 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 110 |
+
|
| 111 |
+
# Repeat k/v heads if n_kv_heads < n_heads
|
| 112 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 113 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 114 |
+
|
| 115 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 116 |
+
|
| 117 |
+
if attention_mask is not None:
|
| 118 |
+
attn_weights = attn_weights + attention_mask
|
| 119 |
+
|
| 120 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 121 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 122 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 123 |
+
|
| 124 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 125 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 126 |
+
attn_output = self.o_proj(attn_output)
|
| 127 |
+
|
| 128 |
+
if not output_attentions:
|
| 129 |
+
attn_weights = None
|
| 130 |
+
|
| 131 |
+
return attn_output, attn_weights, past_key_value
|
| 132 |
+
|
| 133 |
+
class MoeRouter(nn.Module):
|
| 134 |
+
def __init__(self, config):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.num_experts = config.num_experts
|
| 137 |
+
self.top_k = config.top_k
|
| 138 |
+
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
| 139 |
+
|
| 140 |
+
def forward(self, hidden_states):
|
| 141 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 142 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 143 |
+
|
| 144 |
+
# Calculate routing weights
|
| 145 |
+
router_logits = self.gate(hidden_states)
|
| 146 |
+
|
| 147 |
+
# Apply softmax and get top-k experts
|
| 148 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
| 149 |
+
routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
|
| 150 |
+
|
| 151 |
+
# Normalize routing weights
|
| 152 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 153 |
+
|
| 154 |
+
# Calculate auxiliary loss for load balancing
|
| 155 |
+
aux_loss = self._auxiliary_loss(router_logits, routing_weights, selected_experts)
|
| 156 |
+
|
| 157 |
+
return routing_weights, selected_experts, aux_loss
|
| 158 |
+
|
| 159 |
+
def _auxiliary_loss(self, router_logits, routing_weights, selected_experts):
|
| 160 |
+
# Load balancing loss to encourage equal expert usage
|
| 161 |
+
num_tokens = router_logits.shape[0]
|
| 162 |
+
|
| 163 |
+
# Calculate frequency of expert selection
|
| 164 |
+
expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts).float()
|
| 165 |
+
tokens_per_expert = expert_mask.sum(dim=0).sum(dim=0)
|
| 166 |
+
|
| 167 |
+
# Calculate router probability mass per expert
|
| 168 |
+
router_prob_per_expert = F.softmax(router_logits, dim=-1).sum(dim=0)
|
| 169 |
+
|
| 170 |
+
# Auxiliary loss encourages uniform distribution
|
| 171 |
+
aux_loss = (tokens_per_expert * router_prob_per_expert).sum() / (num_tokens * self.num_experts)
|
| 172 |
+
|
| 173 |
+
return aux_loss
|
| 174 |
+
|
| 175 |
+
class MoeExpert(nn.Module):
|
| 176 |
+
def __init__(self, config):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 179 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 180 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 181 |
+
self.act_fn = nn.SiLU()
|
| 182 |
+
|
| 183 |
+
def forward(self, x):
|
| 184 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 185 |
+
|
| 186 |
+
class MoeMLP(nn.Module):
|
| 187 |
+
def __init__(self, config):
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.config = config
|
| 190 |
+
self.num_experts = config.num_experts
|
| 191 |
+
self.top_k = config.top_k
|
| 192 |
+
self.hidden_size = config.hidden_size
|
| 193 |
+
self.intermediate_size = config.intermediate_size
|
| 194 |
+
|
| 195 |
+
self.router = MoeRouter(config)
|
| 196 |
+
self.experts = nn.ModuleList([MoeExpert(config) for _ in range(self.num_experts)])
|
| 197 |
+
|
| 198 |
+
def forward(self, hidden_states):
|
| 199 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 200 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 201 |
+
|
| 202 |
+
# Route tokens to experts
|
| 203 |
+
routing_weights, selected_experts, aux_loss = self.router(hidden_states)
|
| 204 |
+
|
| 205 |
+
final_hidden_states = torch.zeros(
|
| 206 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Process tokens through selected experts
|
| 210 |
+
for expert_idx in range(self.num_experts):
|
| 211 |
+
expert_mask = (selected_experts == expert_idx).any(dim=-1)
|
| 212 |
+
if expert_mask.any():
|
| 213 |
+
expert_tokens = hidden_states[expert_mask]
|
| 214 |
+
expert_output = self.experts[expert_idx](expert_tokens)
|
| 215 |
+
|
| 216 |
+
# Get routing weights for this expert
|
| 217 |
+
expert_routing_weights = routing_weights[expert_mask]
|
| 218 |
+
expert_weights = (selected_experts[expert_mask] == expert_idx).float()
|
| 219 |
+
combined_weights = expert_routing_weights * expert_weights
|
| 220 |
+
combined_weights = combined_weights.sum(dim=-1, keepdim=True)
|
| 221 |
+
|
| 222 |
+
# Add weighted expert output
|
| 223 |
+
final_hidden_states[expert_mask] += expert_output * combined_weights
|
| 224 |
+
|
| 225 |
+
final_hidden_states = final_hidden_states.view(batch_size, sequence_length, hidden_dim)
|
| 226 |
+
|
| 227 |
+
return final_hidden_states, aux_loss
|
| 228 |
+
|
| 229 |
+
class MoeDecoderLayer(nn.Module):
|
| 230 |
+
def __init__(self, config):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.hidden_size = config.hidden_size
|
| 233 |
+
self.self_attn = MoeAttention(config)
|
| 234 |
+
self.mlp = MoeMLP(config)
|
| 235 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 236 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 237 |
+
|
| 238 |
+
def forward(
|
| 239 |
+
self,
|
| 240 |
+
hidden_states: torch.Tensor,
|
| 241 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 242 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 243 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 244 |
+
output_attentions: Optional[bool] = False,
|
| 245 |
+
use_cache: Optional[bool] = False,
|
| 246 |
+
output_router_logits: Optional[bool] = False,
|
| 247 |
+
):
|
| 248 |
+
residual = hidden_states
|
| 249 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 250 |
+
|
| 251 |
+
# Self Attention
|
| 252 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 253 |
+
hidden_states=hidden_states,
|
| 254 |
+
attention_mask=attention_mask,
|
| 255 |
+
position_ids=position_ids,
|
| 256 |
+
past_key_value=past_key_value,
|
| 257 |
+
output_attentions=output_attentions,
|
| 258 |
+
use_cache=use_cache,
|
| 259 |
+
)
|
| 260 |
+
hidden_states = residual + hidden_states
|
| 261 |
+
|
| 262 |
+
# MoE Layer
|
| 263 |
+
residual = hidden_states
|
| 264 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 265 |
+
hidden_states, router_aux_loss = self.mlp(hidden_states)
|
| 266 |
+
hidden_states = residual + hidden_states
|
| 267 |
+
|
| 268 |
+
outputs = (hidden_states,)
|
| 269 |
+
|
| 270 |
+
if output_attentions:
|
| 271 |
+
outputs += (self_attn_weights,)
|
| 272 |
+
|
| 273 |
+
if use_cache:
|
| 274 |
+
outputs += (present_key_value,)
|
| 275 |
+
|
| 276 |
+
if output_router_logits:
|
| 277 |
+
outputs += (router_aux_loss,)
|
| 278 |
+
|
| 279 |
+
return outputs
|
| 280 |
+
|
| 281 |
+
class MoeTransformerPreTrainedModel(PreTrainedModel):
|
| 282 |
+
config_class = MoeTransformerConfig
|
| 283 |
+
base_model_prefix = "model"
|
| 284 |
+
supports_gradient_checkpointing = True
|
| 285 |
+
_no_split_modules = ["MoeDecoderLayer"]
|
| 286 |
+
_skip_keys_device_placement = "past_key_values"
|
| 287 |
+
|
| 288 |
+
def _init_weights(self, module):
|
| 289 |
+
std = self.config.initializer_range if hasattr(self.config, 'initializer_range') else 0.02
|
| 290 |
+
if isinstance(module, nn.Linear):
|
| 291 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 292 |
+
if module.bias is not None:
|
| 293 |
+
module.bias.data.zero_()
|
| 294 |
+
elif isinstance(module, nn.Embedding):
|
| 295 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 296 |
+
if module.padding_idx is not None:
|
| 297 |
+
module.weight.data[module.padding_idx].zero_()
|
| 298 |
+
|
| 299 |
+
class MoeTransformerModel(MoeTransformerPreTrainedModel):
|
| 300 |
+
def __init__(self, config):
|
| 301 |
+
super().__init__(config)
|
| 302 |
+
self.padding_idx = config.pad_token_id
|
| 303 |
+
self.vocab_size = config.vocab_size
|
| 304 |
+
|
| 305 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 306 |
+
self.layers = nn.ModuleList([MoeDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 307 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 308 |
+
|
| 309 |
+
self.gradient_checkpointing = False
|
| 310 |
+
self.post_init()
|
| 311 |
+
|
| 312 |
+
def get_input_embeddings(self):
|
| 313 |
+
return self.embed_tokens
|
| 314 |
+
|
| 315 |
+
def set_input_embeddings(self, value):
|
| 316 |
+
self.embed_tokens = value
|
| 317 |
+
|
| 318 |
+
def forward(
|
| 319 |
+
self,
|
| 320 |
+
input_ids: torch.LongTensor = None,
|
| 321 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 322 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 323 |
+
past_key_values: Optional[list] = None,
|
| 324 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 325 |
+
use_cache: Optional[bool] = None,
|
| 326 |
+
output_attentions: Optional[bool] = None,
|
| 327 |
+
output_hidden_states: Optional[bool] = None,
|
| 328 |
+
output_router_logits: Optional[bool] = None,
|
| 329 |
+
return_dict: Optional[bool] = None,
|
| 330 |
+
):
|
| 331 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 332 |
+
output_hidden_states = (
|
| 333 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 334 |
+
)
|
| 335 |
+
output_router_logits = (
|
| 336 |
+
output_router_logits if output_router_logits is not None else getattr(self.config, 'output_router_logits', False)
|
| 337 |
+
)
|
| 338 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 339 |
+
|
| 340 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 341 |
+
|
| 342 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 343 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 344 |
+
elif input_ids is not None:
|
| 345 |
+
batch_size, seq_length = input_ids.shape
|
| 346 |
+
elif inputs_embeds is not None:
|
| 347 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 350 |
+
|
| 351 |
+
seq_length_with_past = seq_length
|
| 352 |
+
past_key_values_length = 0
|
| 353 |
+
|
| 354 |
+
if past_key_values is not None:
|
| 355 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 356 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 357 |
+
|
| 358 |
+
if position_ids is None:
|
| 359 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 360 |
+
position_ids = torch.arange(
|
| 361 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 362 |
+
)
|
| 363 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 364 |
+
else:
|
| 365 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
| 366 |
+
|
| 367 |
+
if inputs_embeds is None:
|
| 368 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 369 |
+
|
| 370 |
+
if attention_mask is None:
|
| 371 |
+
attention_mask = torch.ones(
|
| 372 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 376 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
hidden_states = inputs_embeds
|
| 380 |
+
|
| 381 |
+
if self.gradient_checkpointing and self.training:
|
| 382 |
+
if use_cache:
|
| 383 |
+
logger.warning_once(
|
| 384 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 385 |
+
)
|
| 386 |
+
use_cache = False
|
| 387 |
+
|
| 388 |
+
all_hidden_states = () if output_hidden_states else None
|
| 389 |
+
all_self_attns = () if output_attentions else None
|
| 390 |
+
all_router_aux_losses = () if output_router_logits else None
|
| 391 |
+
next_decoder_cache = () if use_cache else None
|
| 392 |
+
|
| 393 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 394 |
+
if output_hidden_states:
|
| 395 |
+
all_hidden_states += (hidden_states,)
|
| 396 |
+
|
| 397 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 398 |
+
|
| 399 |
+
if self.gradient_checkpointing and self.training:
|
| 400 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 401 |
+
decoder_layer.__call__,
|
| 402 |
+
hidden_states,
|
| 403 |
+
attention_mask,
|
| 404 |
+
position_ids,
|
| 405 |
+
past_key_value,
|
| 406 |
+
output_attentions,
|
| 407 |
+
use_cache,
|
| 408 |
+
output_router_logits,
|
| 409 |
+
)
|
| 410 |
+
else:
|
| 411 |
+
layer_outputs = decoder_layer(
|
| 412 |
+
hidden_states,
|
| 413 |
+
attention_mask=attention_mask,
|
| 414 |
+
position_ids=position_ids,
|
| 415 |
+
past_key_value=past_key_value,
|
| 416 |
+
output_attentions=output_attentions,
|
| 417 |
+
use_cache=use_cache,
|
| 418 |
+
output_router_logits=output_router_logits,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
hidden_states = layer_outputs[0]
|
| 422 |
+
|
| 423 |
+
if use_cache:
|
| 424 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 425 |
+
|
| 426 |
+
if output_attentions:
|
| 427 |
+
all_self_attns += (layer_outputs[1],)
|
| 428 |
+
|
| 429 |
+
if output_router_logits:
|
| 430 |
+
all_router_aux_losses += (layer_outputs[-1],)
|
| 431 |
+
|
| 432 |
+
hidden_states = self.norm(hidden_states)
|
| 433 |
+
|
| 434 |
+
if output_hidden_states:
|
| 435 |
+
all_hidden_states += (hidden_states,)
|
| 436 |
+
|
| 437 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 438 |
+
if not return_dict:
|
| 439 |
+
outputs = [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
| 440 |
+
if output_router_logits:
|
| 441 |
+
outputs.append(all_router_aux_losses)
|
| 442 |
+
return tuple(v for v in outputs if v is not None)
|
| 443 |
+
|
| 444 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 445 |
+
|
| 446 |
+
# Create custom output for MoE models
|
| 447 |
+
class MoeModelOutputWithPast(BaseModelOutputWithPast):
|
| 448 |
+
def __init__(self, last_hidden_state=None, past_key_values=None, hidden_states=None, attentions=None, router_aux_losses=None):
|
| 449 |
+
super().__init__(last_hidden_state, past_key_values, hidden_states, attentions)
|
| 450 |
+
self.router_aux_losses = router_aux_losses
|
| 451 |
+
|
| 452 |
+
return MoeModelOutputWithPast(
|
| 453 |
+
last_hidden_state=hidden_states,
|
| 454 |
+
past_key_values=next_cache,
|
| 455 |
+
hidden_states=all_hidden_states,
|
| 456 |
+
attentions=all_self_attns,
|
| 457 |
+
router_aux_losses=all_router_aux_losses,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 461 |
+
# create causal mask
|
| 462 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 463 |
+
combined_attention_mask = None
|
| 464 |
+
if input_shape[-1] > 1:
|
| 465 |
+
combined_attention_mask = self._make_causal_mask(
|
| 466 |
+
input_shape,
|
| 467 |
+
inputs_embeds.dtype,
|
| 468 |
+
device=inputs_embeds.device,
|
| 469 |
+
past_key_values_length=past_key_values_length,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
if attention_mask is not None:
|
| 473 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 474 |
+
expanded_attn_mask = self._expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
| 475 |
+
inputs_embeds.device
|
| 476 |
+
)
|
| 477 |
+
combined_attention_mask = (
|
| 478 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
return combined_attention_mask
|
| 482 |
+
|
| 483 |
+
@staticmethod
|
| 484 |
+
def _make_causal_mask(
|
| 485 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 486 |
+
):
|
| 487 |
+
bsz, tgt_len = input_ids_shape
|
| 488 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 489 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 490 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 491 |
+
mask = mask.to(dtype)
|
| 492 |
+
|
| 493 |
+
if past_key_values_length > 0:
|
| 494 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 495 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 496 |
+
|
| 497 |
+
@staticmethod
|
| 498 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 499 |
+
bsz, src_len = mask.size()
|
| 500 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 501 |
+
|
| 502 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 503 |
+
|
| 504 |
+
inverted_mask = 1.0 - expanded_mask
|
| 505 |
+
|
| 506 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 507 |
+
|
| 508 |
+
class MoeTransformerForCausalLM(MoeTransformerPreTrainedModel):
|
| 509 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 510 |
+
|
| 511 |
+
def __init__(self, config):
|
| 512 |
+
super().__init__(config)
|
| 513 |
+
self.model = MoeTransformerModel(config)
|
| 514 |
+
self.vocab_size = config.vocab_size
|
| 515 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 516 |
+
|
| 517 |
+
# MoE specific config
|
| 518 |
+
self.router_aux_loss_coef = getattr(config, 'router_aux_loss_coef', 0.01)
|
| 519 |
+
self.router_z_loss_coef = getattr(config, 'router_z_loss_coef', 0.001)
|
| 520 |
+
|
| 521 |
+
# Initialize weights and apply final processing
|
| 522 |
+
self.post_init()
|
| 523 |
+
|
| 524 |
+
def get_input_embeddings(self):
|
| 525 |
+
return self.model.embed_tokens
|
| 526 |
+
|
| 527 |
+
def set_input_embeddings(self, value):
|
| 528 |
+
self.model.embed_tokens = value
|
| 529 |
+
|
| 530 |
+
def get_output_embeddings(self):
|
| 531 |
+
return self.lm_head
|
| 532 |
+
|
| 533 |
+
def set_output_embeddings(self, new_embeddings):
|
| 534 |
+
self.lm_head = new_embeddings
|
| 535 |
+
|
| 536 |
+
def set_decoder(self, decoder):
|
| 537 |
+
self.model = decoder
|
| 538 |
+
|
| 539 |
+
def get_decoder(self):
|
| 540 |
+
return self.model
|
| 541 |
+
|
| 542 |
+
def forward(
|
| 543 |
+
self,
|
| 544 |
+
input_ids: torch.LongTensor = None,
|
| 545 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 546 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 547 |
+
past_key_values: Optional[list] = None,
|
| 548 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 549 |
+
labels: Optional[torch.LongTensor] = None,
|
| 550 |
+
use_cache: Optional[bool] = None,
|
| 551 |
+
output_attentions: Optional[bool] = None,
|
| 552 |
+
output_hidden_states: Optional[bool] = None,
|
| 553 |
+
output_router_logits: Optional[bool] = None,
|
| 554 |
+
return_dict: Optional[bool] = None,
|
| 555 |
+
):
|
| 556 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 557 |
+
output_hidden_states = (
|
| 558 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 559 |
+
)
|
| 560 |
+
output_router_logits = (
|
| 561 |
+
output_router_logits if output_router_logits is not None else getattr(self.config, 'output_router_logits', False)
|
| 562 |
+
)
|
| 563 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 564 |
+
|
| 565 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 566 |
+
outputs = self.model(
|
| 567 |
+
input_ids=input_ids,
|
| 568 |
+
attention_mask=attention_mask,
|
| 569 |
+
position_ids=position_ids,
|
| 570 |
+
past_key_values=past_key_values,
|
| 571 |
+
inputs_embeds=inputs_embeds,
|
| 572 |
+
use_cache=use_cache,
|
| 573 |
+
output_attentions=output_attentions,
|
| 574 |
+
output_hidden_states=output_hidden_states,
|
| 575 |
+
output_router_logits=output_router_logits,
|
| 576 |
+
return_dict=return_dict,
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
hidden_states = outputs[0]
|
| 580 |
+
if self.config.pretraining_tp > 1:
|
| 581 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 582 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 583 |
+
logits = torch.cat(logits, dim=-1)
|
| 584 |
+
else:
|
| 585 |
+
logits = self.lm_head(hidden_states)
|
| 586 |
+
logits = logits.float()
|
| 587 |
+
|
| 588 |
+
loss = None
|
| 589 |
+
if labels is not None:
|
| 590 |
+
# Shift so that tokens < n predict n
|
| 591 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 592 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 593 |
+
# Flatten the tokens
|
| 594 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 595 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 596 |
+
shift_labels = shift_labels.view(-1)
|
| 597 |
+
# Enable model parallelism
|
| 598 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 599 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 600 |
+
|
| 601 |
+
# Add auxiliary loss from MoE routing
|
| 602 |
+
if output_router_logits and hasattr(outputs, 'router_aux_losses'):
|
| 603 |
+
aux_loss = sum(outputs.router_aux_losses)
|
| 604 |
+
loss += self.router_aux_loss_coef * aux_loss
|
| 605 |
+
|
| 606 |
+
if not return_dict:
|
| 607 |
+
output = (logits,) + outputs[1:]
|
| 608 |
+
return (loss,) + output if loss is not None else output
|
| 609 |
+
|
| 610 |
+
# Create custom output class for MoE
|
| 611 |
+
class MoeCausalLMOutputWithPast(CausalLMOutputWithPast):
|
| 612 |
+
def __init__(self, loss=None, logits=None, past_key_values=None, hidden_states=None, attentions=None, router_aux_losses=None):
|
| 613 |
+
super().__init__(loss, logits, past_key_values, hidden_states, attentions)
|
| 614 |
+
self.router_aux_losses = router_aux_losses
|
| 615 |
+
|
| 616 |
+
return MoeCausalLMOutputWithPast(
|
| 617 |
+
loss=loss,
|
| 618 |
+
logits=logits,
|
| 619 |
+
past_key_values=outputs.past_key_values,
|
| 620 |
+
hidden_states=outputs.hidden_states,
|
| 621 |
+
attentions=outputs.attentions,
|
| 622 |
+
router_aux_losses=getattr(outputs, 'router_aux_losses', None),
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
def prepare_inputs_for_generation(
|
| 626 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 627 |
+
):
|
| 628 |
+
if past_key_values:
|
| 629 |
+
input_ids = input_ids[:, -1:]
|
| 630 |
+
|
| 631 |
+
position_ids = kwargs.get("position_ids", None)
|
| 632 |
+
if attention_mask is not None and position_ids is None:
|
| 633 |
+
# create position_ids on the fly for batch generation
|
| 634 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 635 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 636 |
+
if past_key_values:
|
| 637 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 638 |
+
|
| 639 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 640 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 641 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 642 |
+
else:
|
| 643 |
+
model_inputs = {"input_ids": input_ids}
|
| 644 |
+
|
| 645 |
+
model_inputs.update(
|
| 646 |
+
{
|
| 647 |
+
"position_ids": position_ids,
|
| 648 |
+
"past_key_values": past_key_values,
|
| 649 |
+
"use_cache": kwargs.get("use_cache"),
|
| 650 |
+
"attention_mask": attention_mask,
|
| 651 |
+
"output_router_logits": kwargs.get("output_router_logits", False),
|
| 652 |
+
}
|
| 653 |
+
)
|
| 654 |
+
return model_inputs
|
| 655 |
+
|
| 656 |
+
@staticmethod
|
| 657 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 658 |
+
reordered_past = ()
|
| 659 |
+
for layer_past in past_key_values:
|
| 660 |
+
reordered_past += (
|
| 661 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 662 |
+
)
|
| 663 |
+
return reordered_past
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:21ed09e2458c99053d2a8aa8d87513aeb66fb7bbf42e9c6feab68aa78161eb12
|
| 3 |
+
size 1494731559
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"0": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"1": {
|
| 14 |
+
"content": "<|startoftext|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"2": {
|
| 22 |
+
"content": "<|endoftext|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"bos_token": "<|startoftext|>",
|
| 31 |
+
"chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
|
| 32 |
+
"clean_up_tokenization_spaces": true,
|
| 33 |
+
"eos_token": "<|endoftext|>",
|
| 34 |
+
"legacy": false,
|
| 35 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 36 |
+
"pad_token": "<|endoftext|>",
|
| 37 |
+
"sp_model_kwargs": {},
|
| 38 |
+
"spaces_between_special_tokens": false,
|
| 39 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 40 |
+
"unk_token": "<|endoftext|>",
|
| 41 |
+
"use_default_system_prompt": false
|
| 42 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|