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