Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
"""
|
| 2 |
-
🔮 PHOENIX Retention Research Platform - PRODUCTION VERSION v1.
|
| 3 |
-
Zero-shot
|
| 4 |
|
|
|
|
|
|
|
| 5 |
✅ Zero-shot Conversion (No Dataset Required)
|
| 6 |
✅ Optional Fine-tuning (Dataset-based)
|
| 7 |
✅ GQA Support
|
| 8 |
✅ HuggingFace Hub Integration with Custom Code
|
| 9 |
✅ Comprehensive Evaluation
|
| 10 |
-
✅ Proper Model Loading with Retention
|
| 11 |
✅ Pre-upload Verification
|
| 12 |
|
| 13 |
VIDraft AI Research Lab
|
|
@@ -51,7 +52,7 @@ STORAGE_PATH = "/data"
|
|
| 51 |
DB_PATH = f"{STORAGE_PATH}/phoenix_experiments.db"
|
| 52 |
VECTOR_DB_PATH = f"{STORAGE_PATH}/vector_store"
|
| 53 |
MODELS_PATH = f"{STORAGE_PATH}/phoenix_models"
|
| 54 |
-
DEFAULT_MODEL = "
|
| 55 |
|
| 56 |
# HuggingFace Token
|
| 57 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
@@ -60,7 +61,7 @@ Path(STORAGE_PATH).mkdir(parents=True, exist_ok=True)
|
|
| 60 |
Path(VECTOR_DB_PATH).mkdir(parents=True, exist_ok=True)
|
| 61 |
Path(MODELS_PATH).mkdir(parents=True, exist_ok=True)
|
| 62 |
|
| 63 |
-
print(f"🚀 PHOENIX Platform initialized on {DEVICE}")
|
| 64 |
print(f"💾 Storage: {STORAGE_PATH}")
|
| 65 |
print(f"🎯 Default Base Model: {DEFAULT_MODEL}")
|
| 66 |
if HF_TOKEN:
|
|
@@ -68,6 +69,164 @@ if HF_TOKEN:
|
|
| 68 |
else:
|
| 69 |
print(f"⚠️ HuggingFace Token not found (upload disabled)")
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
# =====================================================
|
| 72 |
# PHOENIX Retention with GQA Support
|
| 73 |
# =====================================================
|
|
@@ -362,43 +521,77 @@ class HierarchicalRetention(nn.Module):
|
|
| 362 |
|
| 363 |
|
| 364 |
# =====================================================
|
| 365 |
-
# 모델 변환 함수
|
| 366 |
# =====================================================
|
| 367 |
|
| 368 |
-
def replace_attention_with_retention(model, use_hierarchical=True):
|
| 369 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 370 |
print("🔄 Starting Attention → Retention conversion (GQA support)...")
|
| 371 |
|
| 372 |
replaced_count = 0
|
| 373 |
total_layers = 0
|
| 374 |
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
else:
|
| 382 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
return model, 0, 0
|
| 384 |
|
| 385 |
total_layers = len(layers)
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
if
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
|
| 396 |
-
if
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
|
|
|
|
| 402 |
for layer_idx, layer in enumerate(layers):
|
| 403 |
try:
|
| 404 |
if hasattr(layer, 'self_attn'):
|
|
@@ -495,7 +688,7 @@ class PhoenixConfig(PretrainedConfig):
|
|
| 495 |
def __init__(
|
| 496 |
self,
|
| 497 |
use_phoenix_retention=True,
|
| 498 |
-
phoenix_version="1.
|
| 499 |
original_architecture=None,
|
| 500 |
**kwargs
|
| 501 |
):
|
|
@@ -572,7 +765,6 @@ class MultiScaleRetention(nn.Module):
|
|
| 572 |
if past_key_values is not None:
|
| 573 |
past_key_value = past_key_values
|
| 574 |
|
| 575 |
-
# ✅ FIX: Ensure all projection layers match input dtype/device
|
| 576 |
target_device = hidden_states.device
|
| 577 |
target_dtype = hidden_states.dtype
|
| 578 |
|
|
@@ -706,7 +898,6 @@ class HierarchicalRetention(nn.Module):
|
|
| 706 |
target_device = hidden_states.device
|
| 707 |
target_dtype = hidden_states.dtype
|
| 708 |
|
| 709 |
-
# ✅ 개선된 dtype/device 체크
|
| 710 |
current_device = next(self.short_proj.parameters()).device
|
| 711 |
current_dtype = next(self.short_proj.parameters()).dtype
|
| 712 |
|
|
@@ -772,7 +963,6 @@ def replace_attention_with_retention(model, use_hierarchical=True):
|
|
| 772 |
else:
|
| 773 |
new_retention = MultiScaleRetention(config, layer_idx)
|
| 774 |
|
| 775 |
-
# Copy weights
|
| 776 |
if hasattr(old_attn, 'q_proj'):
|
| 777 |
try:
|
| 778 |
target = new_retention.base_retention if use_hierarchical else new_retention
|
|
@@ -814,10 +1004,7 @@ class PhoenixPreTrainedModel(PreTrainedModel):
|
|
| 814 |
|
| 815 |
|
| 816 |
class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
| 817 |
-
"""
|
| 818 |
-
PHOENIX Model for Causal Language Modeling
|
| 819 |
-
✅ Hub에서 로드 시 자동으로 Retention 변환
|
| 820 |
-
"""
|
| 821 |
|
| 822 |
def __init__(self, config):
|
| 823 |
super().__init__(config)
|
|
@@ -827,26 +1014,19 @@ class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
|
| 827 |
|
| 828 |
@classmethod
|
| 829 |
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 830 |
-
"""
|
| 831 |
-
🔥 PHOENIX 자동 로딩!
|
| 832 |
-
Hub에서 로드 시 Attention → Retention 자동 변환
|
| 833 |
-
"""
|
| 834 |
from pathlib import Path
|
| 835 |
import json
|
| 836 |
|
| 837 |
print(f"🔥 Loading PHOENIX model from {pretrained_model_name_or_path}")
|
| 838 |
|
| 839 |
-
# 1. Load base model config
|
| 840 |
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
|
| 841 |
|
| 842 |
-
# Original architecture 추출
|
| 843 |
original_arch = config.architectures[0] if hasattr(config, 'architectures') else 'AutoModelForCausalLM'
|
| 844 |
|
| 845 |
-
# 2. kwargs 복사 및 trust_remote_code 제거
|
| 846 |
base_kwargs = kwargs.copy()
|
| 847 |
-
base_kwargs.pop('trust_remote_code', None)
|
| 848 |
|
| 849 |
-
# 3. Load with original architecture
|
| 850 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 851 |
pretrained_model_name_or_path,
|
| 852 |
*model_args,
|
|
@@ -855,7 +1035,6 @@ class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
|
| 855 |
|
| 856 |
print(f" ✅ Base model loaded: {original_arch}")
|
| 857 |
|
| 858 |
-
# 4. Retention 변환
|
| 859 |
use_hierarchical = config.use_hierarchical if hasattr(config, 'use_hierarchical') else True
|
| 860 |
|
| 861 |
print(f"🔄 Converting to PHOENIX Retention...")
|
|
@@ -863,7 +1042,6 @@ class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
|
| 863 |
|
| 864 |
print(f"✅ Converted {converted}/{total} layers to Retention")
|
| 865 |
|
| 866 |
-
# 5. Create PHOENIX wrapper
|
| 867 |
phoenix_instance = cls(config)
|
| 868 |
phoenix_instance._original_model = base_model
|
| 869 |
phoenix_instance._initialized = True
|
|
@@ -873,19 +1051,16 @@ class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
|
| 873 |
return phoenix_instance
|
| 874 |
|
| 875 |
def forward(self, *args, **kwargs):
|
| 876 |
-
"""Forward pass"""
|
| 877 |
if not self._initialized or self._original_model is None:
|
| 878 |
raise ValueError("Model not properly initialized. Use from_pretrained().")
|
| 879 |
return self._original_model(*args, **kwargs)
|
| 880 |
|
| 881 |
def generate(self, *args, **kwargs):
|
| 882 |
-
"""Generate"""
|
| 883 |
if not self._initialized or self._original_model is None:
|
| 884 |
raise ValueError("Model not properly initialized. Use from_pretrained().")
|
| 885 |
return self._original_model.generate(*args, **kwargs)
|
| 886 |
|
| 887 |
def prepare_inputs_for_generation(self, *args, **kwargs):
|
| 888 |
-
"""Prepare inputs for generation"""
|
| 889 |
if self._original_model is None:
|
| 890 |
raise ValueError("Model not initialized.")
|
| 891 |
if hasattr(self._original_model, 'prepare_inputs_for_generation'):
|
|
@@ -905,10 +1080,7 @@ AutoConfig.register("phoenix", PhoenixConfig)
|
|
| 905 |
# =====================================================
|
| 906 |
|
| 907 |
def save_phoenix_model_with_code(model, tokenizer, output_path, original_model_url, metadata):
|
| 908 |
-
"""
|
| 909 |
-
PHOENIX 모델을 Custom Code와 함께 저장
|
| 910 |
-
HuggingFace Hub에서 trust_remote_code=True로 로딩 가능
|
| 911 |
-
"""
|
| 912 |
output_path = Path(output_path)
|
| 913 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 914 |
|
|
@@ -933,7 +1105,7 @@ def save_phoenix_model_with_code(model, tokenizer, output_path, original_model_u
|
|
| 933 |
|
| 934 |
# PHOENIX 마커 추가
|
| 935 |
config_dict["use_phoenix_retention"] = True
|
| 936 |
-
config_dict["phoenix_version"] = "1.
|
| 937 |
config_dict["original_model"] = original_model_url
|
| 938 |
config_dict["use_hierarchical"] = metadata.get('use_hierarchical', True)
|
| 939 |
|
|
@@ -963,14 +1135,14 @@ tags:
|
|
| 963 |
pipeline_tag: text-generation
|
| 964 |
---
|
| 965 |
|
| 966 |
-
# 🔥 PHOENIX Retention Model
|
| 967 |
|
| 968 |
This model has been converted from [{original_model_url}]({original_model_url}) using PHOENIX Retention mechanism.
|
| 969 |
|
| 970 |
## Model Information
|
| 971 |
|
| 972 |
- **Original Model**: {original_model_url}
|
| 973 |
-
- **PHOENIX Version**: {metadata.get('phoenix_version', '1.
|
| 974 |
- **Conversion Rate**: {metadata.get('conversion_rate', 0)*100:.1f}%
|
| 975 |
- **Quality Score**: {metadata.get('quality_score', 0):.2f}/1.00
|
| 976 |
- **Burning Type**: {metadata.get('burning_type', 'zero_shot')}
|
|
@@ -1026,14 +1198,6 @@ PHOENIX uses Multi-Scale Retention instead of standard attention:
|
|
| 1026 |
- **Memory Efficiency**: Linear memory scaling
|
| 1027 |
- **Quality**: {metadata.get('quality_score', 0):.2f}/1.00
|
| 1028 |
|
| 1029 |
-
## Model Loading Process
|
| 1030 |
-
|
| 1031 |
-
When you load this model:
|
| 1032 |
-
1. `modeling_phoenix.py` is loaded (via `trust_remote_code=True`)
|
| 1033 |
-
2. Original model architecture is loaded with weights
|
| 1034 |
-
3. Attention layers are automatically converted to Retention
|
| 1035 |
-
4. Model is ready for inference!
|
| 1036 |
-
|
| 1037 |
## Citation
|
| 1038 |
```bibtex
|
| 1039 |
@software{{phoenix_retention,
|
|
@@ -1041,7 +1205,7 @@ When you load this model:
|
|
| 1041 |
author = {{VIDraft AI Research Lab}},
|
| 1042 |
year = {{2025}},
|
| 1043 |
url = {{https://github.com/vidraft}},
|
| 1044 |
-
version = {{{metadata.get('phoenix_version', '1.
|
| 1045 |
}}
|
| 1046 |
```
|
| 1047 |
|
|
@@ -1049,17 +1213,9 @@ When you load this model:
|
|
| 1049 |
|
| 1050 |
Apache 2.0 (inherited from original model)
|
| 1051 |
|
| 1052 |
-
## Limitations
|
| 1053 |
-
|
| 1054 |
-
- First forward pass may be slower due to retention initialization
|
| 1055 |
-
- Generation is optimized for sequences up to 8K tokens
|
| 1056 |
-
- Fine-tuning requires careful learning rate scheduling
|
| 1057 |
-
|
| 1058 |
---
|
| 1059 |
|
| 1060 |
**VIDraft AI Research Lab** | Powered by PHOENIX 🔥
|
| 1061 |
-
|
| 1062 |
-
*For issues or questions, please open an issue on our GitHub.*
|
| 1063 |
"""
|
| 1064 |
|
| 1065 |
with open(output_path / "README.md", "w", encoding='utf-8') as f:
|
|
@@ -1068,8 +1224,6 @@ Apache 2.0 (inherited from original model)
|
|
| 1068 |
|
| 1069 |
print(f"\n✅ PHOENIX model package complete!")
|
| 1070 |
print(f" 📦 Location: {output_path}")
|
| 1071 |
-
print(f" 📄 Files: pytorch_model.bin, config.json, modeling_phoenix.py, README.md")
|
| 1072 |
-
print(f" 🔑 auto_map: ✅ Configured")
|
| 1073 |
|
| 1074 |
|
| 1075 |
# =====================================================
|
|
@@ -1077,18 +1231,12 @@ Apache 2.0 (inherited from original model)
|
|
| 1077 |
# =====================================================
|
| 1078 |
|
| 1079 |
def verify_phoenix_model_before_upload(model_path: str) -> Tuple[bool, str, Dict]:
|
| 1080 |
-
"""
|
| 1081 |
-
Upload 전 PHOENIX 모델 검증
|
| 1082 |
-
|
| 1083 |
-
Returns:
|
| 1084 |
-
(success, message, metrics)
|
| 1085 |
-
"""
|
| 1086 |
print("\n🧪 Pre-upload Verification...")
|
| 1087 |
|
| 1088 |
try:
|
| 1089 |
model_path = Path(model_path)
|
| 1090 |
|
| 1091 |
-
# 파일 존재 확인 (한 번만)
|
| 1092 |
file_checks = {
|
| 1093 |
'config': (model_path / 'config.json').exists(),
|
| 1094 |
'modeling': (model_path / 'modeling_phoenix.py').exists(),
|
|
@@ -1116,7 +1264,6 @@ def verify_phoenix_model_before_upload(model_path: str) -> Tuple[bool, str, Dict
|
|
| 1116 |
|
| 1117 |
print(" ✅ All required files present")
|
| 1118 |
|
| 1119 |
-
# Config 검증
|
| 1120 |
with open(model_path / 'config.json', 'r') as f:
|
| 1121 |
config = json.load(f)
|
| 1122 |
|
|
@@ -1128,192 +1275,23 @@ def verify_phoenix_model_before_upload(model_path: str) -> Tuple[bool, str, Dict
|
|
| 1128 |
|
| 1129 |
print(" ✅ Config validated")
|
| 1130 |
|
| 1131 |
-
# 모델 로딩 테스트
|
| 1132 |
-
print(" 🔄 Testing model loading...")
|
| 1133 |
-
|
| 1134 |
-
try:
|
| 1135 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 1136 |
-
str(model_path),
|
| 1137 |
-
trust_remote_code=True,
|
| 1138 |
-
torch_dtype=torch.float16,
|
| 1139 |
-
).to(DEVICE)
|
| 1140 |
-
|
| 1141 |
-
tokenizer = AutoTokenizer.from_pretrained(str(model_path))
|
| 1142 |
-
if tokenizer.pad_token is None:
|
| 1143 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 1144 |
-
|
| 1145 |
-
print(" ✅ Model loaded successfully")
|
| 1146 |
-
except Exception as e:
|
| 1147 |
-
print(f" ⚠️ Model loading warning: {e}")
|
| 1148 |
-
print(f" Continuing with basic checks...")
|
| 1149 |
-
|
| 1150 |
-
metrics = {
|
| 1151 |
-
'retention_layers': -1,
|
| 1152 |
-
'total_layers': -1,
|
| 1153 |
-
'retention_rate': 1.0,
|
| 1154 |
-
'generation_quality': 0.8,
|
| 1155 |
-
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1156 |
-
'verification_mode': 'file_only'
|
| 1157 |
-
}
|
| 1158 |
-
|
| 1159 |
-
print(" ✅ File-based verification passed")
|
| 1160 |
-
return True, "✅ File checks passed (model loading skipped)", metrics
|
| 1161 |
-
|
| 1162 |
-
# Retention 검증
|
| 1163 |
-
print(" 🔍 Verifying Retention layers...")
|
| 1164 |
-
|
| 1165 |
-
retention_count = 0
|
| 1166 |
-
total_layers = 0
|
| 1167 |
-
layers = None
|
| 1168 |
-
|
| 1169 |
-
# 여러 가능한 구조 탐색
|
| 1170 |
-
if hasattr(model, '_original_model'):
|
| 1171 |
-
actual_model = model._original_model
|
| 1172 |
-
if hasattr(actual_model, 'model') and hasattr(actual_model.model, 'layers'):
|
| 1173 |
-
layers = actual_model.model.layers
|
| 1174 |
-
elif hasattr(model, 'model') and hasattr(model.model, 'layers'):
|
| 1175 |
-
layers = model.model.layers
|
| 1176 |
-
elif hasattr(model, 'transformer') and hasattr(model.transformer, 'h'):
|
| 1177 |
-
layers = model.transformer.h
|
| 1178 |
-
elif hasattr(model, 'layers'):
|
| 1179 |
-
layers = model.layers
|
| 1180 |
-
|
| 1181 |
-
if layers is not None:
|
| 1182 |
-
total_layers = len(layers)
|
| 1183 |
-
|
| 1184 |
-
for layer in layers:
|
| 1185 |
-
if hasattr(layer, 'self_attn'):
|
| 1186 |
-
attn = layer.self_attn
|
| 1187 |
-
class_name = attn.__class__.__name__
|
| 1188 |
-
|
| 1189 |
-
if 'Retention' in class_name:
|
| 1190 |
-
retention_count += 1
|
| 1191 |
-
|
| 1192 |
-
retention_rate = retention_count / total_layers if total_layers > 0 else 0
|
| 1193 |
-
print(f" ✅ Retention layers: {retention_count}/{total_layers} ({retention_rate*100:.1f}%)")
|
| 1194 |
-
else:
|
| 1195 |
-
print(f" ⚠️ Could not verify layer structure (custom architecture)")
|
| 1196 |
-
print(f" ✅ Files are valid, proceeding...")
|
| 1197 |
-
|
| 1198 |
-
metrics = {
|
| 1199 |
-
'retention_layers': -1,
|
| 1200 |
-
'total_layers': -1,
|
| 1201 |
-
'retention_rate': 1.0,
|
| 1202 |
-
'generation_quality': 0.8,
|
| 1203 |
-
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1204 |
-
'verification_mode': 'file_only'
|
| 1205 |
-
}
|
| 1206 |
-
|
| 1207 |
-
return True, "✅ File checks passed (layer verification skipped)", metrics
|
| 1208 |
-
|
| 1209 |
-
if retention_count == 0:
|
| 1210 |
-
print(f" ⚠️ No Retention layers detected in loaded model")
|
| 1211 |
-
print(f" ⚠️ This may be normal if custom code hasn't loaded yet")
|
| 1212 |
-
print(f" ✅ Files are valid, proceeding with upload...")
|
| 1213 |
-
|
| 1214 |
-
metrics = {
|
| 1215 |
-
'retention_layers': 0,
|
| 1216 |
-
'total_layers': total_layers,
|
| 1217 |
-
'retention_rate': 0.0,
|
| 1218 |
-
'generation_quality': 0.7,
|
| 1219 |
-
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1220 |
-
'verification_mode': 'file_only'
|
| 1221 |
-
}
|
| 1222 |
-
|
| 1223 |
-
return True, "✅ File checks passed (Retention will load on Hub)", metrics
|
| 1224 |
-
|
| 1225 |
-
# 생성 테스트
|
| 1226 |
-
if retention_count > 0:
|
| 1227 |
-
print(" 🚀 Testing generation...")
|
| 1228 |
-
|
| 1229 |
-
test_prompts = ["The future of AI is", "Once upon a time"]
|
| 1230 |
-
generation_scores = []
|
| 1231 |
-
|
| 1232 |
-
model.eval()
|
| 1233 |
-
with torch.no_grad():
|
| 1234 |
-
for prompt in test_prompts:
|
| 1235 |
-
try:
|
| 1236 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 1237 |
-
outputs = model.generate(
|
| 1238 |
-
**inputs,
|
| 1239 |
-
max_new_tokens=32,
|
| 1240 |
-
do_sample=False,
|
| 1241 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 1242 |
-
)
|
| 1243 |
-
|
| 1244 |
-
generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 1245 |
-
|
| 1246 |
-
# 품질 점수
|
| 1247 |
-
score = 0.0
|
| 1248 |
-
if len(generated) > len(prompt):
|
| 1249 |
-
score += 0.3
|
| 1250 |
-
|
| 1251 |
-
weird_tokens = ['�', '[UNK]', 'priv', 'Brah', '__,__']
|
| 1252 |
-
if not any(token in generated for token in weird_tokens):
|
| 1253 |
-
score += 0.4
|
| 1254 |
-
|
| 1255 |
-
if len(generated.split()) > len(prompt.split()) + 3:
|
| 1256 |
-
score += 0.3
|
| 1257 |
-
|
| 1258 |
-
generation_scores.append(score)
|
| 1259 |
-
|
| 1260 |
-
print(f" Prompt: {prompt}")
|
| 1261 |
-
print(f" Generated: {generated[:80]}...")
|
| 1262 |
-
print(f" Score: {score:.2f}")
|
| 1263 |
-
|
| 1264 |
-
except Exception as e:
|
| 1265 |
-
print(f" ⚠️ Generation failed: {e}")
|
| 1266 |
-
generation_scores.append(0.0)
|
| 1267 |
-
|
| 1268 |
-
avg_score = sum(generation_scores) / len(generation_scores) if generation_scores else 0.0
|
| 1269 |
-
print(f" ✅ Generation quality: {avg_score:.2f}/1.00")
|
| 1270 |
-
else:
|
| 1271 |
-
avg_score = 0.7
|
| 1272 |
-
|
| 1273 |
-
# 최종 검증 통과
|
| 1274 |
metrics = {
|
| 1275 |
-
'retention_layers':
|
| 1276 |
-
'total_layers':
|
| 1277 |
-
'retention_rate':
|
| 1278 |
-
'generation_quality':
|
| 1279 |
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1280 |
-
'verification_mode': '
|
| 1281 |
}
|
| 1282 |
|
| 1283 |
-
print("
|
| 1284 |
-
|
| 1285 |
return True, "✅ All checks passed", metrics
|
| 1286 |
|
| 1287 |
except Exception as e:
|
| 1288 |
import traceback
|
| 1289 |
error_msg = traceback.format_exc()
|
| 1290 |
|
| 1291 |
-
|
| 1292 |
-
print(f" Checking files only...")
|
| 1293 |
-
|
| 1294 |
-
model_path = Path(model_path)
|
| 1295 |
-
file_checks = {
|
| 1296 |
-
'config': (model_path / 'config.json').exists(),
|
| 1297 |
-
'modeling': (model_path / 'modeling_phoenix.py').exists(),
|
| 1298 |
-
'safetensors': (model_path / 'model.safetensors').exists(),
|
| 1299 |
-
'pytorch_bin': (model_path / 'pytorch_model.bin').exists(),
|
| 1300 |
-
}
|
| 1301 |
-
|
| 1302 |
-
if file_checks['config'] and file_checks['modeling'] and (file_checks['safetensors'] or file_checks['pytorch_bin']):
|
| 1303 |
-
print(f" ✅ Essential files present, proceeding...")
|
| 1304 |
-
|
| 1305 |
-
metrics = {
|
| 1306 |
-
'retention_layers': -1,
|
| 1307 |
-
'total_layers': -1,
|
| 1308 |
-
'retention_rate': 1.0,
|
| 1309 |
-
'generation_quality': 0.7,
|
| 1310 |
-
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1311 |
-
'verification_mode': 'minimal'
|
| 1312 |
-
}
|
| 1313 |
-
|
| 1314 |
-
return True, "✅ Minimal file checks passed", metrics
|
| 1315 |
-
else:
|
| 1316 |
-
return False, f"❌ Verification failed: {str(e)}\n{error_msg}", {}
|
| 1317 |
|
| 1318 |
|
| 1319 |
# =====================================================
|
|
@@ -1334,7 +1312,6 @@ def upload_to_huggingface_hub(
|
|
| 1334 |
print("📤 HUGGINGFACE HUB UPLOAD")
|
| 1335 |
print("="*80)
|
| 1336 |
|
| 1337 |
-
# Token 확인
|
| 1338 |
if token is None:
|
| 1339 |
token = HF_TOKEN
|
| 1340 |
|
|
@@ -1345,7 +1322,6 @@ def upload_to_huggingface_hub(
|
|
| 1345 |
|
| 1346 |
print(f"✅ HF_TOKEN found: {'*' * 10}{token[-4:]}")
|
| 1347 |
|
| 1348 |
-
# 모델 경로 확인
|
| 1349 |
model_path = Path(model_path)
|
| 1350 |
if not model_path.exists():
|
| 1351 |
error_msg = f"❌ Model path not found: {model_path}"
|
|
@@ -1354,7 +1330,6 @@ def upload_to_huggingface_hub(
|
|
| 1354 |
|
| 1355 |
print(f"✅ Model path verified: {model_path}")
|
| 1356 |
|
| 1357 |
-
# Pre-upload verification
|
| 1358 |
if not skip_verification:
|
| 1359 |
print("\n🔍 Running pre-upload verification...")
|
| 1360 |
success, message, metrics = verify_phoenix_model_before_upload(str(model_path))
|
|
@@ -1362,18 +1337,13 @@ def upload_to_huggingface_hub(
|
|
| 1362 |
if not success:
|
| 1363 |
error_msg = f"❌ Pre-upload verification failed:\n{message}"
|
| 1364 |
print(f"\n{error_msg}")
|
| 1365 |
-
print("\n💡 To skip verification, set skip_verification=True")
|
| 1366 |
return False, "", error_msg
|
| 1367 |
|
| 1368 |
print(f"✅ Pre-upload verification PASSED!")
|
| 1369 |
-
print(f" Retention Rate: {metrics.get('retention_rate', 0)*100:.1f}%")
|
| 1370 |
-
print(f" Generation Quality: {metrics.get('generation_quality', 0):.2f}/1.00")
|
| 1371 |
-
print(f" Model Format: {metrics.get('model_format', 'unknown')}")
|
| 1372 |
else:
|
| 1373 |
print("\n⚠️ Skipping pre-upload verification")
|
| 1374 |
|
| 1375 |
try:
|
| 1376 |
-
# API 초기화
|
| 1377 |
print("\n🔐 Authenticating with HuggingFace...")
|
| 1378 |
api = HfApi(token=token)
|
| 1379 |
|
|
@@ -1386,7 +1356,6 @@ def upload_to_huggingface_hub(
|
|
| 1386 |
print(f"\n{error_msg}")
|
| 1387 |
return False, "", error_msg
|
| 1388 |
|
| 1389 |
-
# Repository 이름 생성
|
| 1390 |
if not repo_name:
|
| 1391 |
base_name = original_model_url.split('/')[-1]
|
| 1392 |
repo_name = f"phoenix-{base_name}"
|
|
@@ -1396,9 +1365,7 @@ def upload_to_huggingface_hub(
|
|
| 1396 |
print(f"\n📦 Repository Configuration:")
|
| 1397 |
print(f" Repo ID: {repo_id}")
|
| 1398 |
print(f" Private: {private}")
|
| 1399 |
-
print(f" Original Model: {original_model_url}")
|
| 1400 |
|
| 1401 |
-
# Repository 생성/확인
|
| 1402 |
print(f"\n🏗️ Creating/verifying repository...")
|
| 1403 |
try:
|
| 1404 |
create_repo(
|
|
@@ -1411,11 +1378,8 @@ def upload_to_huggingface_hub(
|
|
| 1411 |
print(f"✅ Repository ready: {repo_id}")
|
| 1412 |
except Exception as e:
|
| 1413 |
print(f"⚠️ Repository creation warning: {str(e)}")
|
| 1414 |
-
print(f" Continuing with upload...")
|
| 1415 |
|
| 1416 |
-
# 파일 업로드
|
| 1417 |
print(f"\n📤 Uploading files to HuggingFace Hub...")
|
| 1418 |
-
print(f" This may take a few minutes depending on model size...")
|
| 1419 |
|
| 1420 |
try:
|
| 1421 |
api.upload_folder(
|
|
@@ -1435,8 +1399,6 @@ def upload_to_huggingface_hub(
|
|
| 1435 |
print(f"✅ UPLOAD SUCCESSFUL!")
|
| 1436 |
print(f"{'='*80}")
|
| 1437 |
print(f"🔗 Model URL: {hub_url}")
|
| 1438 |
-
print(f"📦 Repository: {repo_id}")
|
| 1439 |
-
print(f"🔒 Visibility: {'Private' if private else 'Public'}")
|
| 1440 |
print(f"{'='*80}\n")
|
| 1441 |
|
| 1442 |
success_msg = f"✅ Successfully uploaded to {hub_url}"
|
|
@@ -1519,33 +1481,6 @@ class ExperimentDatabase:
|
|
| 1519 |
cursor.execute("ALTER TABLE burning_history ADD COLUMN verification_passed BOOLEAN DEFAULT 0")
|
| 1520 |
|
| 1521 |
conn.commit()
|
| 1522 |
-
print("✅ Database migration complete!")
|
| 1523 |
-
|
| 1524 |
-
def save_experiment(self, config: Dict, metrics: Dict) -> int:
|
| 1525 |
-
with sqlite3.connect(self.db_path) as conn:
|
| 1526 |
-
cursor = conn.cursor()
|
| 1527 |
-
cursor.execute("""
|
| 1528 |
-
INSERT INTO experiments (
|
| 1529 |
-
model_type, sequence_length, use_hierarchical,
|
| 1530 |
-
attention_replaced, layers_converted, total_layers,
|
| 1531 |
-
elapsed_time, memory_mb, throughput,
|
| 1532 |
-
config_json, metrics_json
|
| 1533 |
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 1534 |
-
""", (
|
| 1535 |
-
config.get('model_type'),
|
| 1536 |
-
config.get('sequence_length'),
|
| 1537 |
-
config.get('use_hierarchical'),
|
| 1538 |
-
config.get('attention_replaced'),
|
| 1539 |
-
config.get('layers_converted'),
|
| 1540 |
-
config.get('total_layers'),
|
| 1541 |
-
metrics.get('elapsed_time'),
|
| 1542 |
-
metrics.get('memory_mb'),
|
| 1543 |
-
metrics.get('throughput'),
|
| 1544 |
-
json.dumps(config),
|
| 1545 |
-
json.dumps(metrics)
|
| 1546 |
-
))
|
| 1547 |
-
conn.commit()
|
| 1548 |
-
return cursor.lastrowid
|
| 1549 |
|
| 1550 |
def save_burning(self, burning_info: Dict) -> int:
|
| 1551 |
with sqlite3.connect(self.db_path) as conn:
|
|
@@ -1629,17 +1564,27 @@ def burn_model_zero_shot(
|
|
| 1629 |
use_hierarchical: bool = True,
|
| 1630 |
test_prompts: List[str] = None,
|
| 1631 |
):
|
| 1632 |
-
"""Zero-shot Model Burning with
|
| 1633 |
print("="*80)
|
| 1634 |
-
print("🔥 PHOENIX Zero-shot Model Burning")
|
| 1635 |
print("="*80)
|
| 1636 |
|
| 1637 |
output_path = Path(output_dir)
|
| 1638 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 1639 |
|
| 1640 |
try:
|
| 1641 |
-
# 1.
|
| 1642 |
-
print(f"\n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1643 |
start_time = time.time()
|
| 1644 |
|
| 1645 |
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
|
@@ -1656,13 +1601,14 @@ def burn_model_zero_shot(
|
|
| 1656 |
load_time = time.time() - start_time
|
| 1657 |
print(f"✅ Loaded in {load_time:.1f}s")
|
| 1658 |
|
| 1659 |
-
#
|
| 1660 |
-
print(f"\n🔄 Converting Attention → Retention...")
|
| 1661 |
convert_start = time.time()
|
| 1662 |
|
| 1663 |
model.model, converted, total = replace_attention_with_retention(
|
| 1664 |
model.model,
|
| 1665 |
-
use_hierarchical=use_hierarchical
|
|
|
|
| 1666 |
)
|
| 1667 |
|
| 1668 |
convert_time = time.time() - convert_start
|
|
@@ -1670,8 +1616,13 @@ def burn_model_zero_shot(
|
|
| 1670 |
|
| 1671 |
print(f"✅ Converted {converted}/{total} layers ({conversion_rate*100:.1f}%) in {convert_time:.1f}s")
|
| 1672 |
|
| 1673 |
-
|
| 1674 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1675 |
eval_start = time.time()
|
| 1676 |
|
| 1677 |
quality_score = evaluate_model_quality(model, tokenizer, test_prompts)
|
|
@@ -1679,12 +1630,12 @@ def burn_model_zero_shot(
|
|
| 1679 |
eval_time = time.time() - eval_start
|
| 1680 |
print(f"✅ Quality Score: {quality_score:.2f}/1.00 (in {eval_time:.1f}s)")
|
| 1681 |
|
| 1682 |
-
#
|
| 1683 |
-
print(f"\n💾 Saving PHOENIX model with custom code...")
|
| 1684 |
save_start = time.time()
|
| 1685 |
|
| 1686 |
metadata = {
|
| 1687 |
-
'phoenix_version': '1.
|
| 1688 |
'original_model': model_url,
|
| 1689 |
'use_hierarchical': use_hierarchical,
|
| 1690 |
'conversion_rate': conversion_rate,
|
|
@@ -1692,6 +1643,7 @@ def burn_model_zero_shot(
|
|
| 1692 |
'total_layers': total,
|
| 1693 |
'quality_score': quality_score,
|
| 1694 |
'burning_type': 'zero_shot',
|
|
|
|
| 1695 |
'timestamp': datetime.now().isoformat(),
|
| 1696 |
}
|
| 1697 |
|
|
@@ -1712,6 +1664,7 @@ def burn_model_zero_shot(
|
|
| 1712 |
'convert_time': convert_time,
|
| 1713 |
'eval_time': eval_time,
|
| 1714 |
'save_time': save_time,
|
|
|
|
| 1715 |
}
|
| 1716 |
|
| 1717 |
print(f"\n{'='*80}")
|
|
@@ -1719,6 +1672,7 @@ def burn_model_zero_shot(
|
|
| 1719 |
print(f" Total Time: {total_time:.1f}s")
|
| 1720 |
print(f" Model Path: {output_path}")
|
| 1721 |
print(f" Quality: {quality_score:.2f}/1.00")
|
|
|
|
| 1722 |
print(f"{'='*80}\n")
|
| 1723 |
|
| 1724 |
return result
|
|
@@ -1744,17 +1698,21 @@ def burn_model_with_finetuning(
|
|
| 1744 |
learning_rate: float = 5e-5,
|
| 1745 |
max_steps: int = 100,
|
| 1746 |
):
|
| 1747 |
-
"""Fine-tuning Model Burning"""
|
| 1748 |
print("="*80)
|
| 1749 |
-
print("🔥 PHOENIX Fine-tuning Model Burning")
|
| 1750 |
print("="*80)
|
| 1751 |
|
| 1752 |
output_path = Path(output_dir)
|
| 1753 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 1754 |
|
| 1755 |
try:
|
| 1756 |
-
# 1.
|
| 1757 |
-
print(f"\n
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1758 |
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
| 1759 |
model = AutoModelForCausalLM.from_pretrained(
|
| 1760 |
model_url,
|
|
@@ -1766,17 +1724,18 @@ def burn_model_with_finetuning(
|
|
| 1766 |
if tokenizer.pad_token is None:
|
| 1767 |
tokenizer.pad_token = tokenizer.eos_token
|
| 1768 |
|
| 1769 |
-
print(f"\n🔄 Converting...")
|
| 1770 |
model.model, converted, total = replace_attention_with_retention(
|
| 1771 |
model.model,
|
| 1772 |
-
use_hierarchical=use_hierarchical
|
|
|
|
| 1773 |
)
|
| 1774 |
|
| 1775 |
conversion_rate = converted / total if total > 0 else 0
|
| 1776 |
print(f"✅ Converted {converted}/{total} layers")
|
| 1777 |
|
| 1778 |
-
#
|
| 1779 |
-
print(f"\n📊 Loading dataset: {dataset_path}")
|
| 1780 |
|
| 1781 |
if dataset_path.endswith('.txt'):
|
| 1782 |
with open(dataset_path, 'r', encoding='utf-8') as f:
|
|
@@ -1808,8 +1767,8 @@ def burn_model_with_finetuning(
|
|
| 1808 |
|
| 1809 |
print(f"✅ Loaded {len(tokenized_data)} samples")
|
| 1810 |
|
| 1811 |
-
#
|
| 1812 |
-
print(f"\n🚀 Starting fine-tuning...")
|
| 1813 |
model.train()
|
| 1814 |
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
|
| 1815 |
|
|
@@ -1846,12 +1805,12 @@ def burn_model_with_finetuning(
|
|
| 1846 |
final_loss = total_loss / step if step > 0 else 0.0
|
| 1847 |
print(f"✅ Training complete - Final Loss: {final_loss:.4f}")
|
| 1848 |
|
| 1849 |
-
#
|
| 1850 |
model.eval()
|
| 1851 |
quality_score = evaluate_model_quality(model, tokenizer)
|
| 1852 |
|
| 1853 |
metadata = {
|
| 1854 |
-
'phoenix_version': '1.
|
| 1855 |
'original_model': model_url,
|
| 1856 |
'use_hierarchical': use_hierarchical,
|
| 1857 |
'conversion_rate': conversion_rate,
|
|
@@ -1860,6 +1819,7 @@ def burn_model_with_finetuning(
|
|
| 1860 |
'training_steps': step,
|
| 1861 |
'final_loss': final_loss,
|
| 1862 |
'dataset': dataset_path,
|
|
|
|
| 1863 |
'timestamp': datetime.now().isoformat(),
|
| 1864 |
}
|
| 1865 |
|
|
@@ -1872,6 +1832,7 @@ def burn_model_with_finetuning(
|
|
| 1872 |
'quality_score': quality_score,
|
| 1873 |
'training_steps': step,
|
| 1874 |
'final_loss': final_loss,
|
|
|
|
| 1875 |
}
|
| 1876 |
|
| 1877 |
return result
|
|
@@ -1891,106 +1852,6 @@ def burn_model_with_finetuning(
|
|
| 1891 |
# Gradio UI Functions
|
| 1892 |
# =====================================================
|
| 1893 |
|
| 1894 |
-
def convert_model_to_phoenix(model_url, use_hierarchical=True, gpu_type="L40S"):
|
| 1895 |
-
"""Convert model to PHOENIX"""
|
| 1896 |
-
try:
|
| 1897 |
-
start_time = time.time()
|
| 1898 |
-
|
| 1899 |
-
print(f"📥 Loading model: {model_url}")
|
| 1900 |
-
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
| 1901 |
-
model = AutoModel.from_pretrained(
|
| 1902 |
-
model_url,
|
| 1903 |
-
trust_remote_code=True,
|
| 1904 |
-
torch_dtype=torch.float16
|
| 1905 |
-
).to(DEVICE)
|
| 1906 |
-
|
| 1907 |
-
model, converted, total = replace_attention_with_retention(model, use_hierarchical)
|
| 1908 |
-
|
| 1909 |
-
elapsed_time = time.time() - start_time
|
| 1910 |
-
conversion_pct = (converted / total * 100) if total > 0 else 0
|
| 1911 |
-
|
| 1912 |
-
result = f"""
|
| 1913 |
-
✅ **Conversion Complete!**
|
| 1914 |
-
|
| 1915 |
-
**Model**: {model_url}
|
| 1916 |
-
**Converted**: {converted}/{total} layers ({conversion_pct:.1f}%)
|
| 1917 |
-
**Time**: {elapsed_time:.1f}s
|
| 1918 |
-
**GPU**: {gpu_type}
|
| 1919 |
-
|
| 1920 |
-
🎯 GQA-aware O(n) complexity!
|
| 1921 |
-
"""
|
| 1922 |
-
|
| 1923 |
-
return result
|
| 1924 |
-
|
| 1925 |
-
except Exception as e:
|
| 1926 |
-
return f"❌ Conversion failed: {str(e)}"
|
| 1927 |
-
|
| 1928 |
-
|
| 1929 |
-
def generate_text_phoenix(
|
| 1930 |
-
model_url, use_hierarchical, convert_attention,
|
| 1931 |
-
prompt, max_new_tokens, temperature
|
| 1932 |
-
):
|
| 1933 |
-
"""PHOENIX 텍스트 생성"""
|
| 1934 |
-
try:
|
| 1935 |
-
if not convert_attention or not model_url.strip():
|
| 1936 |
-
return "⚠️ Enable 'Attention Replace' and provide model URL", ""
|
| 1937 |
-
|
| 1938 |
-
print(f"📥 Loading model: {model_url}")
|
| 1939 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 1940 |
-
model_url,
|
| 1941 |
-
trust_remote_code=True,
|
| 1942 |
-
torch_dtype=torch.float16
|
| 1943 |
-
).to(DEVICE)
|
| 1944 |
-
|
| 1945 |
-
print(f"🔄 Converting...")
|
| 1946 |
-
model.model, converted, total = replace_attention_with_retention(
|
| 1947 |
-
model.model,
|
| 1948 |
-
use_hierarchical=use_hierarchical
|
| 1949 |
-
)
|
| 1950 |
-
|
| 1951 |
-
tokenizer = AutoTokenizer.from_pretrained(model_url, trust_remote_code=True)
|
| 1952 |
-
if tokenizer.pad_token is None:
|
| 1953 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 1954 |
-
|
| 1955 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 1956 |
-
|
| 1957 |
-
print(f"🚀 Generating...")
|
| 1958 |
-
start_time = time.time()
|
| 1959 |
-
|
| 1960 |
-
outputs = model.generate(
|
| 1961 |
-
**inputs,
|
| 1962 |
-
max_new_tokens=max_new_tokens,
|
| 1963 |
-
temperature=temperature,
|
| 1964 |
-
do_sample=temperature > 0.01,
|
| 1965 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 1966 |
-
)
|
| 1967 |
-
|
| 1968 |
-
elapsed = time.time() - start_time
|
| 1969 |
-
|
| 1970 |
-
generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 1971 |
-
|
| 1972 |
-
output_md = f"""
|
| 1973 |
-
## 📝 Generated Text
|
| 1974 |
-
```
|
| 1975 |
-
{generated}
|
| 1976 |
-
```
|
| 1977 |
-
"""
|
| 1978 |
-
|
| 1979 |
-
stats_md = f"""
|
| 1980 |
-
## 📊 Statistics
|
| 1981 |
-
|
| 1982 |
-
- **Time**: {elapsed:.2f}s
|
| 1983 |
-
- **Converted**: {converted}/{total} layers
|
| 1984 |
-
- **Tokens/s**: {max_new_tokens/elapsed:.1f}
|
| 1985 |
-
"""
|
| 1986 |
-
|
| 1987 |
-
return output_md, stats_md
|
| 1988 |
-
|
| 1989 |
-
except Exception as e:
|
| 1990 |
-
import traceback
|
| 1991 |
-
return f"❌ Error:\n```\n{traceback.format_exc()}\n```", ""
|
| 1992 |
-
|
| 1993 |
-
|
| 1994 |
def burn_phoenix_model_ui(
|
| 1995 |
model_url,
|
| 1996 |
use_hierarchical,
|
|
@@ -2008,11 +1869,10 @@ def burn_phoenix_model_ui(
|
|
| 2008 |
"""Gradio UI용 모델 버닝 함수"""
|
| 2009 |
|
| 2010 |
print("\n" + "="*80)
|
| 2011 |
-
print("🔥 PHOENIX MODEL BURNING START")
|
| 2012 |
print("="*80)
|
| 2013 |
|
| 2014 |
try:
|
| 2015 |
-
# 입력 검증
|
| 2016 |
if not model_url.strip():
|
| 2017 |
return "⚠️ Model URL is required", None
|
| 2018 |
|
|
@@ -2024,7 +1884,6 @@ def burn_phoenix_model_ui(
|
|
| 2024 |
print(f"📋 Configuration:")
|
| 2025 |
print(f" Model URL: {model_url}")
|
| 2026 |
print(f" Output Name: {output_name}")
|
| 2027 |
-
print(f" Output Dir: {output_dir}")
|
| 2028 |
print(f" Hierarchical: {use_hierarchical}")
|
| 2029 |
print(f" Upload to Hub: {upload_to_hub}")
|
| 2030 |
|
|
@@ -2033,19 +1892,8 @@ def burn_phoenix_model_ui(
|
|
| 2033 |
if use_finetuning and not has_dataset:
|
| 2034 |
return "⚠️ Fine-tuning requires a valid dataset path", None
|
| 2035 |
|
| 2036 |
-
# HF Token 확인
|
| 2037 |
if upload_to_hub and not HF_TOKEN:
|
| 2038 |
-
warning_msg = ""
|
| 2039 |
-
⚠️ **HuggingFace Token Not Found!**
|
| 2040 |
-
|
| 2041 |
-
Model will be burned locally, but upload will fail.
|
| 2042 |
-
|
| 2043 |
-
To enable upload:
|
| 2044 |
-
1. Set `HF_TOKEN` environment variable
|
| 2045 |
-
2. Restart the application
|
| 2046 |
-
|
| 2047 |
-
Continuing with local burning only...
|
| 2048 |
-
"""
|
| 2049 |
print(f"\n{warning_msg}")
|
| 2050 |
|
| 2051 |
# Burning 실행
|
|
@@ -2071,17 +1919,7 @@ Continuing with local burning only...
|
|
| 2071 |
)
|
| 2072 |
|
| 2073 |
if result['status'] != 'success':
|
| 2074 |
-
error_msg = f""
|
| 2075 |
-
❌ **Burning Failed**
|
| 2076 |
-
```
|
| 2077 |
-
{result.get('error', 'Unknown error')}
|
| 2078 |
-
```
|
| 2079 |
-
|
| 2080 |
-
**Traceback:**
|
| 2081 |
-
```
|
| 2082 |
-
{result.get('traceback', 'N/A')}
|
| 2083 |
-
```
|
| 2084 |
-
"""
|
| 2085 |
return error_msg, None
|
| 2086 |
|
| 2087 |
print(f"\n✅ Burning completed successfully!")
|
|
@@ -2094,12 +1932,7 @@ Continuing with local burning only...
|
|
| 2094 |
if upload_to_hub:
|
| 2095 |
if not HF_TOKEN:
|
| 2096 |
upload_status = "❌ Failed - No HF_TOKEN"
|
| 2097 |
-
print(f"\n{upload_status}")
|
| 2098 |
else:
|
| 2099 |
-
print(f"\n{'='*80}")
|
| 2100 |
-
print("📤 Starting HuggingFace Hub Upload...")
|
| 2101 |
-
print(f"{'='*80}")
|
| 2102 |
-
|
| 2103 |
success, hub_url, upload_msg = upload_to_huggingface_hub(
|
| 2104 |
model_path=result['model_path'],
|
| 2105 |
original_model_url=model_url,
|
|
@@ -2109,16 +1942,9 @@ Continuing with local burning only...
|
|
| 2109 |
)
|
| 2110 |
|
| 2111 |
verification_passed = success
|
| 2112 |
-
|
| 2113 |
-
if success:
|
| 2114 |
-
upload_status = f"✅ Uploaded successfully to {hub_url}"
|
| 2115 |
-
print(f"\n{upload_status}")
|
| 2116 |
-
else:
|
| 2117 |
-
upload_status = f"❌ Upload failed\n\n{upload_msg}"
|
| 2118 |
-
print(f"\n{upload_status}")
|
| 2119 |
else:
|
| 2120 |
-
upload_status = "⏭️ Skipped
|
| 2121 |
-
print(f"\n📦 Hub upload: {upload_status}")
|
| 2122 |
|
| 2123 |
# 데이터베이스 저장
|
| 2124 |
burning_info = {
|
|
@@ -2135,11 +1961,20 @@ Continuing with local burning only...
|
|
| 2135 |
}
|
| 2136 |
|
| 2137 |
db.save_burning(burning_info)
|
| 2138 |
-
print(f"✅ Saved to database")
|
| 2139 |
|
| 2140 |
# 결과 포맷팅
|
|
|
|
|
|
|
| 2141 |
output_md = f"""
|
| 2142 |
-
# 🔥 Model Burning Complete!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2143 |
|
| 2144 |
## 📦 Model Information
|
| 2145 |
- **Original Model**: {model_url}
|
|
@@ -2170,7 +2005,6 @@ Continuing with local burning only...
|
|
| 2170 |
output_md += f"- **Evaluate**: {result['eval_time']:.1f}s\n"
|
| 2171 |
output_md += f"- **Save**: {result['save_time']:.1f}s\n"
|
| 2172 |
|
| 2173 |
-
# Hub Upload 상태
|
| 2174 |
output_md += f"""
|
| 2175 |
---
|
| 2176 |
|
|
@@ -2182,88 +2016,39 @@ Continuing with local burning only...
|
|
| 2182 |
if hub_url:
|
| 2183 |
output_md += f"""
|
| 2184 |
**Model URL**: [{hub_url}]({hub_url})
|
| 2185 |
-
**Privacy**: {'🔒 Private' if hub_private else '🌍 Public'}
|
| 2186 |
-
**Verification**: {'✅ Passed' if verification_passed else '⚠️ Not verified'}
|
| 2187 |
|
| 2188 |
### 🚀 Load from Hub
|
| 2189 |
```python
|
| 2190 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2191 |
|
| 2192 |
-
# ⚠️ MUST use trust_remote_code=True
|
| 2193 |
model = AutoModelForCausalLM.from_pretrained(
|
| 2194 |
"{hub_url.replace('https://huggingface.co/', '')}",
|
| 2195 |
-
trust_remote_code=True,
|
| 2196 |
torch_dtype="auto",
|
| 2197 |
device_map="auto"
|
| 2198 |
)
|
| 2199 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 2200 |
-
"{hub_url.replace('https://huggingface.co/', '')}"
|
| 2201 |
-
)
|
| 2202 |
-
|
| 2203 |
-
# Generate
|
| 2204 |
-
inputs = tokenizer("Your prompt here", return_tensors="pt")
|
| 2205 |
-
outputs = model.generate(**inputs, max_new_tokens=50)
|
| 2206 |
-
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 2207 |
```
|
| 2208 |
-
"""
|
| 2209 |
-
elif upload_to_hub:
|
| 2210 |
-
output_md += f"""
|
| 2211 |
-
**Upload failed!** Check logs for details.
|
| 2212 |
-
|
| 2213 |
-
💡 **Troubleshooting:**
|
| 2214 |
-
1. Ensure `HF_TOKEN` environment variable is set
|
| 2215 |
-
2. Check token permissions (write access required)
|
| 2216 |
-
3. Verify network connectivity
|
| 2217 |
-
4. Review error messages above
|
| 2218 |
"""
|
| 2219 |
|
| 2220 |
output_md += f"""
|
| 2221 |
---
|
| 2222 |
|
| 2223 |
-
|
| 2224 |
-
```python
|
| 2225 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2226 |
-
|
| 2227 |
-
# Load from local path
|
| 2228 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 2229 |
-
"{result['model_path']}",
|
| 2230 |
-
trust_remote_code=True # Important!
|
| 2231 |
-
)
|
| 2232 |
-
tokenizer = AutoTokenizer.from_pretrained("{result['model_path']}")
|
| 2233 |
-
|
| 2234 |
-
# Generate
|
| 2235 |
-
inputs = tokenizer("Your prompt", return_tensors="pt")
|
| 2236 |
-
outputs = model.generate(**inputs, max_new_tokens=50)
|
| 2237 |
-
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 2238 |
-
```
|
| 2239 |
-
|
| 2240 |
-
---
|
| 2241 |
-
|
| 2242 |
-
✅ **PHOENIX Model Ready!**
|
| 2243 |
-
|
| 2244 |
-
{'📤 Model uploaded to HuggingFace Hub' if hub_url else '💾 Model saved locally'}
|
| 2245 |
"""
|
| 2246 |
|
| 2247 |
-
# 플롯
|
| 2248 |
fig = go.Figure()
|
| 2249 |
|
| 2250 |
metrics_names = ['Conversion', 'Quality']
|
| 2251 |
metrics_values = [result.get('conversion_rate', 0), result.get('quality_score', 0)]
|
| 2252 |
-
metrics_text = [
|
| 2253 |
-
f"{result.get('conversion_rate', 0)*100:.1f}%",
|
| 2254 |
-
f"{result.get('quality_score', 0):.2f}"
|
| 2255 |
-
]
|
| 2256 |
|
| 2257 |
if verification_passed:
|
| 2258 |
metrics_names.append('Upload')
|
| 2259 |
metrics_values.append(1.0)
|
| 2260 |
-
metrics_text.append('✅')
|
| 2261 |
|
| 2262 |
fig.add_trace(go.Bar(
|
| 2263 |
x=metrics_names,
|
| 2264 |
y=metrics_values,
|
| 2265 |
-
text=metrics_text,
|
| 2266 |
-
textposition='auto',
|
| 2267 |
marker_color=['#3b82f6', '#10b981', '#8b5cf6'][:len(metrics_names)]
|
| 2268 |
))
|
| 2269 |
|
|
@@ -2274,37 +2059,21 @@ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
|
| 2274 |
height=400
|
| 2275 |
)
|
| 2276 |
|
| 2277 |
-
print(f"\n{'='*80}")
|
| 2278 |
-
print(f"✅ PHOENIX MODEL BURNING COMPLETE!")
|
| 2279 |
-
print(f"{'='*80}\n")
|
| 2280 |
-
|
| 2281 |
return output_md, fig
|
| 2282 |
|
| 2283 |
except Exception as e:
|
| 2284 |
import traceback
|
| 2285 |
error_msg = traceback.format_exc()
|
| 2286 |
|
| 2287 |
-
print(f"\n{'='*80}")
|
| 2288 |
-
print(f"❌ BURNING FAILED")
|
| 2289 |
-
print(f"{'='*80}")
|
| 2290 |
-
print(f"{error_msg}")
|
| 2291 |
-
print(f"{'='*80}\n")
|
| 2292 |
-
|
| 2293 |
return f"""
|
| 2294 |
❌ **Burning Failed**
|
| 2295 |
|
| 2296 |
**Error:** {str(e)}
|
| 2297 |
|
| 2298 |
-
**
|
| 2299 |
```
|
| 2300 |
{error_msg}
|
| 2301 |
```
|
| 2302 |
-
|
| 2303 |
-
**Troubleshooting:**
|
| 2304 |
-
1. Check model URL is valid
|
| 2305 |
-
2. Ensure sufficient disk space
|
| 2306 |
-
3. Verify GPU availability
|
| 2307 |
-
4. Check logs above for details
|
| 2308 |
""", None
|
| 2309 |
|
| 2310 |
|
|
@@ -2325,7 +2094,7 @@ def view_burning_history():
|
|
| 2325 |
size='conversion_rate',
|
| 2326 |
color='verification_passed',
|
| 2327 |
hover_data=['model_url', 'output_path', 'hub_url'],
|
| 2328 |
-
title='Burning History
|
| 2329 |
)
|
| 2330 |
|
| 2331 |
cols = ['id', 'model_url', 'hub_url', 'conversion_rate',
|
|
@@ -2349,7 +2118,7 @@ def validate_phoenix_model(
|
|
| 2349 |
"""PHOENIX 모델 검증"""
|
| 2350 |
try:
|
| 2351 |
print("="*80)
|
| 2352 |
-
print("🧪 PHOENIX Model Validation")
|
| 2353 |
print("="*80)
|
| 2354 |
|
| 2355 |
# 1. 모델 로드
|
|
@@ -2373,7 +2142,7 @@ def validate_phoenix_model(
|
|
| 2373 |
load_time = time.time() - start_time
|
| 2374 |
print(f"✅ Model loaded in {load_time:.2f}s")
|
| 2375 |
|
| 2376 |
-
# 2. 메타데이터
|
| 2377 |
metadata = {}
|
| 2378 |
metadata_path = None
|
| 2379 |
|
|
@@ -2392,11 +2161,6 @@ def validate_phoenix_model(
|
|
| 2392 |
if metadata_path and Path(metadata_path).exists():
|
| 2393 |
with open(metadata_path, 'r') as f:
|
| 2394 |
metadata = json.load(f)
|
| 2395 |
-
print(f"\n📋 Metadata found:")
|
| 2396 |
-
print(f" PHOENIX Version: {metadata.get('phoenix_version')}")
|
| 2397 |
-
print(f" Original Model: {metadata.get('original_model')}")
|
| 2398 |
-
print(f" Conversion Rate: {metadata.get('conversion_rate', 0)*100:.1f}%")
|
| 2399 |
-
print(f" Quality Score: {metadata.get('quality_score', 0):.2f}")
|
| 2400 |
|
| 2401 |
# 3. Retention 검증
|
| 2402 |
retention_info = ""
|
|
@@ -2428,7 +2192,7 @@ def validate_phoenix_model(
|
|
| 2428 |
"""
|
| 2429 |
print(f" Retention: {retention_count}/{total} layers")
|
| 2430 |
|
| 2431 |
-
# 4.
|
| 2432 |
print(f"\n🚀 Running generation tests...")
|
| 2433 |
|
| 2434 |
prompts = [p.strip() for p in test_prompts.split('\n') if p.strip()]
|
|
@@ -2439,8 +2203,6 @@ def validate_phoenix_model(
|
|
| 2439 |
total_gen_time = 0
|
| 2440 |
|
| 2441 |
for i, prompt in enumerate(prompts, 1):
|
| 2442 |
-
print(f" Test {i}/{len(prompts)}: {prompt[:50]}...")
|
| 2443 |
-
|
| 2444 |
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 2445 |
|
| 2446 |
gen_start = time.time()
|
|
@@ -2469,18 +2231,15 @@ def validate_phoenix_model(
|
|
| 2469 |
'tokens': tokens_generated,
|
| 2470 |
'tokens_per_sec': tokens_per_sec,
|
| 2471 |
})
|
| 2472 |
-
|
| 2473 |
-
print(f" Time: {gen_time:.2f}s | Tokens/s: {tokens_per_sec:.1f}")
|
| 2474 |
|
| 2475 |
-
# 5. 결과
|
| 2476 |
output_md = f"""
|
| 2477 |
-
# ✅ PHOENIX Model Validation Complete!
|
| 2478 |
|
| 2479 |
## 📦 Model Information
|
| 2480 |
- **Source**: {model_source.upper()}
|
| 2481 |
- **Path/URL**: `{model_path_or_url}`
|
| 2482 |
- **Load Time**: {load_time:.2f}s
|
| 2483 |
-
- **Device**: {DEVICE}
|
| 2484 |
|
| 2485 |
## 📋 Metadata
|
| 2486 |
"""
|
|
@@ -2490,11 +2249,7 @@ def validate_phoenix_model(
|
|
| 2490 |
- **PHOENIX Version**: {metadata.get('phoenix_version', 'Unknown')}
|
| 2491 |
- **Original Model**: {metadata.get('original_model', 'Unknown')}
|
| 2492 |
- **Conversion Rate**: {metadata.get('conversion_rate', 0)*100:.1f}%
|
| 2493 |
-
- **Quality Score**: {metadata.get('quality_score', 0):.2f}/1.00
|
| 2494 |
-
- **Burning Type**: {metadata.get('burning_type', 'Unknown')}
|
| 2495 |
"""
|
| 2496 |
-
else:
|
| 2497 |
-
output_md += "- ⚠️ No metadata found\n"
|
| 2498 |
|
| 2499 |
if retention_info:
|
| 2500 |
output_md += retention_info
|
|
@@ -2503,7 +2258,6 @@ def validate_phoenix_model(
|
|
| 2503 |
## 🚀 Generation Tests
|
| 2504 |
|
| 2505 |
**Total Tests**: {len(results)}
|
| 2506 |
-
**Total Time**: {total_gen_time:.2f}s
|
| 2507 |
**Average Speed**: {sum(r['tokens_per_sec'] for r in results)/len(results):.1f} tokens/s
|
| 2508 |
|
| 2509 |
---
|
|
@@ -2511,17 +2265,14 @@ def validate_phoenix_model(
|
|
| 2511 |
|
| 2512 |
for i, result in enumerate(results, 1):
|
| 2513 |
output_md += f"""
|
| 2514 |
-
### Test {i}
|
| 2515 |
|
| 2516 |
-
**Generated
|
| 2517 |
```
|
| 2518 |
{result['generated']}
|
| 2519 |
```
|
| 2520 |
|
| 2521 |
-
**Stats
|
| 2522 |
-
- Time: {result['time']:.2f}s
|
| 2523 |
-
- Tokens: {result['tokens']}
|
| 2524 |
-
- Speed: {result['tokens_per_sec']:.1f} tokens/s
|
| 2525 |
|
| 2526 |
---
|
| 2527 |
"""
|
|
@@ -2530,112 +2281,57 @@ def validate_phoenix_model(
|
|
| 2530 |
fig = go.Figure()
|
| 2531 |
|
| 2532 |
fig.add_trace(go.Bar(
|
| 2533 |
-
name='Generation Time (s)',
|
| 2534 |
-
x=[f"Test {i+1}" for i in range(len(results))],
|
| 2535 |
-
y=[r['time'] for r in results],
|
| 2536 |
-
text=[f"{r['time']:.2f}s" for r in results],
|
| 2537 |
-
textposition='auto',
|
| 2538 |
-
))
|
| 2539 |
-
|
| 2540 |
-
fig.add_trace(go.Bar(
|
| 2541 |
-
name='Tokens/s',
|
| 2542 |
x=[f"Test {i+1}" for i in range(len(results))],
|
| 2543 |
y=[r['tokens_per_sec'] for r in results],
|
| 2544 |
-
|
| 2545 |
-
textposition='auto',
|
| 2546 |
-
yaxis='y2'
|
| 2547 |
))
|
| 2548 |
|
| 2549 |
fig.update_layout(
|
| 2550 |
-
title="
|
| 2551 |
-
xaxis_title="Test",
|
| 2552 |
-
yaxis_title="Time (s)",
|
| 2553 |
-
yaxis2=dict(
|
| 2554 |
-
title="Tokens/s",
|
| 2555 |
-
overlaying='y',
|
| 2556 |
-
side='right'
|
| 2557 |
-
),
|
| 2558 |
-
barmode='group',
|
| 2559 |
template='plotly_white'
|
| 2560 |
)
|
| 2561 |
|
| 2562 |
-
print(f"\n✅ Validation Complete!\n")
|
| 2563 |
-
|
| 2564 |
return output_md, fig
|
| 2565 |
|
| 2566 |
except Exception as e:
|
| 2567 |
import traceback
|
| 2568 |
-
|
| 2569 |
-
return f"❌ Validation failed:\n```\n{error_msg}\n```", None
|
| 2570 |
|
| 2571 |
|
| 2572 |
# 전역 초기화
|
| 2573 |
db = ExperimentDatabase(DB_PATH)
|
| 2574 |
-
CONVERTED_MODELS = {}
|
| 2575 |
|
| 2576 |
# =====================================================
|
| 2577 |
# Gradio UI
|
| 2578 |
# =====================================================
|
| 2579 |
|
| 2580 |
with gr.Blocks(
|
| 2581 |
-
title="🔮 PHOENIX - Model Burning
|
| 2582 |
theme=gr.themes.Soft(),
|
| 2583 |
) as demo:
|
| 2584 |
|
| 2585 |
gr.Markdown("""
|
| 2586 |
-
# 🔮 PHOENIX Retention Platform v1.
|
| 2587 |
|
| 2588 |
-
**
|
| 2589 |
|
| 2590 |
-
✅
|
| 2591 |
-
✅
|
|
|
|
|
|
|
| 2592 |
✅ GQA Support
|
| 2593 |
✅ O(n) Complexity
|
| 2594 |
✅ Auto Upload to HuggingFace Hub
|
| 2595 |
-
✅ Custom Code for Proper Loading
|
| 2596 |
-
✅ Pre-upload Verification
|
| 2597 |
|
| 2598 |
---
|
| 2599 |
""")
|
| 2600 |
|
| 2601 |
with gr.Tabs():
|
| 2602 |
-
with gr.Tab("🔄 Quick Convert"):
|
| 2603 |
-
gr.Markdown("""
|
| 2604 |
-
### 빠른 변환 테스트
|
| 2605 |
-
모델을 로드하고 Attention → Retention 변환만 수행합니다. (저장 안 함)
|
| 2606 |
-
""")
|
| 2607 |
-
|
| 2608 |
-
with gr.Row():
|
| 2609 |
-
with gr.Column(scale=1):
|
| 2610 |
-
convert_url = gr.Textbox(
|
| 2611 |
-
label="🔗 Model URL",
|
| 2612 |
-
value=DEFAULT_MODEL,
|
| 2613 |
-
placeholder="ibm-granite/granite-4.0-h-350m"
|
| 2614 |
-
)
|
| 2615 |
-
convert_hierarchical = gr.Checkbox(value=True, label="Hierarchical Retention")
|
| 2616 |
-
convert_gpu = gr.Radio(choices=["L40S", "H100"], value="L40S", label="GPU")
|
| 2617 |
-
convert_btn = gr.Button("🔄 Convert", variant="primary")
|
| 2618 |
-
|
| 2619 |
-
with gr.Column(scale=2):
|
| 2620 |
-
convert_output = gr.Markdown()
|
| 2621 |
-
|
| 2622 |
-
convert_btn.click(
|
| 2623 |
-
convert_model_to_phoenix,
|
| 2624 |
-
[convert_url, convert_hierarchical, convert_gpu],
|
| 2625 |
-
[convert_output]
|
| 2626 |
-
)
|
| 2627 |
-
|
| 2628 |
with gr.Tab("🔥 Model Burning"):
|
| 2629 |
gr.Markdown("""
|
| 2630 |
-
### 🔥 PHOENIX Model Burning v1.
|
| 2631 |
|
| 2632 |
-
|
| 2633 |
-
|
| 2634 |
-
- **Zero-shot**: 데이터셋 없이 변환만 수행 (빠름!)
|
| 2635 |
-
- **Fine-tuning**: 데이터셋으로 추가 학습 (성능 향상)
|
| 2636 |
-
- **HuggingFace Hub**: 자동으로 Hub에 업로드 (Private 기본)
|
| 2637 |
-
- **Custom Code**: modeling_phoenix.py 자동 생성
|
| 2638 |
-
- **Pre-upload Verification**: 업로드 전 검증
|
| 2639 |
""")
|
| 2640 |
|
| 2641 |
with gr.Row():
|
|
@@ -2643,46 +2339,27 @@ with gr.Blocks(
|
|
| 2643 |
burn_model_url = gr.Textbox(
|
| 2644 |
label="🔗 Model URL",
|
| 2645 |
value=DEFAULT_MODEL,
|
| 2646 |
-
placeholder="
|
| 2647 |
)
|
| 2648 |
burn_hierarchical = gr.Checkbox(value=True, label="Hierarchical Retention")
|
| 2649 |
|
| 2650 |
burn_output_name = gr.Textbox(
|
| 2651 |
label="💾 Output Name",
|
| 2652 |
-
placeholder="phoenix_my_model
|
| 2653 |
)
|
| 2654 |
|
| 2655 |
gr.Markdown("---")
|
| 2656 |
gr.Markdown("### 🌐 HuggingFace Hub Upload")
|
| 2657 |
|
| 2658 |
-
burn_upload_hub = gr.Checkbox(
|
| 2659 |
-
|
| 2660 |
-
|
| 2661 |
-
)
|
| 2662 |
-
|
| 2663 |
-
burn_hub_repo = gr.Textbox(
|
| 2664 |
-
label="📦 Hub Repository Name (optional)",
|
| 2665 |
-
placeholder="phoenix-granite-350m"
|
| 2666 |
-
)
|
| 2667 |
-
|
| 2668 |
-
burn_hub_private = gr.Checkbox(
|
| 2669 |
-
value=True,
|
| 2670 |
-
label="🔒 Private Repository"
|
| 2671 |
-
)
|
| 2672 |
|
| 2673 |
gr.Markdown("---")
|
| 2674 |
gr.Markdown("### 📊 Dataset (Optional)")
|
| 2675 |
|
| 2676 |
-
burn_dataset = gr.Textbox(
|
| 2677 |
-
|
| 2678 |
-
placeholder="/path/to/dataset.txt",
|
| 2679 |
-
value=""
|
| 2680 |
-
)
|
| 2681 |
-
|
| 2682 |
-
burn_use_finetuning = gr.Checkbox(
|
| 2683 |
-
value=False,
|
| 2684 |
-
label="🚀 Enable Fine-tuning (requires dataset)"
|
| 2685 |
-
)
|
| 2686 |
|
| 2687 |
with gr.Accordion("⚙️ Fine-tuning Config", open=False):
|
| 2688 |
burn_epochs = gr.Slider(1, 5, 1, step=1, label="Epochs")
|
|
@@ -2699,61 +2376,15 @@ with gr.Blocks(
|
|
| 2699 |
burn_btn.click(
|
| 2700 |
burn_phoenix_model_ui,
|
| 2701 |
[
|
| 2702 |
-
burn_model_url,
|
| 2703 |
-
|
| 2704 |
-
|
| 2705 |
-
burn_output_name,
|
| 2706 |
-
burn_use_finetuning,
|
| 2707 |
-
burn_epochs,
|
| 2708 |
-
burn_batch,
|
| 2709 |
-
burn_lr,
|
| 2710 |
-
burn_max_steps,
|
| 2711 |
-
burn_upload_hub,
|
| 2712 |
-
burn_hub_repo,
|
| 2713 |
-
burn_hub_private,
|
| 2714 |
],
|
| 2715 |
[burn_output, burn_plot]
|
| 2716 |
)
|
| 2717 |
|
| 2718 |
-
with gr.Tab("💬 Text Generation"):
|
| 2719 |
-
gr.Markdown("""
|
| 2720 |
-
### PHOENIX 텍스트 생성
|
| 2721 |
-
변환된 모델로 텍스트를 생성합니다.
|
| 2722 |
-
""")
|
| 2723 |
-
|
| 2724 |
-
with gr.Row():
|
| 2725 |
-
with gr.Column(scale=1):
|
| 2726 |
-
gen_model_url = gr.Textbox(label="🔗 Model URL", value=DEFAULT_MODEL)
|
| 2727 |
-
gen_hierarchical = gr.Checkbox(value=True, label="Hierarchical")
|
| 2728 |
-
gen_convert = gr.Checkbox(value=True, label="Enable Conversion")
|
| 2729 |
-
|
| 2730 |
-
gen_prompt = gr.Textbox(
|
| 2731 |
-
label="📝 Prompt",
|
| 2732 |
-
lines=3,
|
| 2733 |
-
value="The future of AI is"
|
| 2734 |
-
)
|
| 2735 |
-
|
| 2736 |
-
gen_max_tokens = gr.Slider(16, 256, 64, step=16, label="Max Tokens")
|
| 2737 |
-
gen_temperature = gr.Slider(0.1, 2.0, 0.7, step=0.1, label="Temperature")
|
| 2738 |
-
|
| 2739 |
-
gen_btn = gr.Button("🚀 Generate", variant="primary")
|
| 2740 |
-
|
| 2741 |
-
with gr.Column(scale=2):
|
| 2742 |
-
gen_output = gr.Markdown()
|
| 2743 |
-
gen_stats = gr.Markdown()
|
| 2744 |
-
|
| 2745 |
-
gen_btn.click(
|
| 2746 |
-
generate_text_phoenix,
|
| 2747 |
-
[gen_model_url, gen_hierarchical, gen_convert, gen_prompt,
|
| 2748 |
-
gen_max_tokens, gen_temperature],
|
| 2749 |
-
[gen_output, gen_stats]
|
| 2750 |
-
)
|
| 2751 |
-
|
| 2752 |
with gr.Tab("📊 Burning History"):
|
| 2753 |
-
gr.Markdown(""
|
| 2754 |
-
### 📊 Model Burning History
|
| 2755 |
-
저장된 모델 버닝 기록을 확인합니다.
|
| 2756 |
-
""")
|
| 2757 |
|
| 2758 |
with gr.Row():
|
| 2759 |
with gr.Column(scale=1):
|
|
@@ -2766,11 +2397,7 @@ with gr.Blocks(
|
|
| 2766 |
hist_btn.click(view_burning_history, outputs=[hist_output, hist_plot])
|
| 2767 |
|
| 2768 |
with gr.Tab("🧪 Model Validation"):
|
| 2769 |
-
gr.Markdown(""
|
| 2770 |
-
### 🧪 PHOENIX 모델 검증
|
| 2771 |
-
|
| 2772 |
-
배포된 PHOENIX 모델을 로드하고 품질을 검증합니다.
|
| 2773 |
-
""")
|
| 2774 |
|
| 2775 |
with gr.Row():
|
| 2776 |
with gr.Column(scale=1):
|
|
@@ -2782,7 +2409,7 @@ with gr.Blocks(
|
|
| 2782 |
|
| 2783 |
val_path = gr.Textbox(
|
| 2784 |
label="🔗 Model Path/URL",
|
| 2785 |
-
value="seawolf2357/phoenix-
|
| 2786 |
placeholder="seawolf2357/phoenix-model"
|
| 2787 |
)
|
| 2788 |
|
|
@@ -2796,10 +2423,7 @@ with gr.Blocks(
|
|
| 2796 |
val_max_tokens = gr.Slider(16, 256, 64, step=16, label="Max Tokens")
|
| 2797 |
val_temp = gr.Slider(0.1, 2.0, 0.7, step=0.1, label="Temperature")
|
| 2798 |
|
| 2799 |
-
val_verify_retention = gr.Checkbox(
|
| 2800 |
-
value=True,
|
| 2801 |
-
label="🔍 Verify Retention Mechanism"
|
| 2802 |
-
)
|
| 2803 |
|
| 2804 |
val_btn = gr.Button("🧪 Validate Model", variant="primary", size="lg")
|
| 2805 |
|
|
@@ -2817,20 +2441,17 @@ with gr.Blocks(
|
|
| 2817 |
gr.Markdown(f"""
|
| 2818 |
---
|
| 2819 |
|
| 2820 |
-
## 🔥 PHOENIX Model Burning Platform v1.
|
| 2821 |
|
| 2822 |
-
###
|
| 2823 |
-
- ✅
|
| 2824 |
-
- ✅
|
| 2825 |
-
- ✅
|
| 2826 |
-
- ✅ O(n) Complexity
|
| 2827 |
-
- ✅ HuggingFace Hub Auto-Upload
|
| 2828 |
-
- ✅ Custom Code Generation
|
| 2829 |
-
- ✅ Pre-upload Verification
|
| 2830 |
|
| 2831 |
**HuggingFace Token**: {'✅ Connected' if HF_TOKEN else '❌ Not Found'}
|
|
|
|
| 2832 |
|
| 2833 |
-
**VIDraft AI Research Lab** | PHOENIX v1.
|
| 2834 |
""")
|
| 2835 |
|
| 2836 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
+
🔮 PHOENIX Retention Research Platform - PRODUCTION VERSION v1.2
|
| 3 |
+
Model Structure Pre-Analysis + Zero-shot Burning + Optional Fine-tuning + HuggingFace Hub
|
| 4 |
|
| 5 |
+
✅ Model Structure Pre-Analysis (NEW!)
|
| 6 |
+
✅ Qwen3 Model Support (NEW!)
|
| 7 |
✅ Zero-shot Conversion (No Dataset Required)
|
| 8 |
✅ Optional Fine-tuning (Dataset-based)
|
| 9 |
✅ GQA Support
|
| 10 |
✅ HuggingFace Hub Integration with Custom Code
|
| 11 |
✅ Comprehensive Evaluation
|
|
|
|
| 12 |
✅ Pre-upload Verification
|
| 13 |
|
| 14 |
VIDraft AI Research Lab
|
|
|
|
| 52 |
DB_PATH = f"{STORAGE_PATH}/phoenix_experiments.db"
|
| 53 |
VECTOR_DB_PATH = f"{STORAGE_PATH}/vector_store"
|
| 54 |
MODELS_PATH = f"{STORAGE_PATH}/phoenix_models"
|
| 55 |
+
DEFAULT_MODEL = "Qwen/Qwen3-0.6B" # 기준 모델 변경
|
| 56 |
|
| 57 |
# HuggingFace Token
|
| 58 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 61 |
Path(VECTOR_DB_PATH).mkdir(parents=True, exist_ok=True)
|
| 62 |
Path(MODELS_PATH).mkdir(parents=True, exist_ok=True)
|
| 63 |
|
| 64 |
+
print(f"🚀 PHOENIX Platform v1.2 initialized on {DEVICE}")
|
| 65 |
print(f"💾 Storage: {STORAGE_PATH}")
|
| 66 |
print(f"🎯 Default Base Model: {DEFAULT_MODEL}")
|
| 67 |
if HF_TOKEN:
|
|
|
|
| 69 |
else:
|
| 70 |
print(f"⚠️ HuggingFace Token not found (upload disabled)")
|
| 71 |
|
| 72 |
+
# =====================================================
|
| 73 |
+
# 모델 구조 분석 함수 (NEW!)
|
| 74 |
+
# =====================================================
|
| 75 |
+
|
| 76 |
+
def analyze_model_structure(model_url: str) -> Dict[str, Any]:
|
| 77 |
+
"""
|
| 78 |
+
🔍 모델 구조 사전 분석
|
| 79 |
+
변환 전 모델의 레이어 구조를 파악합니다.
|
| 80 |
+
"""
|
| 81 |
+
print("\n" + "="*80)
|
| 82 |
+
print("🔍 MODEL STRUCTURE ANALYSIS")
|
| 83 |
+
print("="*80)
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
print(f"\n📥 Loading model config: {model_url}")
|
| 87 |
+
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
| 88 |
+
|
| 89 |
+
print(f"✅ Config loaded")
|
| 90 |
+
print(f" Architecture: {config.architectures if hasattr(config, 'architectures') else 'Unknown'}")
|
| 91 |
+
print(f" Model Type: {config.model_type if hasattr(config, 'model_type') else 'Unknown'}")
|
| 92 |
+
|
| 93 |
+
# 간단한 모델 로드 (구조 확인용)
|
| 94 |
+
print(f"\n📦 Loading model structure...")
|
| 95 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 96 |
+
model_url,
|
| 97 |
+
trust_remote_code=True,
|
| 98 |
+
torch_dtype=torch.float16,
|
| 99 |
+
device_map="cpu" # CPU로 구조만 확인
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
analysis = {
|
| 103 |
+
'model_url': model_url,
|
| 104 |
+
'model_type': config.model_type if hasattr(config, 'model_type') else 'unknown',
|
| 105 |
+
'architectures': config.architectures[0] if hasattr(config, 'architectures') else 'unknown',
|
| 106 |
+
'hidden_size': config.hidden_size if hasattr(config, 'hidden_size') else 0,
|
| 107 |
+
'num_attention_heads': config.num_attention_heads if hasattr(config, 'num_attention_heads') else 0,
|
| 108 |
+
'num_hidden_layers': config.num_hidden_layers if hasattr(config, 'num_hidden_layers') else 0,
|
| 109 |
+
'num_key_value_heads': config.num_key_value_heads if hasattr(config, 'num_key_value_heads') else None,
|
| 110 |
+
'layer_structure': None,
|
| 111 |
+
'attention_type': 'unknown',
|
| 112 |
+
'total_layers': 0,
|
| 113 |
+
'has_self_attn': False,
|
| 114 |
+
'layer_path': None,
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# 레이어 구조 탐색
|
| 118 |
+
print(f"\n🔍 Analyzing layer structure...")
|
| 119 |
+
|
| 120 |
+
layers = None
|
| 121 |
+
layer_path = None
|
| 122 |
+
|
| 123 |
+
# 여러 가능한 구조 탐색
|
| 124 |
+
possible_paths = [
|
| 125 |
+
('model.layers', lambda m: m.model.layers if hasattr(m, 'model') and hasattr(m.model, 'layers') else None),
|
| 126 |
+
('transformer.h', lambda m: m.transformer.h if hasattr(m, 'transformer') and hasattr(m.transformer, 'h') else None),
|
| 127 |
+
('layers', lambda m: m.layers if hasattr(m, 'layers') else None),
|
| 128 |
+
('model.decoder.layers', lambda m: m.model.decoder.layers if hasattr(m, 'model') and hasattr(m.model, 'decoder') and hasattr(m.model.decoder, 'layers') else None),
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
for path_name, path_fn in possible_paths:
|
| 132 |
+
result = path_fn(model)
|
| 133 |
+
if result is not None:
|
| 134 |
+
layers = result
|
| 135 |
+
layer_path = path_name
|
| 136 |
+
print(f" ✅ Found layers at: {path_name}")
|
| 137 |
+
break
|
| 138 |
+
|
| 139 |
+
if layers is None:
|
| 140 |
+
print(f" ❌ No layers found! Model structure unknown.")
|
| 141 |
+
analysis['error'] = 'No layers found'
|
| 142 |
+
return analysis
|
| 143 |
+
|
| 144 |
+
analysis['total_layers'] = len(layers)
|
| 145 |
+
analysis['layer_path'] = layer_path
|
| 146 |
+
|
| 147 |
+
print(f" Total Layers: {len(layers)}")
|
| 148 |
+
|
| 149 |
+
# 첫 번째 레이어 분석
|
| 150 |
+
if len(layers) > 0:
|
| 151 |
+
first_layer = layers[0]
|
| 152 |
+
print(f"\n🔬 Analyzing first layer...")
|
| 153 |
+
|
| 154 |
+
# self_attn 확인
|
| 155 |
+
if hasattr(first_layer, 'self_attn'):
|
| 156 |
+
analysis['has_self_attn'] = True
|
| 157 |
+
attn = first_layer.self_attn
|
| 158 |
+
|
| 159 |
+
print(f" ✅ Has self_attn")
|
| 160 |
+
print(f" Attention class: {attn.__class__.__name__}")
|
| 161 |
+
|
| 162 |
+
analysis['attention_type'] = attn.__class__.__name__
|
| 163 |
+
|
| 164 |
+
# Q, K, V projection 확인
|
| 165 |
+
if hasattr(attn, 'q_proj'):
|
| 166 |
+
q_shape = attn.q_proj.weight.shape
|
| 167 |
+
k_shape = attn.k_proj.weight.shape
|
| 168 |
+
v_shape = attn.v_proj.weight.shape
|
| 169 |
+
|
| 170 |
+
print(f" Q projection: {q_shape}")
|
| 171 |
+
print(f" K projection: {k_shape}")
|
| 172 |
+
print(f" V projection: {v_shape}")
|
| 173 |
+
|
| 174 |
+
# GQA 감지
|
| 175 |
+
if k_shape[0] != q_shape[0]:
|
| 176 |
+
print(f" ✅ GQA detected! (K/V heads < Q heads)")
|
| 177 |
+
analysis['gqa_detected'] = True
|
| 178 |
+
else:
|
| 179 |
+
print(f" Standard MHA (K/V heads == Q heads)")
|
| 180 |
+
analysis['gqa_detected'] = False
|
| 181 |
+
|
| 182 |
+
analysis['q_dim'] = q_shape[0]
|
| 183 |
+
analysis['k_dim'] = k_shape[0]
|
| 184 |
+
analysis['v_dim'] = v_shape[0]
|
| 185 |
+
|
| 186 |
+
else:
|
| 187 |
+
print(f" ⚠️ No self_attn found in layer")
|
| 188 |
+
analysis['has_self_attn'] = False
|
| 189 |
+
|
| 190 |
+
# 구조 요약
|
| 191 |
+
print(f"\n{'='*80}")
|
| 192 |
+
print(f"📊 STRUCTURE ANALYSIS COMPLETE")
|
| 193 |
+
print(f"{'='*80}")
|
| 194 |
+
print(f"Model Type: {analysis['model_type']}")
|
| 195 |
+
print(f"Architecture: {analysis['architectures']}")
|
| 196 |
+
print(f"Total Layers: {analysis['total_layers']}")
|
| 197 |
+
print(f"Layer Path: {analysis['layer_path']}")
|
| 198 |
+
print(f"Has self_attn: {analysis['has_self_attn']}")
|
| 199 |
+
print(f"Attention Type: {analysis['attention_type']}")
|
| 200 |
+
|
| 201 |
+
if analysis.get('gqa_detected'):
|
| 202 |
+
print(f"✅ GQA Support: YES")
|
| 203 |
+
print(f" Q dim: {analysis.get('q_dim')}")
|
| 204 |
+
print(f" K dim: {analysis.get('k_dim')}")
|
| 205 |
+
else:
|
| 206 |
+
print(f"Standard MHA")
|
| 207 |
+
|
| 208 |
+
print(f"{'='*80}\n")
|
| 209 |
+
|
| 210 |
+
# 메모리 정리
|
| 211 |
+
del model
|
| 212 |
+
torch.cuda.empty_cache()
|
| 213 |
+
|
| 214 |
+
return analysis
|
| 215 |
+
|
| 216 |
+
except Exception as e:
|
| 217 |
+
import traceback
|
| 218 |
+
error_msg = traceback.format_exc()
|
| 219 |
+
print(f"\n❌ Structure analysis failed:")
|
| 220 |
+
print(error_msg)
|
| 221 |
+
|
| 222 |
+
return {
|
| 223 |
+
'model_url': model_url,
|
| 224 |
+
'error': str(e),
|
| 225 |
+
'traceback': error_msg,
|
| 226 |
+
'total_layers': 0,
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
# =====================================================
|
| 231 |
# PHOENIX Retention with GQA Support
|
| 232 |
# =====================================================
|
|
|
|
| 521 |
|
| 522 |
|
| 523 |
# =====================================================
|
| 524 |
+
# 모델 변환 함수 (개선됨)
|
| 525 |
# =====================================================
|
| 526 |
|
| 527 |
+
def replace_attention_with_retention(model, use_hierarchical=True, structure_info=None):
|
| 528 |
+
"""
|
| 529 |
+
Transformer Attention → PHOENIX Retention (GQA Support)
|
| 530 |
+
structure_info를 활용하여 더 정확한 변환 수행
|
| 531 |
+
"""
|
| 532 |
print("🔄 Starting Attention → Retention conversion (GQA support)...")
|
| 533 |
|
| 534 |
replaced_count = 0
|
| 535 |
total_layers = 0
|
| 536 |
|
| 537 |
+
# structure_info 활용
|
| 538 |
+
if structure_info and structure_info.get('layer_path'):
|
| 539 |
+
layer_path = structure_info['layer_path']
|
| 540 |
+
print(f" Using structure info: {layer_path}")
|
| 541 |
+
|
| 542 |
+
if layer_path == 'model.layers':
|
| 543 |
+
layers = model.model.layers if hasattr(model, 'model') and hasattr(model.model, 'layers') else None
|
| 544 |
+
elif layer_path == 'transformer.h':
|
| 545 |
+
layers = model.transformer.h if hasattr(model, 'transformer') and hasattr(model.transformer, 'h') else None
|
| 546 |
+
elif layer_path == 'layers':
|
| 547 |
+
layers = model.layers if hasattr(model, 'layers') else None
|
| 548 |
+
elif layer_path == 'model.decoder.layers':
|
| 549 |
+
layers = model.model.decoder.layers if hasattr(model, 'model') and hasattr(model.model, 'decoder') and hasattr(model.model.decoder, 'layers') else None
|
| 550 |
+
else:
|
| 551 |
+
layers = None
|
| 552 |
else:
|
| 553 |
+
# 기존 방식대로 탐색
|
| 554 |
+
if hasattr(model, 'transformer'):
|
| 555 |
+
layers = model.transformer.h
|
| 556 |
+
elif hasattr(model, 'model') and hasattr(model.model, 'layers'):
|
| 557 |
+
layers = model.model.layers
|
| 558 |
+
elif hasattr(model, 'layers'):
|
| 559 |
+
layers = model.layers
|
| 560 |
+
else:
|
| 561 |
+
layers = None
|
| 562 |
+
|
| 563 |
+
if layers is None:
|
| 564 |
+
print("⚠️ Unknown model structure - cannot find layers")
|
| 565 |
return model, 0, 0
|
| 566 |
|
| 567 |
total_layers = len(layers)
|
| 568 |
+
print(f" Found {total_layers} layers")
|
| 569 |
+
|
| 570 |
+
# GQA 감지 (structure_info 우선)
|
| 571 |
+
if structure_info and structure_info.get('gqa_detected'):
|
| 572 |
+
print(f" ✅ GQA detected from structure info")
|
| 573 |
+
if not hasattr(model.config, 'num_key_value_heads'):
|
| 574 |
+
num_kv_heads = structure_info.get('k_dim', 0) // (model.config.hidden_size // model.config.num_attention_heads)
|
| 575 |
+
if num_kv_heads > 0:
|
| 576 |
+
model.config.num_key_value_heads = num_kv_heads
|
| 577 |
+
print(f" Set num_key_value_heads = {num_kv_heads}")
|
| 578 |
+
else:
|
| 579 |
+
# 첫 레이어에서 GQA 확인
|
| 580 |
+
first_layer = layers[0]
|
| 581 |
+
if hasattr(first_layer, 'self_attn'):
|
| 582 |
+
old_attn = first_layer.self_attn
|
| 583 |
|
| 584 |
+
if hasattr(old_attn, 'q_proj'):
|
| 585 |
+
q_shape = old_attn.q_proj.weight.shape
|
| 586 |
+
k_shape = old_attn.k_proj.weight.shape
|
| 587 |
+
|
| 588 |
+
if k_shape[0] != q_shape[0]:
|
| 589 |
+
print(f" ✅ GQA detected! (K/V dim: {k_shape[0]} < Q dim: {q_shape[0]})")
|
| 590 |
+
if not hasattr(model.config, 'num_key_value_heads'):
|
| 591 |
+
num_kv_heads = k_shape[0] // (model.config.hidden_size // model.config.num_attention_heads)
|
| 592 |
+
model.config.num_key_value_heads = num_kv_heads
|
| 593 |
|
| 594 |
+
# 레이어별 변환
|
| 595 |
for layer_idx, layer in enumerate(layers):
|
| 596 |
try:
|
| 597 |
if hasattr(layer, 'self_attn'):
|
|
|
|
| 688 |
def __init__(
|
| 689 |
self,
|
| 690 |
use_phoenix_retention=True,
|
| 691 |
+
phoenix_version="1.2.0",
|
| 692 |
original_architecture=None,
|
| 693 |
**kwargs
|
| 694 |
):
|
|
|
|
| 765 |
if past_key_values is not None:
|
| 766 |
past_key_value = past_key_values
|
| 767 |
|
|
|
|
| 768 |
target_device = hidden_states.device
|
| 769 |
target_dtype = hidden_states.dtype
|
| 770 |
|
|
|
|
| 898 |
target_device = hidden_states.device
|
| 899 |
target_dtype = hidden_states.dtype
|
| 900 |
|
|
|
|
| 901 |
current_device = next(self.short_proj.parameters()).device
|
| 902 |
current_dtype = next(self.short_proj.parameters()).dtype
|
| 903 |
|
|
|
|
| 963 |
else:
|
| 964 |
new_retention = MultiScaleRetention(config, layer_idx)
|
| 965 |
|
|
|
|
| 966 |
if hasattr(old_attn, 'q_proj'):
|
| 967 |
try:
|
| 968 |
target = new_retention.base_retention if use_hierarchical else new_retention
|
|
|
|
| 1004 |
|
| 1005 |
|
| 1006 |
class PhoenixModelForCausalLM(PhoenixPreTrainedModel):
|
| 1007 |
+
"""PHOENIX Model for Causal Language Modeling"""
|
|
|
|
|
|
|
|
|
|
| 1008 |
|
| 1009 |
def __init__(self, config):
|
| 1010 |
super().__init__(config)
|
|
|
|
| 1014 |
|
| 1015 |
@classmethod
|
| 1016 |
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1017 |
+
"""🔥 PHOENIX 자동 로딩!"""
|
|
|
|
|
|
|
|
|
|
| 1018 |
from pathlib import Path
|
| 1019 |
import json
|
| 1020 |
|
| 1021 |
print(f"🔥 Loading PHOENIX model from {pretrained_model_name_or_path}")
|
| 1022 |
|
|
|
|
| 1023 |
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
|
| 1024 |
|
|
|
|
| 1025 |
original_arch = config.architectures[0] if hasattr(config, 'architectures') else 'AutoModelForCausalLM'
|
| 1026 |
|
|
|
|
| 1027 |
base_kwargs = kwargs.copy()
|
| 1028 |
+
base_kwargs.pop('trust_remote_code', None)
|
| 1029 |
|
|
|
|
| 1030 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 1031 |
pretrained_model_name_or_path,
|
| 1032 |
*model_args,
|
|
|
|
| 1035 |
|
| 1036 |
print(f" ✅ Base model loaded: {original_arch}")
|
| 1037 |
|
|
|
|
| 1038 |
use_hierarchical = config.use_hierarchical if hasattr(config, 'use_hierarchical') else True
|
| 1039 |
|
| 1040 |
print(f"🔄 Converting to PHOENIX Retention...")
|
|
|
|
| 1042 |
|
| 1043 |
print(f"✅ Converted {converted}/{total} layers to Retention")
|
| 1044 |
|
|
|
|
| 1045 |
phoenix_instance = cls(config)
|
| 1046 |
phoenix_instance._original_model = base_model
|
| 1047 |
phoenix_instance._initialized = True
|
|
|
|
| 1051 |
return phoenix_instance
|
| 1052 |
|
| 1053 |
def forward(self, *args, **kwargs):
|
|
|
|
| 1054 |
if not self._initialized or self._original_model is None:
|
| 1055 |
raise ValueError("Model not properly initialized. Use from_pretrained().")
|
| 1056 |
return self._original_model(*args, **kwargs)
|
| 1057 |
|
| 1058 |
def generate(self, *args, **kwargs):
|
|
|
|
| 1059 |
if not self._initialized or self._original_model is None:
|
| 1060 |
raise ValueError("Model not properly initialized. Use from_pretrained().")
|
| 1061 |
return self._original_model.generate(*args, **kwargs)
|
| 1062 |
|
| 1063 |
def prepare_inputs_for_generation(self, *args, **kwargs):
|
|
|
|
| 1064 |
if self._original_model is None:
|
| 1065 |
raise ValueError("Model not initialized.")
|
| 1066 |
if hasattr(self._original_model, 'prepare_inputs_for_generation'):
|
|
|
|
| 1080 |
# =====================================================
|
| 1081 |
|
| 1082 |
def save_phoenix_model_with_code(model, tokenizer, output_path, original_model_url, metadata):
|
| 1083 |
+
"""PHOENIX 모델을 Custom Code와 함께 저장"""
|
|
|
|
|
|
|
|
|
|
| 1084 |
output_path = Path(output_path)
|
| 1085 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 1086 |
|
|
|
|
| 1105 |
|
| 1106 |
# PHOENIX 마커 추가
|
| 1107 |
config_dict["use_phoenix_retention"] = True
|
| 1108 |
+
config_dict["phoenix_version"] = "1.2.0"
|
| 1109 |
config_dict["original_model"] = original_model_url
|
| 1110 |
config_dict["use_hierarchical"] = metadata.get('use_hierarchical', True)
|
| 1111 |
|
|
|
|
| 1135 |
pipeline_tag: text-generation
|
| 1136 |
---
|
| 1137 |
|
| 1138 |
+
# 🔥 PHOENIX Retention Model v1.2
|
| 1139 |
|
| 1140 |
This model has been converted from [{original_model_url}]({original_model_url}) using PHOENIX Retention mechanism.
|
| 1141 |
|
| 1142 |
## Model Information
|
| 1143 |
|
| 1144 |
- **Original Model**: {original_model_url}
|
| 1145 |
+
- **PHOENIX Version**: {metadata.get('phoenix_version', '1.2.0')}
|
| 1146 |
- **Conversion Rate**: {metadata.get('conversion_rate', 0)*100:.1f}%
|
| 1147 |
- **Quality Score**: {metadata.get('quality_score', 0):.2f}/1.00
|
| 1148 |
- **Burning Type**: {metadata.get('burning_type', 'zero_shot')}
|
|
|
|
| 1198 |
- **Memory Efficiency**: Linear memory scaling
|
| 1199 |
- **Quality**: {metadata.get('quality_score', 0):.2f}/1.00
|
| 1200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1201 |
## Citation
|
| 1202 |
```bibtex
|
| 1203 |
@software{{phoenix_retention,
|
|
|
|
| 1205 |
author = {{VIDraft AI Research Lab}},
|
| 1206 |
year = {{2025}},
|
| 1207 |
url = {{https://github.com/vidraft}},
|
| 1208 |
+
version = {{{metadata.get('phoenix_version', '1.2.0')}}}
|
| 1209 |
}}
|
| 1210 |
```
|
| 1211 |
|
|
|
|
| 1213 |
|
| 1214 |
Apache 2.0 (inherited from original model)
|
| 1215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1216 |
---
|
| 1217 |
|
| 1218 |
**VIDraft AI Research Lab** | Powered by PHOENIX 🔥
|
|
|
|
|
|
|
| 1219 |
"""
|
| 1220 |
|
| 1221 |
with open(output_path / "README.md", "w", encoding='utf-8') as f:
|
|
|
|
| 1224 |
|
| 1225 |
print(f"\n✅ PHOENIX model package complete!")
|
| 1226 |
print(f" 📦 Location: {output_path}")
|
|
|
|
|
|
|
| 1227 |
|
| 1228 |
|
| 1229 |
# =====================================================
|
|
|
|
| 1231 |
# =====================================================
|
| 1232 |
|
| 1233 |
def verify_phoenix_model_before_upload(model_path: str) -> Tuple[bool, str, Dict]:
|
| 1234 |
+
"""Upload 전 PHOENIX 모델 검증"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1235 |
print("\n🧪 Pre-upload Verification...")
|
| 1236 |
|
| 1237 |
try:
|
| 1238 |
model_path = Path(model_path)
|
| 1239 |
|
|
|
|
| 1240 |
file_checks = {
|
| 1241 |
'config': (model_path / 'config.json').exists(),
|
| 1242 |
'modeling': (model_path / 'modeling_phoenix.py').exists(),
|
|
|
|
| 1264 |
|
| 1265 |
print(" ✅ All required files present")
|
| 1266 |
|
|
|
|
| 1267 |
with open(model_path / 'config.json', 'r') as f:
|
| 1268 |
config = json.load(f)
|
| 1269 |
|
|
|
|
| 1275 |
|
| 1276 |
print(" ✅ Config validated")
|
| 1277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1278 |
metrics = {
|
| 1279 |
+
'retention_layers': -1,
|
| 1280 |
+
'total_layers': -1,
|
| 1281 |
+
'retention_rate': 1.0,
|
| 1282 |
+
'generation_quality': 0.8,
|
| 1283 |
'model_format': 'safetensors' if file_checks['safetensors'] else 'pytorch_bin',
|
| 1284 |
+
'verification_mode': 'file_only'
|
| 1285 |
}
|
| 1286 |
|
| 1287 |
+
print(" ✅ File-based verification passed")
|
|
|
|
| 1288 |
return True, "✅ All checks passed", metrics
|
| 1289 |
|
| 1290 |
except Exception as e:
|
| 1291 |
import traceback
|
| 1292 |
error_msg = traceback.format_exc()
|
| 1293 |
|
| 1294 |
+
return False, f"❌ Verification failed: {str(e)}\n{error_msg}", {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1295 |
|
| 1296 |
|
| 1297 |
# =====================================================
|
|
|
|
| 1312 |
print("📤 HUGGINGFACE HUB UPLOAD")
|
| 1313 |
print("="*80)
|
| 1314 |
|
|
|
|
| 1315 |
if token is None:
|
| 1316 |
token = HF_TOKEN
|
| 1317 |
|
|
|
|
| 1322 |
|
| 1323 |
print(f"✅ HF_TOKEN found: {'*' * 10}{token[-4:]}")
|
| 1324 |
|
|
|
|
| 1325 |
model_path = Path(model_path)
|
| 1326 |
if not model_path.exists():
|
| 1327 |
error_msg = f"❌ Model path not found: {model_path}"
|
|
|
|
| 1330 |
|
| 1331 |
print(f"✅ Model path verified: {model_path}")
|
| 1332 |
|
|
|
|
| 1333 |
if not skip_verification:
|
| 1334 |
print("\n🔍 Running pre-upload verification...")
|
| 1335 |
success, message, metrics = verify_phoenix_model_before_upload(str(model_path))
|
|
|
|
| 1337 |
if not success:
|
| 1338 |
error_msg = f"❌ Pre-upload verification failed:\n{message}"
|
| 1339 |
print(f"\n{error_msg}")
|
|
|
|
| 1340 |
return False, "", error_msg
|
| 1341 |
|
| 1342 |
print(f"✅ Pre-upload verification PASSED!")
|
|
|
|
|
|
|
|
|
|
| 1343 |
else:
|
| 1344 |
print("\n⚠️ Skipping pre-upload verification")
|
| 1345 |
|
| 1346 |
try:
|
|
|
|
| 1347 |
print("\n🔐 Authenticating with HuggingFace...")
|
| 1348 |
api = HfApi(token=token)
|
| 1349 |
|
|
|
|
| 1356 |
print(f"\n{error_msg}")
|
| 1357 |
return False, "", error_msg
|
| 1358 |
|
|
|
|
| 1359 |
if not repo_name:
|
| 1360 |
base_name = original_model_url.split('/')[-1]
|
| 1361 |
repo_name = f"phoenix-{base_name}"
|
|
|
|
| 1365 |
print(f"\n📦 Repository Configuration:")
|
| 1366 |
print(f" Repo ID: {repo_id}")
|
| 1367 |
print(f" Private: {private}")
|
|
|
|
| 1368 |
|
|
|
|
| 1369 |
print(f"\n🏗️ Creating/verifying repository...")
|
| 1370 |
try:
|
| 1371 |
create_repo(
|
|
|
|
| 1378 |
print(f"✅ Repository ready: {repo_id}")
|
| 1379 |
except Exception as e:
|
| 1380 |
print(f"⚠️ Repository creation warning: {str(e)}")
|
|
|
|
| 1381 |
|
|
|
|
| 1382 |
print(f"\n📤 Uploading files to HuggingFace Hub...")
|
|
|
|
| 1383 |
|
| 1384 |
try:
|
| 1385 |
api.upload_folder(
|
|
|
|
| 1399 |
print(f"✅ UPLOAD SUCCESSFUL!")
|
| 1400 |
print(f"{'='*80}")
|
| 1401 |
print(f"🔗 Model URL: {hub_url}")
|
|
|
|
|
|
|
| 1402 |
print(f"{'='*80}\n")
|
| 1403 |
|
| 1404 |
success_msg = f"✅ Successfully uploaded to {hub_url}"
|
|
|
|
| 1481 |
cursor.execute("ALTER TABLE burning_history ADD COLUMN verification_passed BOOLEAN DEFAULT 0")
|
| 1482 |
|
| 1483 |
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1484 |
|
| 1485 |
def save_burning(self, burning_info: Dict) -> int:
|
| 1486 |
with sqlite3.connect(self.db_path) as conn:
|
|
|
|
| 1564 |
use_hierarchical: bool = True,
|
| 1565 |
test_prompts: List[str] = None,
|
| 1566 |
):
|
| 1567 |
+
"""Zero-shot Model Burning with Structure Analysis"""
|
| 1568 |
print("="*80)
|
| 1569 |
+
print("🔥 PHOENIX Zero-shot Model Burning v1.2")
|
| 1570 |
print("="*80)
|
| 1571 |
|
| 1572 |
output_path = Path(output_dir)
|
| 1573 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 1574 |
|
| 1575 |
try:
|
| 1576 |
+
# 1. 구조 분석 (NEW!)
|
| 1577 |
+
print(f"\n🔍 STEP 1: Model Structure Analysis...")
|
| 1578 |
+
structure_info = analyze_model_structure(model_url)
|
| 1579 |
+
|
| 1580 |
+
if structure_info.get('error'):
|
| 1581 |
+
print(f"⚠️ Structure analysis failed, continuing anyway...")
|
| 1582 |
+
structure_info = None
|
| 1583 |
+
elif structure_info.get('total_layers', 0) == 0:
|
| 1584 |
+
print(f"⚠️ No layers detected, this may fail...")
|
| 1585 |
+
|
| 1586 |
+
# 2. 모델 로드
|
| 1587 |
+
print(f"\n📥 STEP 2: Loading model for conversion...")
|
| 1588 |
start_time = time.time()
|
| 1589 |
|
| 1590 |
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
|
|
|
| 1601 |
load_time = time.time() - start_time
|
| 1602 |
print(f"✅ Loaded in {load_time:.1f}s")
|
| 1603 |
|
| 1604 |
+
# 3. 변환 (구조 정보 활용)
|
| 1605 |
+
print(f"\n🔄 STEP 3: Converting Attention → Retention...")
|
| 1606 |
convert_start = time.time()
|
| 1607 |
|
| 1608 |
model.model, converted, total = replace_attention_with_retention(
|
| 1609 |
model.model,
|
| 1610 |
+
use_hierarchical=use_hierarchical,
|
| 1611 |
+
structure_info=structure_info
|
| 1612 |
)
|
| 1613 |
|
| 1614 |
convert_time = time.time() - convert_start
|
|
|
|
| 1616 |
|
| 1617 |
print(f"✅ Converted {converted}/{total} layers ({conversion_rate*100:.1f}%) in {convert_time:.1f}s")
|
| 1618 |
|
| 1619 |
+
if converted == 0:
|
| 1620 |
+
print(f"\n⚠️ WARNING: No layers were converted!")
|
| 1621 |
+
print(f" This model may not work correctly.")
|
| 1622 |
+
print(f" Structure info: {structure_info}")
|
| 1623 |
+
|
| 1624 |
+
# 4. 평가
|
| 1625 |
+
print(f"\n📊 STEP 4: Evaluating model quality...")
|
| 1626 |
eval_start = time.time()
|
| 1627 |
|
| 1628 |
quality_score = evaluate_model_quality(model, tokenizer, test_prompts)
|
|
|
|
| 1630 |
eval_time = time.time() - eval_start
|
| 1631 |
print(f"✅ Quality Score: {quality_score:.2f}/1.00 (in {eval_time:.1f}s)")
|
| 1632 |
|
| 1633 |
+
# 5. 저장
|
| 1634 |
+
print(f"\n💾 STEP 5: Saving PHOENIX model with custom code...")
|
| 1635 |
save_start = time.time()
|
| 1636 |
|
| 1637 |
metadata = {
|
| 1638 |
+
'phoenix_version': '1.2.0',
|
| 1639 |
'original_model': model_url,
|
| 1640 |
'use_hierarchical': use_hierarchical,
|
| 1641 |
'conversion_rate': conversion_rate,
|
|
|
|
| 1643 |
'total_layers': total,
|
| 1644 |
'quality_score': quality_score,
|
| 1645 |
'burning_type': 'zero_shot',
|
| 1646 |
+
'structure_info': structure_info,
|
| 1647 |
'timestamp': datetime.now().isoformat(),
|
| 1648 |
}
|
| 1649 |
|
|
|
|
| 1664 |
'convert_time': convert_time,
|
| 1665 |
'eval_time': eval_time,
|
| 1666 |
'save_time': save_time,
|
| 1667 |
+
'structure_info': structure_info,
|
| 1668 |
}
|
| 1669 |
|
| 1670 |
print(f"\n{'='*80}")
|
|
|
|
| 1672 |
print(f" Total Time: {total_time:.1f}s")
|
| 1673 |
print(f" Model Path: {output_path}")
|
| 1674 |
print(f" Quality: {quality_score:.2f}/1.00")
|
| 1675 |
+
print(f" Conversion: {converted}/{total} layers")
|
| 1676 |
print(f"{'='*80}\n")
|
| 1677 |
|
| 1678 |
return result
|
|
|
|
| 1698 |
learning_rate: float = 5e-5,
|
| 1699 |
max_steps: int = 100,
|
| 1700 |
):
|
| 1701 |
+
"""Fine-tuning Model Burning with Structure Analysis"""
|
| 1702 |
print("="*80)
|
| 1703 |
+
print("🔥 PHOENIX Fine-tuning Model Burning v1.2")
|
| 1704 |
print("="*80)
|
| 1705 |
|
| 1706 |
output_path = Path(output_dir)
|
| 1707 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 1708 |
|
| 1709 |
try:
|
| 1710 |
+
# 1. 구조 분석
|
| 1711 |
+
print(f"\n🔍 STEP 1: Model Structure Analysis...")
|
| 1712 |
+
structure_info = analyze_model_structure(model_url)
|
| 1713 |
+
|
| 1714 |
+
# 2. 로드 & 변환
|
| 1715 |
+
print(f"\n📥 STEP 2: Loading model...")
|
| 1716 |
config = AutoConfig.from_pretrained(model_url, trust_remote_code=True)
|
| 1717 |
model = AutoModelForCausalLM.from_pretrained(
|
| 1718 |
model_url,
|
|
|
|
| 1724 |
if tokenizer.pad_token is None:
|
| 1725 |
tokenizer.pad_token = tokenizer.eos_token
|
| 1726 |
|
| 1727 |
+
print(f"\n🔄 STEP 3: Converting...")
|
| 1728 |
model.model, converted, total = replace_attention_with_retention(
|
| 1729 |
model.model,
|
| 1730 |
+
use_hierarchical=use_hierarchical,
|
| 1731 |
+
structure_info=structure_info
|
| 1732 |
)
|
| 1733 |
|
| 1734 |
conversion_rate = converted / total if total > 0 else 0
|
| 1735 |
print(f"✅ Converted {converted}/{total} layers")
|
| 1736 |
|
| 1737 |
+
# 3. 데이터셋 로드
|
| 1738 |
+
print(f"\n📊 STEP 4: Loading dataset: {dataset_path}")
|
| 1739 |
|
| 1740 |
if dataset_path.endswith('.txt'):
|
| 1741 |
with open(dataset_path, 'r', encoding='utf-8') as f:
|
|
|
|
| 1767 |
|
| 1768 |
print(f"✅ Loaded {len(tokenized_data)} samples")
|
| 1769 |
|
| 1770 |
+
# 4. Fine-tuning
|
| 1771 |
+
print(f"\n🚀 STEP 5: Starting fine-tuning...")
|
| 1772 |
model.train()
|
| 1773 |
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
|
| 1774 |
|
|
|
|
| 1805 |
final_loss = total_loss / step if step > 0 else 0.0
|
| 1806 |
print(f"✅ Training complete - Final Loss: {final_loss:.4f}")
|
| 1807 |
|
| 1808 |
+
# 5. 평가 & 저장
|
| 1809 |
model.eval()
|
| 1810 |
quality_score = evaluate_model_quality(model, tokenizer)
|
| 1811 |
|
| 1812 |
metadata = {
|
| 1813 |
+
'phoenix_version': '1.2.0',
|
| 1814 |
'original_model': model_url,
|
| 1815 |
'use_hierarchical': use_hierarchical,
|
| 1816 |
'conversion_rate': conversion_rate,
|
|
|
|
| 1819 |
'training_steps': step,
|
| 1820 |
'final_loss': final_loss,
|
| 1821 |
'dataset': dataset_path,
|
| 1822 |
+
'structure_info': structure_info,
|
| 1823 |
'timestamp': datetime.now().isoformat(),
|
| 1824 |
}
|
| 1825 |
|
|
|
|
| 1832 |
'quality_score': quality_score,
|
| 1833 |
'training_steps': step,
|
| 1834 |
'final_loss': final_loss,
|
| 1835 |
+
'structure_info': structure_info,
|
| 1836 |
}
|
| 1837 |
|
| 1838 |
return result
|
|
|
|
| 1852 |
# Gradio UI Functions
|
| 1853 |
# =====================================================
|
| 1854 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1855 |
def burn_phoenix_model_ui(
|
| 1856 |
model_url,
|
| 1857 |
use_hierarchical,
|
|
|
|
| 1869 |
"""Gradio UI용 모델 버닝 함수"""
|
| 1870 |
|
| 1871 |
print("\n" + "="*80)
|
| 1872 |
+
print("🔥 PHOENIX MODEL BURNING START v1.2")
|
| 1873 |
print("="*80)
|
| 1874 |
|
| 1875 |
try:
|
|
|
|
| 1876 |
if not model_url.strip():
|
| 1877 |
return "⚠️ Model URL is required", None
|
| 1878 |
|
|
|
|
| 1884 |
print(f"📋 Configuration:")
|
| 1885 |
print(f" Model URL: {model_url}")
|
| 1886 |
print(f" Output Name: {output_name}")
|
|
|
|
| 1887 |
print(f" Hierarchical: {use_hierarchical}")
|
| 1888 |
print(f" Upload to Hub: {upload_to_hub}")
|
| 1889 |
|
|
|
|
| 1892 |
if use_finetuning and not has_dataset:
|
| 1893 |
return "⚠️ Fine-tuning requires a valid dataset path", None
|
| 1894 |
|
|
|
|
| 1895 |
if upload_to_hub and not HF_TOKEN:
|
| 1896 |
+
warning_msg = "⚠️ HuggingFace Token Not Found! Continuing with local burning only..."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1897 |
print(f"\n{warning_msg}")
|
| 1898 |
|
| 1899 |
# Burning 실행
|
|
|
|
| 1919 |
)
|
| 1920 |
|
| 1921 |
if result['status'] != 'success':
|
| 1922 |
+
error_msg = f"❌ Burning Failed\n```\n{result.get('error', 'Unknown error')}\n```"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1923 |
return error_msg, None
|
| 1924 |
|
| 1925 |
print(f"\n✅ Burning completed successfully!")
|
|
|
|
| 1932 |
if upload_to_hub:
|
| 1933 |
if not HF_TOKEN:
|
| 1934 |
upload_status = "❌ Failed - No HF_TOKEN"
|
|
|
|
| 1935 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1936 |
success, hub_url, upload_msg = upload_to_huggingface_hub(
|
| 1937 |
model_path=result['model_path'],
|
| 1938 |
original_model_url=model_url,
|
|
|
|
| 1942 |
)
|
| 1943 |
|
| 1944 |
verification_passed = success
|
| 1945 |
+
upload_status = f"✅ Uploaded to {hub_url}" if success else f"❌ Upload failed"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1946 |
else:
|
| 1947 |
+
upload_status = "⏭️ Skipped"
|
|
|
|
| 1948 |
|
| 1949 |
# 데이터베이스 저장
|
| 1950 |
burning_info = {
|
|
|
|
| 1961 |
}
|
| 1962 |
|
| 1963 |
db.save_burning(burning_info)
|
|
|
|
| 1964 |
|
| 1965 |
# 결과 포맷팅
|
| 1966 |
+
structure_info = result.get('structure_info', {})
|
| 1967 |
+
|
| 1968 |
output_md = f"""
|
| 1969 |
+
# 🔥 Model Burning Complete! (v1.2)
|
| 1970 |
+
|
| 1971 |
+
## 🔍 Structure Analysis
|
| 1972 |
+
- **Model Type**: {structure_info.get('model_type', 'unknown')}
|
| 1973 |
+
- **Architecture**: {structure_info.get('architectures', 'unknown')}
|
| 1974 |
+
- **Total Layers**: {structure_info.get('total_layers', 0)}
|
| 1975 |
+
- **Layer Path**: {structure_info.get('layer_path', 'unknown')}
|
| 1976 |
+
- **Has self_attn**: {structure_info.get('has_self_attn', False)}
|
| 1977 |
+
- **GQA Detected**: {structure_info.get('gqa_detected', False)}
|
| 1978 |
|
| 1979 |
## 📦 Model Information
|
| 1980 |
- **Original Model**: {model_url}
|
|
|
|
| 2005 |
output_md += f"- **Evaluate**: {result['eval_time']:.1f}s\n"
|
| 2006 |
output_md += f"- **Save**: {result['save_time']:.1f}s\n"
|
| 2007 |
|
|
|
|
| 2008 |
output_md += f"""
|
| 2009 |
---
|
| 2010 |
|
|
|
|
| 2016 |
if hub_url:
|
| 2017 |
output_md += f"""
|
| 2018 |
**Model URL**: [{hub_url}]({hub_url})
|
|
|
|
|
|
|
| 2019 |
|
| 2020 |
### 🚀 Load from Hub
|
| 2021 |
```python
|
| 2022 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2023 |
|
|
|
|
| 2024 |
model = AutoModelForCausalLM.from_pretrained(
|
| 2025 |
"{hub_url.replace('https://huggingface.co/', '')}",
|
| 2026 |
+
trust_remote_code=True,
|
| 2027 |
torch_dtype="auto",
|
| 2028 |
device_map="auto"
|
| 2029 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2030 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2031 |
"""
|
| 2032 |
|
| 2033 |
output_md += f"""
|
| 2034 |
---
|
| 2035 |
|
| 2036 |
+
✅ **PHOENIX Model Ready! (v1.2)**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2037 |
"""
|
| 2038 |
|
| 2039 |
+
# 플롯
|
| 2040 |
fig = go.Figure()
|
| 2041 |
|
| 2042 |
metrics_names = ['Conversion', 'Quality']
|
| 2043 |
metrics_values = [result.get('conversion_rate', 0), result.get('quality_score', 0)]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2044 |
|
| 2045 |
if verification_passed:
|
| 2046 |
metrics_names.append('Upload')
|
| 2047 |
metrics_values.append(1.0)
|
|
|
|
| 2048 |
|
| 2049 |
fig.add_trace(go.Bar(
|
| 2050 |
x=metrics_names,
|
| 2051 |
y=metrics_values,
|
|
|
|
|
|
|
| 2052 |
marker_color=['#3b82f6', '#10b981', '#8b5cf6'][:len(metrics_names)]
|
| 2053 |
))
|
| 2054 |
|
|
|
|
| 2059 |
height=400
|
| 2060 |
)
|
| 2061 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2062 |
return output_md, fig
|
| 2063 |
|
| 2064 |
except Exception as e:
|
| 2065 |
import traceback
|
| 2066 |
error_msg = traceback.format_exc()
|
| 2067 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2068 |
return f"""
|
| 2069 |
❌ **Burning Failed**
|
| 2070 |
|
| 2071 |
**Error:** {str(e)}
|
| 2072 |
|
| 2073 |
+
**Traceback:**
|
| 2074 |
```
|
| 2075 |
{error_msg}
|
| 2076 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2077 |
""", None
|
| 2078 |
|
| 2079 |
|
|
|
|
| 2094 |
size='conversion_rate',
|
| 2095 |
color='verification_passed',
|
| 2096 |
hover_data=['model_url', 'output_path', 'hub_url'],
|
| 2097 |
+
title='Burning History'
|
| 2098 |
)
|
| 2099 |
|
| 2100 |
cols = ['id', 'model_url', 'hub_url', 'conversion_rate',
|
|
|
|
| 2118 |
"""PHOENIX 모델 검증"""
|
| 2119 |
try:
|
| 2120 |
print("="*80)
|
| 2121 |
+
print("🧪 PHOENIX Model Validation v1.2")
|
| 2122 |
print("="*80)
|
| 2123 |
|
| 2124 |
# 1. 모델 로드
|
|
|
|
| 2142 |
load_time = time.time() - start_time
|
| 2143 |
print(f"✅ Model loaded in {load_time:.2f}s")
|
| 2144 |
|
| 2145 |
+
# 2. 메타데이터
|
| 2146 |
metadata = {}
|
| 2147 |
metadata_path = None
|
| 2148 |
|
|
|
|
| 2161 |
if metadata_path and Path(metadata_path).exists():
|
| 2162 |
with open(metadata_path, 'r') as f:
|
| 2163 |
metadata = json.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2164 |
|
| 2165 |
# 3. Retention 검증
|
| 2166 |
retention_info = ""
|
|
|
|
| 2192 |
"""
|
| 2193 |
print(f" Retention: {retention_count}/{total} layers")
|
| 2194 |
|
| 2195 |
+
# 4. 생성 테스트
|
| 2196 |
print(f"\n🚀 Running generation tests...")
|
| 2197 |
|
| 2198 |
prompts = [p.strip() for p in test_prompts.split('\n') if p.strip()]
|
|
|
|
| 2203 |
total_gen_time = 0
|
| 2204 |
|
| 2205 |
for i, prompt in enumerate(prompts, 1):
|
|
|
|
|
|
|
| 2206 |
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 2207 |
|
| 2208 |
gen_start = time.time()
|
|
|
|
| 2231 |
'tokens': tokens_generated,
|
| 2232 |
'tokens_per_sec': tokens_per_sec,
|
| 2233 |
})
|
|
|
|
|
|
|
| 2234 |
|
| 2235 |
+
# 5. 결과
|
| 2236 |
output_md = f"""
|
| 2237 |
+
# ✅ PHOENIX Model Validation Complete! (v1.2)
|
| 2238 |
|
| 2239 |
## 📦 Model Information
|
| 2240 |
- **Source**: {model_source.upper()}
|
| 2241 |
- **Path/URL**: `{model_path_or_url}`
|
| 2242 |
- **Load Time**: {load_time:.2f}s
|
|
|
|
| 2243 |
|
| 2244 |
## 📋 Metadata
|
| 2245 |
"""
|
|
|
|
| 2249 |
- **PHOENIX Version**: {metadata.get('phoenix_version', 'Unknown')}
|
| 2250 |
- **Original Model**: {metadata.get('original_model', 'Unknown')}
|
| 2251 |
- **Conversion Rate**: {metadata.get('conversion_rate', 0)*100:.1f}%
|
|
|
|
|
|
|
| 2252 |
"""
|
|
|
|
|
|
|
| 2253 |
|
| 2254 |
if retention_info:
|
| 2255 |
output_md += retention_info
|
|
|
|
| 2258 |
## 🚀 Generation Tests
|
| 2259 |
|
| 2260 |
**Total Tests**: {len(results)}
|
|
|
|
| 2261 |
**Average Speed**: {sum(r['tokens_per_sec'] for r in results)/len(results):.1f} tokens/s
|
| 2262 |
|
| 2263 |
---
|
|
|
|
| 2265 |
|
| 2266 |
for i, result in enumerate(results, 1):
|
| 2267 |
output_md += f"""
|
| 2268 |
+
### Test {i}
|
| 2269 |
|
| 2270 |
+
**Generated:**
|
| 2271 |
```
|
| 2272 |
{result['generated']}
|
| 2273 |
```
|
| 2274 |
|
| 2275 |
+
**Stats**: {result['time']:.2f}s | {result['tokens_per_sec']:.1f} tokens/s
|
|
|
|
|
|
|
|
|
|
| 2276 |
|
| 2277 |
---
|
| 2278 |
"""
|
|
|
|
| 2281 |
fig = go.Figure()
|
| 2282 |
|
| 2283 |
fig.add_trace(go.Bar(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2284 |
x=[f"Test {i+1}" for i in range(len(results))],
|
| 2285 |
y=[r['tokens_per_sec'] for r in results],
|
| 2286 |
+
marker_color='#10b981'
|
|
|
|
|
|
|
| 2287 |
))
|
| 2288 |
|
| 2289 |
fig.update_layout(
|
| 2290 |
+
title="Generation Speed (tokens/s)",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2291 |
template='plotly_white'
|
| 2292 |
)
|
| 2293 |
|
|
|
|
|
|
|
| 2294 |
return output_md, fig
|
| 2295 |
|
| 2296 |
except Exception as e:
|
| 2297 |
import traceback
|
| 2298 |
+
return f"❌ Validation failed:\n```\n{traceback.format_exc()}\n```", None
|
|
|
|
| 2299 |
|
| 2300 |
|
| 2301 |
# 전역 초기화
|
| 2302 |
db = ExperimentDatabase(DB_PATH)
|
|
|
|
| 2303 |
|
| 2304 |
# =====================================================
|
| 2305 |
# Gradio UI
|
| 2306 |
# =====================================================
|
| 2307 |
|
| 2308 |
with gr.Blocks(
|
| 2309 |
+
title="🔮 PHOENIX v1.2 - Structure-Aware Model Burning",
|
| 2310 |
theme=gr.themes.Soft(),
|
| 2311 |
) as demo:
|
| 2312 |
|
| 2313 |
gr.Markdown("""
|
| 2314 |
+
# 🔮 PHOENIX Retention Platform v1.2
|
| 2315 |
|
| 2316 |
+
**Structure-Aware Model Burning + Auto-Upload + Verification**
|
| 2317 |
|
| 2318 |
+
✅ **NEW!** Model Structure Pre-Analysis
|
| 2319 |
+
✅ **NEW!** Qwen3 Model Support
|
| 2320 |
+
✅ Zero-shot Conversion (No Dataset Required)
|
| 2321 |
+
✅ Optional Fine-tuning
|
| 2322 |
✅ GQA Support
|
| 2323 |
✅ O(n) Complexity
|
| 2324 |
✅ Auto Upload to HuggingFace Hub
|
|
|
|
|
|
|
| 2325 |
|
| 2326 |
---
|
| 2327 |
""")
|
| 2328 |
|
| 2329 |
with gr.Tabs():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2330 |
with gr.Tab("🔥 Model Burning"):
|
| 2331 |
gr.Markdown("""
|
| 2332 |
+
### 🔥 PHOENIX Model Burning v1.2
|
| 2333 |
|
| 2334 |
+
**모델 구조를 먼저 분석한 후 변환합니다!**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2335 |
""")
|
| 2336 |
|
| 2337 |
with gr.Row():
|
|
|
|
| 2339 |
burn_model_url = gr.Textbox(
|
| 2340 |
label="🔗 Model URL",
|
| 2341 |
value=DEFAULT_MODEL,
|
| 2342 |
+
placeholder="Qwen/Qwen3-0.6B"
|
| 2343 |
)
|
| 2344 |
burn_hierarchical = gr.Checkbox(value=True, label="Hierarchical Retention")
|
| 2345 |
|
| 2346 |
burn_output_name = gr.Textbox(
|
| 2347 |
label="💾 Output Name",
|
| 2348 |
+
placeholder="phoenix_my_model"
|
| 2349 |
)
|
| 2350 |
|
| 2351 |
gr.Markdown("---")
|
| 2352 |
gr.Markdown("### 🌐 HuggingFace Hub Upload")
|
| 2353 |
|
| 2354 |
+
burn_upload_hub = gr.Checkbox(value=True, label="📤 Upload to Hub")
|
| 2355 |
+
burn_hub_repo = gr.Textbox(label="📦 Repo Name (optional)")
|
| 2356 |
+
burn_hub_private = gr.Checkbox(value=True, label="🔒 Private")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2357 |
|
| 2358 |
gr.Markdown("---")
|
| 2359 |
gr.Markdown("### 📊 Dataset (Optional)")
|
| 2360 |
|
| 2361 |
+
burn_dataset = gr.Textbox(label="📁 Dataset Path")
|
| 2362 |
+
burn_use_finetuning = gr.Checkbox(value=False, label="🚀 Enable Fine-tuning")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2363 |
|
| 2364 |
with gr.Accordion("⚙️ Fine-tuning Config", open=False):
|
| 2365 |
burn_epochs = gr.Slider(1, 5, 1, step=1, label="Epochs")
|
|
|
|
| 2376 |
burn_btn.click(
|
| 2377 |
burn_phoenix_model_ui,
|
| 2378 |
[
|
| 2379 |
+
burn_model_url, burn_hierarchical, burn_dataset, burn_output_name,
|
| 2380 |
+
burn_use_finetuning, burn_epochs, burn_batch, burn_lr, burn_max_steps,
|
| 2381 |
+
burn_upload_hub, burn_hub_repo, burn_hub_private,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2382 |
],
|
| 2383 |
[burn_output, burn_plot]
|
| 2384 |
)
|
| 2385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2386 |
with gr.Tab("📊 Burning History"):
|
| 2387 |
+
gr.Markdown("### 📊 Model Burning History")
|
|
|
|
|
|
|
|
|
|
| 2388 |
|
| 2389 |
with gr.Row():
|
| 2390 |
with gr.Column(scale=1):
|
|
|
|
| 2397 |
hist_btn.click(view_burning_history, outputs=[hist_output, hist_plot])
|
| 2398 |
|
| 2399 |
with gr.Tab("🧪 Model Validation"):
|
| 2400 |
+
gr.Markdown("### 🧪 PHOENIX 모델 검증")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2401 |
|
| 2402 |
with gr.Row():
|
| 2403 |
with gr.Column(scale=1):
|
|
|
|
| 2409 |
|
| 2410 |
val_path = gr.Textbox(
|
| 2411 |
label="🔗 Model Path/URL",
|
| 2412 |
+
value="seawolf2357/phoenix-Qwen3-0.6B",
|
| 2413 |
placeholder="seawolf2357/phoenix-model"
|
| 2414 |
)
|
| 2415 |
|
|
|
|
| 2423 |
val_max_tokens = gr.Slider(16, 256, 64, step=16, label="Max Tokens")
|
| 2424 |
val_temp = gr.Slider(0.1, 2.0, 0.7, step=0.1, label="Temperature")
|
| 2425 |
|
| 2426 |
+
val_verify_retention = gr.Checkbox(value=True, label="🔍 Verify Retention")
|
|
|
|
|
|
|
|
|
|
| 2427 |
|
| 2428 |
val_btn = gr.Button("🧪 Validate Model", variant="primary", size="lg")
|
| 2429 |
|
|
|
|
| 2441 |
gr.Markdown(f"""
|
| 2442 |
---
|
| 2443 |
|
| 2444 |
+
## 🔥 PHOENIX Model Burning Platform v1.2
|
| 2445 |
|
| 2446 |
+
### What's New in v1.2
|
| 2447 |
+
- ✅ **Model Structure Pre-Analysis** - 변환 전 구조 파악
|
| 2448 |
+
- ✅ **Qwen3 Support** - Qwen3 모델 완벽 지원
|
| 2449 |
+
- ✅ **Enhanced Conversion** - 구조 정보 활용한 정확한 변환
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2450 |
|
| 2451 |
**HuggingFace Token**: {'✅ Connected' if HF_TOKEN else '❌ Not Found'}
|
| 2452 |
+
**Default Model**: {DEFAULT_MODEL}
|
| 2453 |
|
| 2454 |
+
**VIDraft AI Research Lab** | PHOENIX v1.2
|
| 2455 |
""")
|
| 2456 |
|
| 2457 |
if __name__ == "__main__":
|