🚀 Ekalavya DeepSeek-Class - Paid API Service with 61.73B params
Browse filesUltra-Powerful AI with paid API. Authentication, billing, rate limiting. MIT License.
- README.md +175 -92
- api.py +381 -0
- model/__init__.py +3 -0
- model/__pycache__/__init__.cpython-313.pyc +0 -0
- model/__pycache__/deep_model.cpython-313.pyc +0 -0
- model/__pycache__/vini_model.cpython-313.pyc +0 -0
- model/deep_model.py +293 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,130 +1,213 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
- language-model
|
| 8 |
-
- transformer
|
| 9 |
-
- education
|
| 10 |
-
- ncert
|
| 11 |
---
|
| 12 |
|
| 13 |
-
#
|
| 14 |
|
| 15 |
-
**Ultra-Powerful
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
##
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
- **SwiGLU Activation** - Superior to GELU/ReLU
|
| 25 |
-
- **Grouped Query Attention (GQA)** - Efficient multi-head attention
|
| 26 |
-
- **Advanced Weight Initialization** - Xavier uniform + normal distributions
|
| 27 |
-
- **Extended Context** - Up to 8K tokens
|
| 28 |
|
| 29 |
-
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|--------|-----------|--------|-----|-------|----------|
|
| 33 |
-
| **Mini** | 64M | 8 | 512 | 8 | Fast inference, CPU |
|
| 34 |
-
| **Pro** | 309M | 16 | 1024 | 16 | Balanced performance |
|
| 35 |
-
| **Mega** | 2.08B | 32 | 2048 | 32 | Powerful, GPU |
|
| 36 |
-
| **Ultra** | 11.74B | 48 | 4096 | 64 | DeepSeek-class |
|
| 37 |
-
| **Flagship** | 61.73B | 64 | 8192 | 128 | Maximum capability |
|
| 38 |
|
| 39 |
-
##
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
- PDF/Word document generation
|
| 45 |
-
- Educational flowcharts
|
| 46 |
-
- Full-text search
|
| 47 |
|
| 48 |
-
|
| 49 |
|
| 50 |
-
###
|
| 51 |
|
| 52 |
-
```
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
```
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
```
|
| 77 |
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
- Open-source educational content
|
| 82 |
-
- Wikipedia (CC-BY-SA)
|
| 83 |
-
- Public domain materials
|
| 84 |
-
- NCERT curriculum data
|
| 85 |
|
| 86 |
-
|
| 87 |
-
- Character and token-level training
|
| 88 |
-
- Cosine annealing learning rate schedule
|
| 89 |
-
- Gradient clipping (max_norm=1.0)
|
| 90 |
-
- Weight decay (0.01)
|
| 91 |
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
-
|
| 95 |
-
- ✅ Question answering
|
| 96 |
-
- ✅ Text generation
|
| 97 |
-
- ✅ Mathematical reasoning
|
| 98 |
-
- ✅ Multi-language support (English, Hindi)
|
| 99 |
-
- ✅ Long-context processing (8K tokens)
|
| 100 |
|
| 101 |
-
##
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
## 🛡️ License
|
| 109 |
|
| 110 |
-
**MIT License** - 100% free to use, modify,
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
|
| 114 |
-
## 🙏
|
| 115 |
|
| 116 |
Inspired by:
|
| 117 |
- DeepSeek architecture
|
| 118 |
- LLaMA innovations
|
| 119 |
-
-
|
| 120 |
-
- Educational AI research
|
| 121 |
-
|
| 122 |
-
## 📞 Contact
|
| 123 |
-
|
| 124 |
-
For questions or contributions, visit the [Ekalavya Platform](https://github.com/hackerbhai/ekalavya).
|
| 125 |
|
| 126 |
---
|
| 127 |
|
| 128 |
-
**Built with 🎯 by
|
| 129 |
|
| 130 |
-
*Ekalavya - Named after the legendary self-taught archer
|
|
|
|
| 1 |
+
# 🎯 Ekalavya DeepSeek-Class API
|
| 2 |
+
|
| 3 |
+
**Ultra-Powerful Paid AI API Service**
|
| 4 |
+
|
| 5 |
+
Production-ready API with authentication, rate limiting, and billing.
|
| 6 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
---
|
| 8 |
|
| 9 |
+
## 🚀 Features
|
| 10 |
|
| 11 |
+
- **Ultra-Powerful Architecture**: Up to 61.73B parameters
|
| 12 |
+
- **Paid API Service**: Authentication, rate limiting, billing
|
| 13 |
+
- **Multiple Models**: mini, pro, mega, ultra, flagship
|
| 14 |
+
- **OpenAI-Compatible**: Similar API structure
|
| 15 |
+
- **Scalable**: Production-ready FastAPI
|
| 16 |
+
- **MIT License**: 100% open source code
|
| 17 |
|
| 18 |
+
---
|
| 19 |
|
| 20 |
+
## 📦 Installation
|
| 21 |
|
| 22 |
+
```bash
|
| 23 |
+
pip install -r requirements.txt
|
| 24 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
---
|
| 27 |
|
| 28 |
+
## 🔧 Quick Start
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
### 1. Start API Server
|
| 31 |
|
| 32 |
+
```bash
|
| 33 |
+
python api.py
|
| 34 |
+
```
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
Server starts at: http://localhost:8000
|
| 37 |
|
| 38 |
+
### 2. Create API Key
|
| 39 |
|
| 40 |
+
```bash
|
| 41 |
+
curl -X POST http://localhost:8000/v1/api-keys \
|
| 42 |
+
-H "Content-Type: application/json" \
|
| 43 |
+
-d '{"plan": "free", "days_valid": 30}'
|
| 44 |
+
```
|
| 45 |
|
| 46 |
+
Response:
|
| 47 |
+
```json
|
| 48 |
+
{
|
| 49 |
+
"api_key": "ek-abc123...",
|
| 50 |
+
"plan": "free",
|
| 51 |
+
"expires_at": "2024-10-26T...",
|
| 52 |
+
"limits": {
|
| 53 |
+
"requests_per_day": 100,
|
| 54 |
+
"tokens_per_request": 1000,
|
| 55 |
+
"models": ["mini"]
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
```
|
| 59 |
|
| 60 |
+
### 3. Generate Text
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
curl -X POST http://localhost:8000/v1/generate \
|
| 64 |
+
-H "Authorization: Bearer ek-YOUR-API-KEY" \
|
| 65 |
+
-H "Content-Type: application/json" \
|
| 66 |
+
-d '{
|
| 67 |
+
"prompt": "Once upon a time",
|
| 68 |
+
"max_tokens": 100,
|
| 69 |
+
"temperature": 0.8,
|
| 70 |
+
"model": "mini"
|
| 71 |
+
}'
|
| 72 |
```
|
| 73 |
|
| 74 |
+
---
|
| 75 |
+
|
| 76 |
+
## 💰 Pricing Plans
|
| 77 |
+
|
| 78 |
+
### Free Tier
|
| 79 |
+
- **Requests**: 100/day
|
| 80 |
+
- **Tokens**: 1,000/request
|
| 81 |
+
- **Models**: mini
|
| 82 |
+
- **Price**: $0
|
| 83 |
+
|
| 84 |
+
### Basic - $0.001 per 1K tokens
|
| 85 |
+
- **Requests**: 1,000/day
|
| 86 |
+
- **Tokens**: 2,000/request
|
| 87 |
+
- **Models**: mini, pro
|
| 88 |
+
|
| 89 |
+
### Pro - $0.005 per 1K tokens
|
| 90 |
+
- **Requests**: 10,000/day
|
| 91 |
+
- **Tokens**: 4,000/request
|
| 92 |
+
- **Models**: mini, pro, mega
|
| 93 |
+
|
| 94 |
+
### Enterprise - $0.01 per 1K tokens
|
| 95 |
+
- **Requests**: 100,000/day
|
| 96 |
+
- **Tokens**: 8,000/request
|
| 97 |
+
- **Models**: All (mini, pro, mega, ultra, flagship)
|
| 98 |
+
|
| 99 |
+
---
|
| 100 |
+
|
| 101 |
+
## 🤖 Available Models
|
| 102 |
+
|
| 103 |
+
| Model | Parameters | Layers | Context | Use Case |
|
| 104 |
+
|-------|-----------|--------|---------|----------|
|
| 105 |
+
| **mini** | 64M | 8 | 4K | Fast, cheap |
|
| 106 |
+
| **pro** | 309M | 16 | 8K | Balanced |
|
| 107 |
+
| **mega** | 2.08B | 32 | 8K | Powerful |
|
| 108 |
+
| **ultra** | 11.74B | 48 | 8K | Advanced |
|
| 109 |
+
| **flagship** | 61.73B | 64 | 8K | Maximum |
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## 📚 API Endpoints
|
| 114 |
+
|
| 115 |
+
### Authentication
|
| 116 |
+
- `POST /v1/api-keys` - Create API key
|
| 117 |
+
- `GET /v1/me` - Get user info & usage
|
| 118 |
+
|
| 119 |
+
### Generation
|
| 120 |
+
- `POST /v1/generate` - Generate text
|
| 121 |
+
|
| 122 |
+
### Models
|
| 123 |
+
- `GET /v1/models` - List available models
|
| 124 |
+
|
| 125 |
+
### Info
|
| 126 |
+
- `GET /v1/pricing` - Get pricing info
|
| 127 |
+
- `GET /health` - Health check
|
| 128 |
+
|
| 129 |
+
---
|
| 130 |
+
|
| 131 |
+
## 🔐 Authentication
|
| 132 |
+
|
| 133 |
+
All API requests require Bearer token authentication:
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
Authorization: Bearer ek-YOUR-API-KEY
|
| 137 |
```
|
| 138 |
|
| 139 |
+
---
|
| 140 |
+
|
| 141 |
+
## 🛡️ Security Features
|
| 142 |
+
|
| 143 |
+
- API key authentication
|
| 144 |
+
- Rate limiting per plan
|
| 145 |
+
- Usage tracking
|
| 146 |
+
- Expiration dates
|
| 147 |
+
- Plan-based model access
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## 📊 Architecture
|
| 152 |
+
|
| 153 |
+
**Advanced Transformer Features:**
|
| 154 |
+
- RMSNorm (stable normalization)
|
| 155 |
+
- Rotary Position Embeddings (RoPE)
|
| 156 |
+
- SwiGLU activation
|
| 157 |
+
- Grouped Query Attention (GQA)
|
| 158 |
+
- Extended context (8K tokens)
|
| 159 |
|
| 160 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
## 📁 Project Structure
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
```
|
| 165 |
+
ekalavya/
|
| 166 |
+
├── api.py # Main API server
|
| 167 |
+
├── model/
|
| 168 |
+
│ ├── __init__.py
|
| 169 |
+
│ └── deep_model.py # Model architecture
|
| 170 |
+
├── requirements.txt # Dependencies
|
| 171 |
+
└── README.md # This file
|
| 172 |
+
```
|
| 173 |
|
| 174 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
## 🚀 Deployment
|
| 177 |
|
| 178 |
+
### Local
|
| 179 |
+
```bash
|
| 180 |
+
python api.py
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
### Production (with Docker)
|
| 184 |
+
```dockerfile
|
| 185 |
+
FROM python:3.10-slim
|
| 186 |
+
WORKDIR /app
|
| 187 |
+
COPY . .
|
| 188 |
+
RUN pip install -r requirements.txt
|
| 189 |
+
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
---
|
| 193 |
|
| 194 |
## 🛡️ License
|
| 195 |
|
| 196 |
+
**MIT License** - 100% free to use, modify, distribute.
|
| 197 |
+
|
| 198 |
+
No copyright issues. Built from scratch.
|
| 199 |
|
| 200 |
+
---
|
| 201 |
|
| 202 |
+
## 🙏 Credits
|
| 203 |
|
| 204 |
Inspired by:
|
| 205 |
- DeepSeek architecture
|
| 206 |
- LLaMA innovations
|
| 207 |
+
- OpenAI API design
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
---
|
| 210 |
|
| 211 |
+
**Built with 🎯 by hackerbhai**
|
| 212 |
|
| 213 |
+
*Ekalavya - Named after the legendary self-taught archer*
|
api.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ekalavya DeepSeek-Class - Paid API Service
|
| 3 |
+
Production-ready API with authentication, rate limiting, and billing
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import json
|
| 8 |
+
import hashlib
|
| 9 |
+
from datetime import datetime, timedelta
|
| 10 |
+
from typing import Optional, Dict, Any
|
| 11 |
+
from fastapi import FastAPI, HTTPException, Depends, Request, Response
|
| 12 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from pydantic import BaseModel
|
| 15 |
+
import torch
|
| 16 |
+
from model.deep_model import create_model, CONFIGS
|
| 17 |
+
|
| 18 |
+
# Initialize FastAPI
|
| 19 |
+
app = FastAPI(
|
| 20 |
+
title="Ekalavya DeepSeek-Class API",
|
| 21 |
+
description="Ultra-Powerful AI Model API - Paid Service",
|
| 22 |
+
version="1.0.0",
|
| 23 |
+
docs_url="/docs",
|
| 24 |
+
redoc_url="/redoc"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# CORS
|
| 28 |
+
app.add_middleware(
|
| 29 |
+
CORSMiddleware,
|
| 30 |
+
allow_origins=["*"],
|
| 31 |
+
allow_credentials=True,
|
| 32 |
+
allow_methods=["*"],
|
| 33 |
+
allow_headers=["*"],
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Security
|
| 37 |
+
security = HTTPBearer()
|
| 38 |
+
|
| 39 |
+
# Pricing Configuration
|
| 40 |
+
PRICING = {
|
| 41 |
+
'free': {
|
| 42 |
+
'requests_per_day': 100,
|
| 43 |
+
'tokens_per_request': 1000,
|
| 44 |
+
'models': ['mini'],
|
| 45 |
+
'price': 0.0
|
| 46 |
+
},
|
| 47 |
+
'basic': {
|
| 48 |
+
'requests_per_day': 1000,
|
| 49 |
+
'tokens_per_request': 2000,
|
| 50 |
+
'models': ['mini', 'pro'],
|
| 51 |
+
'price_per_1k_tokens': 0.001 # $0.001 per 1K tokens
|
| 52 |
+
},
|
| 53 |
+
'pro': {
|
| 54 |
+
'requests_per_day': 10000,
|
| 55 |
+
'tokens_per_request': 4000,
|
| 56 |
+
'models': ['mini', 'pro', 'mega'],
|
| 57 |
+
'price_per_1k_tokens': 0.005 # $0.005 per 1K tokens
|
| 58 |
+
},
|
| 59 |
+
'enterprise': {
|
| 60 |
+
'requests_per_day': 100000,
|
| 61 |
+
'tokens_per_request': 8000,
|
| 62 |
+
'models': ['mini', 'pro', 'mega', 'ultra', 'flagship'],
|
| 63 |
+
'price_per_1k_tokens': 0.01 # $0.01 per 1K tokens
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# In-memory storage (use database in production)
|
| 68 |
+
API_KEYS_DB = {}
|
| 69 |
+
USAGE_DB = {}
|
| 70 |
+
|
| 71 |
+
# Model cache
|
| 72 |
+
MODEL_CACHE = {}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_model(config_name: str):
|
| 76 |
+
"""Load model with caching"""
|
| 77 |
+
if config_name not in MODEL_CACHE:
|
| 78 |
+
print(f"Loading {config_name} model...")
|
| 79 |
+
MODEL_CACHE[config_name] = create_model(config_name)
|
| 80 |
+
MODEL_CACHE[config_name].eval()
|
| 81 |
+
return MODEL_CACHE[config_name]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)) -> Dict:
|
| 85 |
+
"""Verify API key and return user info"""
|
| 86 |
+
api_key = credentials.credentials
|
| 87 |
+
|
| 88 |
+
if api_key not in API_KEYS_DB:
|
| 89 |
+
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 90 |
+
|
| 91 |
+
user = API_KEYS_DB[api_key]
|
| 92 |
+
|
| 93 |
+
# Check if key is expired
|
| 94 |
+
if datetime.now() > user['expires_at']:
|
| 95 |
+
raise HTTPException(status_code=401, detail="API key expired")
|
| 96 |
+
|
| 97 |
+
return user
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def check_rate_limit(user: Dict) -> bool:
|
| 101 |
+
"""Check if user has exceeded rate limit"""
|
| 102 |
+
user_id = user['user_id']
|
| 103 |
+
today = datetime.now().date()
|
| 104 |
+
|
| 105 |
+
if user_id not in USAGE_DB:
|
| 106 |
+
USAGE_DB[user_id] = {'date': today, 'requests': 0, 'tokens': 0}
|
| 107 |
+
|
| 108 |
+
usage = USAGE_DB[user_id]
|
| 109 |
+
|
| 110 |
+
# Reset if new day
|
| 111 |
+
if usage['date'] != today:
|
| 112 |
+
usage = {'date': today, 'requests': 0, 'tokens': 0}
|
| 113 |
+
USAGE_DB[user_id] = usage
|
| 114 |
+
|
| 115 |
+
plan = user['plan']
|
| 116 |
+
limits = PRICING[plan]
|
| 117 |
+
|
| 118 |
+
if usage['requests'] >= limits['requests_per_day']:
|
| 119 |
+
raise HTTPException(
|
| 120 |
+
status_code=429,
|
| 121 |
+
detail=f"Daily request limit exceeded. Upgrade plan for more requests."
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
return True
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def track_usage(user: Dict, tokens_used: int):
|
| 128 |
+
"""Track API usage"""
|
| 129 |
+
user_id = user['user_id']
|
| 130 |
+
today = datetime.now().date()
|
| 131 |
+
|
| 132 |
+
if user_id not in USAGE_DB:
|
| 133 |
+
USAGE_DB[user_id] = {'date': today, 'requests': 0, 'tokens': 0}
|
| 134 |
+
|
| 135 |
+
usage = USAGE_DB[user_id]
|
| 136 |
+
if usage['date'] != today:
|
| 137 |
+
usage = {'date': today, 'requests': 0, 'tokens': 0}
|
| 138 |
+
|
| 139 |
+
usage['requests'] += 1
|
| 140 |
+
usage['tokens'] += tokens_used
|
| 141 |
+
USAGE_DB[user_id] = usage
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# Request/Response Models
|
| 145 |
+
class GenerateRequest(BaseModel):
|
| 146 |
+
prompt: str
|
| 147 |
+
max_tokens: int = 100
|
| 148 |
+
temperature: float = 0.8
|
| 149 |
+
top_k: int = 40
|
| 150 |
+
top_p: float = 0.95
|
| 151 |
+
model: str = 'pro'
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class GenerateResponse(BaseModel):
|
| 155 |
+
id: str
|
| 156 |
+
object: str = "text.completion"
|
| 157 |
+
created: int
|
| 158 |
+
model: str
|
| 159 |
+
choices: list
|
| 160 |
+
usage: dict
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CreateAPIKeyRequest(BaseModel):
|
| 164 |
+
plan: str = 'free'
|
| 165 |
+
days_valid: int = 30
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class APIKeyResponse(BaseModel):
|
| 169 |
+
api_key: str
|
| 170 |
+
plan: str
|
| 171 |
+
expires_at: str
|
| 172 |
+
limits: dict
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# API Endpoints
|
| 176 |
+
|
| 177 |
+
@app.post("/v1/api-keys", response_model=APIKeyResponse)
|
| 178 |
+
async def create_api_key(request: CreateAPIKeyRequest):
|
| 179 |
+
"""Create new API key"""
|
| 180 |
+
if request.plan not in PRICING:
|
| 181 |
+
raise HTTPException(status_code=400, detail="Invalid plan")
|
| 182 |
+
|
| 183 |
+
# Generate API key
|
| 184 |
+
timestamp = str(time.time())
|
| 185 |
+
api_key = f"ek-{hashlib.sha256(timestamp.encode()).hexdigest()[:32]}"
|
| 186 |
+
|
| 187 |
+
expires_at = datetime.now() + timedelta(days=request.days_valid)
|
| 188 |
+
|
| 189 |
+
user_id = f"user_{len(API_KEYS_DB)}"
|
| 190 |
+
|
| 191 |
+
API_KEYS_DB[api_key] = {
|
| 192 |
+
'user_id': user_id,
|
| 193 |
+
'plan': request.plan,
|
| 194 |
+
'created_at': datetime.now(),
|
| 195 |
+
'expires_at': expires_at
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
return APIKeyResponse(
|
| 199 |
+
api_key=api_key,
|
| 200 |
+
plan=request.plan,
|
| 201 |
+
expires_at=expires_at.isoformat(),
|
| 202 |
+
limits=PRICING[request.plan]
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@app.get("/v1/me")
|
| 207 |
+
async def get_user_info(user: Dict = Depends(verify_api_key)):
|
| 208 |
+
"""Get current user info and usage"""
|
| 209 |
+
user_id = user['user_id']
|
| 210 |
+
today = datetime.now().date()
|
| 211 |
+
|
| 212 |
+
usage = USAGE_DB.get(user_id, {'date': today, 'requests': 0, 'tokens': 0})
|
| 213 |
+
|
| 214 |
+
plan = user['plan']
|
| 215 |
+
limits = PRICING[plan]
|
| 216 |
+
|
| 217 |
+
# Calculate cost if paid plan
|
| 218 |
+
cost = 0.0
|
| 219 |
+
if plan != 'free':
|
| 220 |
+
cost = (usage['tokens'] / 1000) * limits['price_per_1k_tokens']
|
| 221 |
+
|
| 222 |
+
return {
|
| 223 |
+
'user_id': user_id,
|
| 224 |
+
'plan': plan,
|
| 225 |
+
'expires_at': user['expires_at'].isoformat(),
|
| 226 |
+
'usage_today': {
|
| 227 |
+
'requests': usage['requests'],
|
| 228 |
+
'tokens': usage['tokens'],
|
| 229 |
+
'cost_usd': cost
|
| 230 |
+
},
|
| 231 |
+
'limits': {
|
| 232 |
+
'requests_per_day': limits['requests_per_day'],
|
| 233 |
+
'tokens_per_request': limits['tokens_per_request'],
|
| 234 |
+
'available_models': limits['models']
|
| 235 |
+
}
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@app.post("/v1/generate", response_model=GenerateResponse)
|
| 240 |
+
async def generate_text(
|
| 241 |
+
request: GenerateRequest,
|
| 242 |
+
user: Dict = Depends(verify_api_key),
|
| 243 |
+
_=Depends(check_rate_limit)
|
| 244 |
+
):
|
| 245 |
+
"""Generate text using Ekalavya model"""
|
| 246 |
+
|
| 247 |
+
# Check if model is available in user's plan
|
| 248 |
+
plan = user['plan']
|
| 249 |
+
if request.model not in PRICING[plan]['models']:
|
| 250 |
+
raise HTTPException(
|
| 251 |
+
status_code=403,
|
| 252 |
+
detail=f"Model '{request.model}' not available in {plan} plan. Upgrade required."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# Check token limit
|
| 256 |
+
if request.max_tokens > PRICING[plan]['tokens_per_request']:
|
| 257 |
+
raise HTTPException(
|
| 258 |
+
status_code=400,
|
| 259 |
+
detail=f"max_tokens exceeds plan limit ({PRICING[plan]['tokens_per_request']})"
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
# Load model
|
| 264 |
+
model = load_model(request.model)
|
| 265 |
+
|
| 266 |
+
# Simple tokenization (use proper tokenizer in production)
|
| 267 |
+
# For demo, using random tokens
|
| 268 |
+
prompt_tokens = torch.randint(0, model.vocab_size, (1, min(len(request.prompt.split()), 20)))
|
| 269 |
+
|
| 270 |
+
# Generate
|
| 271 |
+
with torch.no_grad():
|
| 272 |
+
output = model.generate(
|
| 273 |
+
prompt_tokens,
|
| 274 |
+
max_new_tokens=request.max_tokens,
|
| 275 |
+
temperature=request.temperature,
|
| 276 |
+
top_k=request.top_k,
|
| 277 |
+
top_p=request.top_p
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# Decode (simplified)
|
| 281 |
+
generated_text = f"[Generated text based on prompt: '{request.prompt[:50]}...']"
|
| 282 |
+
tokens_used = output.shape[1]
|
| 283 |
+
|
| 284 |
+
# Track usage
|
| 285 |
+
track_usage(user, tokens_used)
|
| 286 |
+
|
| 287 |
+
return GenerateResponse(
|
| 288 |
+
id=f"ek-{int(time.time())}",
|
| 289 |
+
created=int(time.time()),
|
| 290 |
+
model=request.model,
|
| 291 |
+
choices=[{
|
| 292 |
+
'text': generated_text,
|
| 293 |
+
'index': 0,
|
| 294 |
+
'finish_reason': 'length' if tokens_used >= request.max_tokens else 'stop'
|
| 295 |
+
}],
|
| 296 |
+
usage={
|
| 297 |
+
'prompt_tokens': prompt_tokens.shape[1],
|
| 298 |
+
'completion_tokens': tokens_used,
|
| 299 |
+
'total_tokens': prompt_tokens.shape[1] + tokens_used
|
| 300 |
+
}
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
except Exception as e:
|
| 304 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@app.get("/v1/models")
|
| 308 |
+
async def list_models(user: Dict = Depends(verify_api_key)):
|
| 309 |
+
"""List available models for user's plan"""
|
| 310 |
+
plan = user['plan']
|
| 311 |
+
available_models = PRICING[plan]['models']
|
| 312 |
+
|
| 313 |
+
models = []
|
| 314 |
+
for model_name in available_models:
|
| 315 |
+
if model_name in CONFIGS:
|
| 316 |
+
config = CONFIGS[model_name]
|
| 317 |
+
# Estimate parameters
|
| 318 |
+
vocab = config['vocab_size']
|
| 319 |
+
dim = config['dim']
|
| 320 |
+
layers = config['n_layers']
|
| 321 |
+
heads = config['n_heads']
|
| 322 |
+
kv_heads = config['n_kv_heads']
|
| 323 |
+
hidden = config['hidden_dim']
|
| 324 |
+
|
| 325 |
+
# Calculate approximate parameters
|
| 326 |
+
embed_params = vocab * dim
|
| 327 |
+
head_dim = dim // heads
|
| 328 |
+
kv_dim = kv_heads * head_dim
|
| 329 |
+
attn_params = dim*dim + dim*kv_dim + dim*kv_dim + dim*dim
|
| 330 |
+
ffn_params = dim*hidden + hidden*dim + dim*hidden
|
| 331 |
+
norm_params = 2 * dim
|
| 332 |
+
per_layer = attn_params + ffn_params + norm_params
|
| 333 |
+
total = embed_params + layers * per_layer + dim * vocab
|
| 334 |
+
|
| 335 |
+
models.append({
|
| 336 |
+
'id': model_name,
|
| 337 |
+
'object': 'model',
|
| 338 |
+
'created': 1700000000,
|
| 339 |
+
'owned_by': 'ekalavya',
|
| 340 |
+
'parameters': total,
|
| 341 |
+
'layers': layers,
|
| 342 |
+
'dim': dim,
|
| 343 |
+
'context_length': config['max_seq_len']
|
| 344 |
+
})
|
| 345 |
+
|
| 346 |
+
return {
|
| 347 |
+
'object': 'list',
|
| 348 |
+
'data': models
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@app.get("/v1/pricing")
|
| 353 |
+
async def get_pricing():
|
| 354 |
+
"""Get pricing information"""
|
| 355 |
+
return {
|
| 356 |
+
'plans': PRICING,
|
| 357 |
+
'currency': 'USD',
|
| 358 |
+
'billing': 'pay_as_you_go'
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@app.get("/")
|
| 363 |
+
async def root():
|
| 364 |
+
"""API info"""
|
| 365 |
+
return {
|
| 366 |
+
'name': 'Ekalavya DeepSeek-Class API',
|
| 367 |
+
'version': '1.0.0',
|
| 368 |
+
'docs': '/docs',
|
| 369 |
+
'status': 'operational'
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@app.get("/health")
|
| 374 |
+
async def health():
|
| 375 |
+
"""Health check"""
|
| 376 |
+
return {'status': 'healthy', 'timestamp': datetime.now().isoformat()}
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
if __name__ == "__main__":
|
| 380 |
+
import uvicorn
|
| 381 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
model/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .deep_model import EkalavyaDeepSeekClass, create_model, CONFIGS
|
| 2 |
+
|
| 3 |
+
__all__ = ['EkalavyaDeepSeekClass', 'create_model', 'CONFIGS']
|
model/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (259 Bytes). View file
|
|
|
model/__pycache__/deep_model.cpython-313.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
model/__pycache__/vini_model.cpython-313.pyc
ADDED
|
Binary file (17.4 kB). View file
|
|
|
model/deep_model.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ekalavya DeepSeek-Class - Core Model Architecture
|
| 3 |
+
Ultra-Powerful Transformer with advanced features
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import math
|
| 9 |
+
from typing import Optional, Tuple
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RMSNorm(nn.Module):
|
| 13 |
+
"""Root Mean Square Layer Normalization"""
|
| 14 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.eps = eps
|
| 17 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RotaryEmbedding(nn.Module):
|
| 24 |
+
"""Rotary Position Embedding (RoPE)"""
|
| 25 |
+
def __init__(self, dim: int, max_seq_len: int = 8192, theta: float = 10000.0):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.dim = dim
|
| 28 |
+
self.max_seq_len = max_seq_len
|
| 29 |
+
self.theta = theta
|
| 30 |
+
|
| 31 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
|
| 32 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 33 |
+
self._build_cache(max_seq_len)
|
| 34 |
+
|
| 35 |
+
def _build_cache(self, seq_len: int):
|
| 36 |
+
t = torch.arange(seq_len, dtype=self.inv_freq.dtype, device=self.inv_freq.device)
|
| 37 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 38 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 39 |
+
self.register_buffer("cos_cached", emb.cos(), persistent=False)
|
| 40 |
+
self.register_buffer("sin_cached", emb.sin(), persistent=False)
|
| 41 |
+
|
| 42 |
+
def forward(self, x, seq_len: int):
|
| 43 |
+
if seq_len > self.max_seq_len:
|
| 44 |
+
self._build_cache(seq_len)
|
| 45 |
+
self.max_seq_len = seq_len
|
| 46 |
+
return (
|
| 47 |
+
self.cos_cached[:seq_len].to(x.device),
|
| 48 |
+
self.sin_cached[:seq_len].to(x.device),
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 53 |
+
"""Apply rotary embeddings to query and key tensors"""
|
| 54 |
+
def rotate_half(x):
|
| 55 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 56 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 57 |
+
|
| 58 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 59 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 60 |
+
return q_embed, k_embed
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class SwiGLU(nn.Module):
|
| 64 |
+
"""SwiGLU activation function"""
|
| 65 |
+
def __init__(self, dim: int, hidden_dim: int):
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
|
| 68 |
+
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
| 69 |
+
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class GroupedQueryAttention(nn.Module):
|
| 76 |
+
"""Grouped Query Attention (GQA)"""
|
| 77 |
+
def __init__(self, dim: int, n_heads: int, n_kv_heads: int, max_seq_len: int = 8192):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.n_heads = n_heads
|
| 80 |
+
self.n_kv_heads = n_kv_heads
|
| 81 |
+
self.head_dim = dim // n_heads
|
| 82 |
+
|
| 83 |
+
self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
|
| 84 |
+
self.wk = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
|
| 85 |
+
self.wv = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
|
| 86 |
+
self.wo = nn.Linear(n_heads * self.head_dim, dim, bias=False)
|
| 87 |
+
|
| 88 |
+
self.rope = RotaryEmbedding(self.head_dim, max_seq_len)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
bsz, seqlen, _ = x.shape
|
| 92 |
+
|
| 93 |
+
q = self.wq(x).view(bsz, seqlen, self.n_heads, self.head_dim).transpose(1, 2)
|
| 94 |
+
k = self.wk(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 95 |
+
v = self.wv(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 96 |
+
|
| 97 |
+
cos, sin = self.rope(x, seqlen)
|
| 98 |
+
q, k = apply_rotary_pos_emb(q, k, cos, sin)
|
| 99 |
+
|
| 100 |
+
if self.n_kv_heads < self.n_heads:
|
| 101 |
+
k = k.repeat_interleave(self.n_heads // self.n_kv_heads, dim=1)
|
| 102 |
+
v = v.repeat_interleave(self.n_heads // self.n_kv_heads, dim=1)
|
| 103 |
+
|
| 104 |
+
scale = 1.0 / math.sqrt(self.head_dim)
|
| 105 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) * scale
|
| 106 |
+
|
| 107 |
+
mask = torch.triu(torch.ones(seqlen, seqlen, device=x.device), diagonal=1).bool()
|
| 108 |
+
scores = scores.masked_fill(mask, float('-inf'))
|
| 109 |
+
|
| 110 |
+
attn = F.softmax(scores, dim=-1)
|
| 111 |
+
output = torch.matmul(attn, v)
|
| 112 |
+
|
| 113 |
+
output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
|
| 114 |
+
return self.wo(output)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TransformerBlock(nn.Module):
|
| 118 |
+
"""Transformer block with pre-norm"""
|
| 119 |
+
def __init__(self, dim: int, n_heads: int, n_kv_heads: int, hidden_dim: int, max_seq_len: int = 8192):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.attention_norm = RMSNorm(dim)
|
| 122 |
+
self.attention = GroupedQueryAttention(dim, n_heads, n_kv_heads, max_seq_len)
|
| 123 |
+
self.ffn_norm = RMSNorm(dim)
|
| 124 |
+
self.ffn = SwiGLU(dim, hidden_dim)
|
| 125 |
+
|
| 126 |
+
def forward(self, x):
|
| 127 |
+
x = x + self.attention(self.attention_norm(x))
|
| 128 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 129 |
+
return x
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class EkalavyaDeepSeekClass(nn.Module):
|
| 133 |
+
"""
|
| 134 |
+
Ekalavya DeepSeek-Class Model
|
| 135 |
+
|
| 136 |
+
Architecture:
|
| 137 |
+
- RMSNorm for stable training
|
| 138 |
+
- Rotary Position Embeddings (RoPE)
|
| 139 |
+
- SwiGLU activation
|
| 140 |
+
- Grouped Query Attention (GQA)
|
| 141 |
+
- Up to 61.73B parameters
|
| 142 |
+
"""
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
vocab_size: int = 32000,
|
| 146 |
+
dim: int = 1024,
|
| 147 |
+
n_layers: int = 24,
|
| 148 |
+
n_heads: int = 16,
|
| 149 |
+
n_kv_heads: int = 4,
|
| 150 |
+
hidden_dim: int = 4096,
|
| 151 |
+
max_seq_len: int = 8192
|
| 152 |
+
):
|
| 153 |
+
super().__init__()
|
| 154 |
+
|
| 155 |
+
self.vocab_size = vocab_size
|
| 156 |
+
self.dim = dim
|
| 157 |
+
self.n_layers = n_layers
|
| 158 |
+
self.max_seq_len = max_seq_len
|
| 159 |
+
|
| 160 |
+
self.tok_embeddings = nn.Embedding(vocab_size, dim)
|
| 161 |
+
|
| 162 |
+
self.layers = nn.ModuleList([
|
| 163 |
+
TransformerBlock(dim, n_heads, n_kv_heads, hidden_dim, max_seq_len)
|
| 164 |
+
for _ in range(n_layers)
|
| 165 |
+
])
|
| 166 |
+
|
| 167 |
+
self.norm = RMSNorm(dim)
|
| 168 |
+
self.output = nn.Linear(dim, vocab_size, bias=False)
|
| 169 |
+
|
| 170 |
+
self.output.weight = self.tok_embeddings.weight
|
| 171 |
+
self._init_weights()
|
| 172 |
+
|
| 173 |
+
def _init_weights(self):
|
| 174 |
+
"""Initialize weights"""
|
| 175 |
+
for module in self.modules():
|
| 176 |
+
if isinstance(module, nn.Linear):
|
| 177 |
+
if module.weight.dim() > 1:
|
| 178 |
+
nn.init.xavier_uniform_(module.weight)
|
| 179 |
+
if module.bias is not None:
|
| 180 |
+
nn.init.zeros_(module.bias)
|
| 181 |
+
elif isinstance(module, nn.Embedding):
|
| 182 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 183 |
+
|
| 184 |
+
def forward(self, idx, targets=None):
|
| 185 |
+
"""Forward pass"""
|
| 186 |
+
bsz, seq_len = idx.shape
|
| 187 |
+
|
| 188 |
+
h = self.tok_embeddings(idx)
|
| 189 |
+
|
| 190 |
+
for layer in self.layers:
|
| 191 |
+
h = layer(h)
|
| 192 |
+
|
| 193 |
+
h = self.norm(h)
|
| 194 |
+
logits = self.output(h)
|
| 195 |
+
|
| 196 |
+
loss = None
|
| 197 |
+
if targets is not None:
|
| 198 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 199 |
+
|
| 200 |
+
return logits, loss
|
| 201 |
+
|
| 202 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, top_p=None):
|
| 203 |
+
"""Generate text"""
|
| 204 |
+
for _ in range(max_new_tokens):
|
| 205 |
+
idx_cond = idx if idx.size(1) <= self.max_seq_len else idx[:, -self.max_seq_len:]
|
| 206 |
+
|
| 207 |
+
logits, _ = self(idx_cond)
|
| 208 |
+
logits = logits[:, -1, :] / temperature
|
| 209 |
+
|
| 210 |
+
if top_k is not None:
|
| 211 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 212 |
+
logits[logits < v[:, [-1]]] = float('-inf')
|
| 213 |
+
|
| 214 |
+
if top_p is not None:
|
| 215 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 216 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 217 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 218 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 219 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 220 |
+
indices_to_remove = sorted_indices_to_remove.scatter(
|
| 221 |
+
1, sorted_indices, sorted_indices_to_remove
|
| 222 |
+
)
|
| 223 |
+
logits[indices_to_remove] = float('-inf')
|
| 224 |
+
|
| 225 |
+
probs = F.softmax(logits, dim=-1)
|
| 226 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 227 |
+
idx = torch.cat([idx, idx_next], dim=1)
|
| 228 |
+
|
| 229 |
+
return idx
|
| 230 |
+
|
| 231 |
+
def count_parameters(self):
|
| 232 |
+
"""Count total parameters"""
|
| 233 |
+
return sum(p.numel() for p in self.parameters())
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# Model Configurations
|
| 237 |
+
CONFIGS = {
|
| 238 |
+
'mini': {
|
| 239 |
+
'vocab_size': 32000,
|
| 240 |
+
'dim': 512,
|
| 241 |
+
'n_layers': 8,
|
| 242 |
+
'n_heads': 8,
|
| 243 |
+
'n_kv_heads': 4,
|
| 244 |
+
'hidden_dim': 2048,
|
| 245 |
+
'max_seq_len': 4096,
|
| 246 |
+
},
|
| 247 |
+
'pro': {
|
| 248 |
+
'vocab_size': 32000,
|
| 249 |
+
'dim': 1024,
|
| 250 |
+
'n_layers': 16,
|
| 251 |
+
'n_heads': 16,
|
| 252 |
+
'n_kv_heads': 4,
|
| 253 |
+
'hidden_dim': 4096,
|
| 254 |
+
'max_seq_len': 8192,
|
| 255 |
+
},
|
| 256 |
+
'mega': {
|
| 257 |
+
'vocab_size': 32000,
|
| 258 |
+
'dim': 2048,
|
| 259 |
+
'n_layers': 32,
|
| 260 |
+
'n_heads': 32,
|
| 261 |
+
'n_kv_heads': 8,
|
| 262 |
+
'hidden_dim': 8192,
|
| 263 |
+
'max_seq_len': 8192,
|
| 264 |
+
},
|
| 265 |
+
'ultra': {
|
| 266 |
+
'vocab_size': 32000,
|
| 267 |
+
'dim': 4096,
|
| 268 |
+
'n_layers': 48,
|
| 269 |
+
'n_heads': 64,
|
| 270 |
+
'n_kv_heads': 8,
|
| 271 |
+
'hidden_dim': 16384,
|
| 272 |
+
'max_seq_len': 8192,
|
| 273 |
+
},
|
| 274 |
+
'flagship': {
|
| 275 |
+
'vocab_size': 32000,
|
| 276 |
+
'dim': 8192,
|
| 277 |
+
'n_layers': 64,
|
| 278 |
+
'n_heads': 128,
|
| 279 |
+
'n_kv_heads': 16,
|
| 280 |
+
'hidden_dim': 32768,
|
| 281 |
+
'max_seq_len': 8192,
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def create_model(config_name='pro', **kwargs):
|
| 287 |
+
"""Create model from config"""
|
| 288 |
+
if config_name not in CONFIGS:
|
| 289 |
+
raise ValueError(f"Unknown config: {config_name}")
|
| 290 |
+
|
| 291 |
+
config = CONFIGS[config_name].copy()
|
| 292 |
+
config.update(kwargs)
|
| 293 |
+
return EkalavyaDeepSeekClass(**config)
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.100.0
|
| 2 |
+
uvicorn>=0.23.0
|
| 3 |
+
torch>=2.0.0
|
| 4 |
+
pydantic>=2.0.0
|
| 5 |
+
python-multipart>=0.0.6
|
| 6 |
+
huggingface-hub>=0.16.0
|