File size: 9,883 Bytes
7aabfdc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
POC ๋ฐ๋ชจ ์คํฌ๋ฆฝํธ - ๊ธด ํ
์คํธ ์๋ ๋ถํ ์ฒ๋ฆฌ
"""
import torch
import sys
import io
from pathlib import Path
import time
# UTF-8 ์ธ์ฝ๋ฉ ์ค์
if sys.stdout.encoding != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.path.append(str(Path(__file__).parent))
from core.boundary_aware_model import BoundaryAwareTokenizerModel
from src.core.byte_tokenizer_v6 import ByteTokenizerV6
# Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class IntelligentTokenizerPOC:
"""POC ๋ฐ๋ชจ์ฉ ํด๋์ค"""
def __init__(self, checkpoint_path="checkpoints/unified/latest_checkpoint.pt"):
print("="*70)
print("INTELLIGENT TOKENIZER v6.0 - POC Demo")
print("="*70)
print(f"Device: {device}")
print(f"Loading checkpoint...")
# ์ฒดํฌํฌ์ธํธ ๋ก๋
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
self.model = BoundaryAwareTokenizerModel(**checkpoint['model_config'])
self.model.load_state_dict(checkpoint['model_state_dict'])
self.model = self.model.to(device)
self.model.eval()
self.tokenizer = ByteTokenizerV6()
self.max_chunk_size = 250 # 256๋ณด๋ค ์ฝ๊ฐ ์๊ฒ (์์ ๋ง์ง)
print(f"Model loaded: Epoch {checkpoint['epoch']}, Loss {checkpoint['loss']:.4f}")
print(f"Current limitation: 256 bytes per chunk")
print(f"(Due to POC development constraints and limited GPU resources)")
print("="*70)
print()
def process_text(self, text: str, show_details=True):
"""ํ
์คํธ ์ฒ๋ฆฌ (์๋ ๋ถํ )"""
# ๋ฐ์ดํธ๋ก ๋ณํ
text_bytes = text.encode('utf-8')
total_bytes = len(text_bytes)
if show_details:
print(f"Input text: {text[:100]}..." if len(text) > 100 else f"Input text: {text}")
print(f"Total bytes: {total_bytes}")
# 256 ๋ฐ์ดํธ ์ด๊ณผ์ ์๋ ๋ถํ
if total_bytes > self.max_chunk_size:
chunks = self._split_text_safely(text)
if show_details:
print(f"Auto-splitting into {len(chunks)} chunks (256 byte limit for POC)")
print("Note: Production version will handle up to 4096+ bytes")
print("-"*50)
results = []
total_compressed = 0
for i, chunk in enumerate(chunks):
if show_details:
print(f"\nChunk {i+1}/{len(chunks)}:")
result = self._process_single_chunk(chunk, show_details)
results.append(result)
total_compressed += result['compressed_tokens']
# ์ ์ฒด ํต๊ณ
if show_details:
print("\n" + "="*50)
print("OVERALL RESULTS:")
print(f"Total input: {total_bytes} bytes")
print(f"Total compressed: {total_compressed} tokens")
print(f"Compression ratio: {total_bytes/total_compressed:.2f}x")
print(f"Average accuracy: {sum(r['accuracy'] for r in results)/len(results):.1%}")
return results
else:
# ๋จ์ผ ์ฒญํฌ ์ฒ๋ฆฌ
return self._process_single_chunk(text, show_details)
def _split_text_safely(self, text: str):
"""UTF-8 ๊ฒฝ๊ณ๋ฅผ ๊ณ ๋ คํ ์์ ํ ํ
์คํธ ๋ถํ """
chunks = []
text_bytes = text.encode('utf-8')
start = 0
while start < len(text_bytes):
# ์ฒญํฌ ํฌ๊ธฐ ๊ฒฐ์
end = min(start + self.max_chunk_size, len(text_bytes))
# UTF-8 ๊ฒฝ๊ณ ํ์ธ (ํ๊ธ์ 3๋ฐ์ดํธ)
while end > start and end < len(text_bytes):
try:
# ๋์ฝ๋ฉ ์๋
chunk = text_bytes[start:end].decode('utf-8')
break
except UnicodeDecodeError:
# UTF-8 ๊ฒฝ๊ณ๊ฐ ์๋๋ฉด 1๋ฐ์ดํธ ๋ค๋ก
end -= 1
if end > start:
chunk = text_bytes[start:end].decode('utf-8')
chunks.append(chunk)
start = end
else:
break
return chunks
def _process_single_chunk(self, text: str, show_details=True):
"""๋จ์ผ ์ฒญํฌ ์ฒ๋ฆฌ"""
# ์ธ์ฝ๋ฉ
encoded = self.tokenizer.encode(text)
byte_ids = encoded['input_ids']
input_ids = torch.tensor([byte_ids], device=device)
attention_mask = torch.tensor([encoded['attention_mask']], device=device)
with torch.no_grad():
# ์์ถ
start_time = time.time()
encoder_outputs = self.model.encoder(input_ids, attention_mask)
encoder_hidden = encoder_outputs['last_hidden_state']
compression_time = time.time() - start_time
compressed_tokens = encoder_hidden.shape[1]
compression_ratio = len(byte_ids) / compressed_tokens
# ๋ณต์ (Teacher Forcing)
if len(byte_ids) > 1:
decoder_input = input_ids[:, :-1]
labels = input_ids[:, 1:]
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input,
labels=labels,
use_cross_attention=True
)
predictions = torch.argmax(outputs['logits'], dim=-1)
accuracy = (predictions == labels).float().mean().item()
else:
accuracy = 1.0
if show_details:
print(f" Input: {len(byte_ids)} bytes")
print(f" Compressed: {compressed_tokens} tokens ({compression_ratio:.2f}x)")
print(f" Accuracy: {accuracy:.1%}")
print(f" Processing time: {compression_time*1000:.1f}ms")
return {
'text': text,
'input_bytes': len(byte_ids),
'compressed_tokens': compressed_tokens,
'compression_ratio': compression_ratio,
'accuracy': accuracy,
'time_ms': compression_time * 1000
}
def benchmark_languages(self):
"""๋ค๊ตญ์ด ๋ฒค์น๋งํฌ"""
print("\n" + "="*70)
print("MULTILINGUAL BENCHMARK")
print("="*70)
test_samples = {
'English': "The quick brown fox jumps over the lazy dog",
'Korean': "์๋
ํ์ธ์. ์ค๋ ๋ ์จ๊ฐ ์ ๋ง ์ข๋ค์",
'Chinese': "ไปๅคฉๅคฉๆฐๅพๅฅฝ",
'Japanese': "ใใใซใกใฏ",
'Spanish': "Hola, ยฟcรณmo estรกs?",
'Arabic': "ู
ุฑุญุจุง ุจู",
'Russian': "ะัะธะฒะตั, ะบะฐะบ ะดะตะปะฐ?",
}
for lang, text in test_samples.items():
print(f"\n{lang}:")
self._process_single_chunk(text, show_details=True)
def explain_advantages(self):
"""์ฅ์ ์ค๋ช
"""
print("\n" + "="*70)
print("KEY ADVANTAGES")
print("="*70)
print("""
1. PURE LEARNING-BASED
- No vocabulary files (260 fixed bytes vs 50K+ tokens)
- No language-specific rules
- Learns compression patterns from data
2. MULTILINGUAL EQUALITY
- All 204 languages treated equally
- No vocabulary bias towards English
- Better for low-resource languages
3. COMPRESSION CAPABILITY
- Current: 2-3x compression (POC stage)
- Target: 5-10x compression (with more training)
- API cost reduction: 50-80%
4. CURRENT LIMITATIONS (POC)
- 256 byte chunks (due to limited GPU resources)
- Will expand to 4096+ bytes post-POC
- Training on personal RTX 3060 (4 months development)
5. FUTURE ROADMAP
- Multimodal support (text + image + audio)
- Dynamic compression levels
- Real-time streaming mode
""")
print("="*70)
def main():
"""๋ฉ์ธ ๋ฐ๋ชจ"""
poc = IntelligentTokenizerPOC()
# 1. ์งง์ ํ
์คํธ ๋ฐ๋ชจ
print("\n### SHORT TEXT DEMO ###")
poc.process_text("Hello, world!")
poc.process_text("์๋
ํ์ธ์. ๋ฐ๊ฐ์ต๋๋ค.")
# 2. ๊ธด ํ
์คํธ ์๋ ๋ถํ ๋ฐ๋ชจ
print("\n### LONG TEXT AUTO-SPLIT DEMO ###")
long_text = """
์ธ๊ณต์ง๋ฅ ๊ธฐ์ ์ด ๋น ๋ฅด๊ฒ ๋ฐ์ ํ๊ณ ์์ต๋๋ค. ํนํ ์์ฐ์ด ์ฒ๋ฆฌ ๋ถ์ผ์์
๋๋ผ์ด ์ฑ๊ณผ๋ฅผ ๋ณด์ด๊ณ ์์ผ๋ฉฐ, ์ด๋ ์ฐ๋ฆฌ์ ์ผ์์ํ์๋ ํฐ ์ํฅ์
๋ฏธ์น๊ณ ์์ต๋๋ค. ์์ผ๋ก ๋ ๋ง์ ํ์ ์ด ๊ธฐ๋๋ฉ๋๋ค.
The development of artificial intelligence is accelerating rapidly.
Natural language processing, in particular, has shown remarkable progress,
significantly impacting our daily lives. We can expect even more innovations
in the near future.
"""
poc.process_text(long_text)
# 3. ๋ค๊ตญ์ด ๋ฒค์น๋งํฌ
poc.benchmark_languages()
# 4. ์ฅ์ ์ค๋ช
poc.explain_advantages()
print("\n" + "="*70)
print("POC DEMO COMPLETE")
print("Developed in 4 months by a solo developer with no prior AI experience")
print("Contact: [your contact info]")
print("="*70)
if __name__ == "__main__":
main() |