Upload inference.py with huggingface_hub
Browse files- inference.py +186 -297
inference.py
CHANGED
|
@@ -1,297 +1,186 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import
|
| 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 |
-
text_bytes = text.encode('utf-8')
|
| 188 |
-
embeddings = self.embed(text)
|
| 189 |
-
|
| 190 |
-
original_size = len(text_bytes)
|
| 191 |
-
compressed_size = embeddings.shape[1]
|
| 192 |
-
compression_ratio = original_size / compressed_size if compressed_size > 0 else 0
|
| 193 |
-
|
| 194 |
-
return {
|
| 195 |
-
'original_bytes': original_size,
|
| 196 |
-
'compressed_tokens': compressed_size,
|
| 197 |
-
'compression_ratio': compression_ratio,
|
| 198 |
-
'embedding_shape': list(embeddings.shape)
|
| 199 |
-
}
|
| 200 |
-
|
| 201 |
-
def _split_text_safely(self, text: str) -> List[str]:
|
| 202 |
-
"""Split text safely at UTF-8 boundaries"""
|
| 203 |
-
chunks = []
|
| 204 |
-
text_bytes = text.encode('utf-8')
|
| 205 |
-
|
| 206 |
-
start = 0
|
| 207 |
-
while start < len(text_bytes):
|
| 208 |
-
end = min(start + self.max_chunk_size, len(text_bytes))
|
| 209 |
-
|
| 210 |
-
# Find valid UTF-8 boundary
|
| 211 |
-
while end > start and end < len(text_bytes):
|
| 212 |
-
try:
|
| 213 |
-
chunk = text_bytes[start:end].decode('utf-8')
|
| 214 |
-
break
|
| 215 |
-
except UnicodeDecodeError:
|
| 216 |
-
end -= 1
|
| 217 |
-
|
| 218 |
-
if end > start:
|
| 219 |
-
chunk = text_bytes[start:end].decode('utf-8')
|
| 220 |
-
chunks.append(chunk)
|
| 221 |
-
start = end
|
| 222 |
-
else:
|
| 223 |
-
break
|
| 224 |
-
|
| 225 |
-
return chunks
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
def test_model():
|
| 229 |
-
"""Test model functionality"""
|
| 230 |
-
print("="*70)
|
| 231 |
-
print("INTELLIGENT TOKENIZER v6.0 - FUNCTIONALITY TEST")
|
| 232 |
-
print("="*70)
|
| 233 |
-
|
| 234 |
-
# Initialize tokenizer
|
| 235 |
-
tokenizer = IntelligentTokenizer()
|
| 236 |
-
|
| 237 |
-
# Test samples
|
| 238 |
-
test_samples = [
|
| 239 |
-
("English", "Hello, world!"),
|
| 240 |
-
("Korean", "์๋
ํ์ธ์. ๋ฐ๊ฐ์ต๋๋ค."),
|
| 241 |
-
("Chinese", "ไปๅคฉๅคฉๆฐๅพๅฅฝ"),
|
| 242 |
-
("Japanese", "ใใใซใกใฏ"),
|
| 243 |
-
("Arabic", "ู
ุฑุญุจุง ุจู"),
|
| 244 |
-
("Russian", "ะัะธะฒะตั, ะบะฐะบ ะดะตะปะฐ?"),
|
| 245 |
-
("Emoji", "Hello ๐ World ๐!"),
|
| 246 |
-
]
|
| 247 |
-
|
| 248 |
-
print("\n" + "="*70)
|
| 249 |
-
print("EMBEDDING & RESTORATION TESTS")
|
| 250 |
-
print("="*70)
|
| 251 |
-
|
| 252 |
-
total_accuracy = 0
|
| 253 |
-
successful = 0
|
| 254 |
-
|
| 255 |
-
for lang, text in test_samples:
|
| 256 |
-
print(f"\n[{lang}]")
|
| 257 |
-
print(f"Original: {text}")
|
| 258 |
-
|
| 259 |
-
# Test embedding
|
| 260 |
-
embeddings = tokenizer.embed(text)
|
| 261 |
-
print(f"Embedding: {embeddings.shape}")
|
| 262 |
-
|
| 263 |
-
# Test compression
|
| 264 |
-
compression = tokenizer.compress(text)
|
| 265 |
-
print(f"Compression: {compression['original_bytes']} bytes โ {compression['compressed_tokens']} tokens")
|
| 266 |
-
print(f"Ratio: {compression['compression_ratio']:.2f}x")
|
| 267 |
-
|
| 268 |
-
# Test restoration
|
| 269 |
-
restored, accuracy = tokenizer.restore(text)
|
| 270 |
-
print(f"Restored: {restored}")
|
| 271 |
-
print(f"Accuracy: {accuracy:.1%}")
|
| 272 |
-
|
| 273 |
-
if accuracy > 0.7:
|
| 274 |
-
successful += 1
|
| 275 |
-
total_accuracy += accuracy
|
| 276 |
-
|
| 277 |
-
# Summary
|
| 278 |
-
print("\n" + "="*70)
|
| 279 |
-
print("TEST SUMMARY")
|
| 280 |
-
print("="*70)
|
| 281 |
-
print(f"Tests passed: {successful}/{len(test_samples)}")
|
| 282 |
-
print(f"Average accuracy: {total_accuracy/len(test_samples):.1%}")
|
| 283 |
-
|
| 284 |
-
if successful == len(test_samples):
|
| 285 |
-
print("\nโ
ALL TESTS PASSED!")
|
| 286 |
-
return True
|
| 287 |
-
elif successful >= len(test_samples) * 0.7:
|
| 288 |
-
print("\nโ ๏ธ PARTIAL SUCCESS (70%+ tests passed)")
|
| 289 |
-
return True
|
| 290 |
-
else:
|
| 291 |
-
print("\nโ TESTS FAILED")
|
| 292 |
-
return False
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
if __name__ == "__main__":
|
| 296 |
-
success = test_model()
|
| 297 |
-
sys.exit(0 if success else 1)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
B2NL-IntelligentTokenizer v6.2.1 - ์ค์ ์๋ํ๋ ์ถ๋ก ์ฝ๋
|
| 3 |
+
์ด ํ์ผ์ด ๋ฉ์ธ ์ฌ์ฉ๋ฒ์
๋๋ค.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
# ๊ฒฝ๋ก ์ถ๊ฐ
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "intelligent-tokenizer_v6.2.1"))
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "intelligent-tokenizer_v6.2.1/core"))
|
| 13 |
+
|
| 14 |
+
from core.unified_model import IntelligentTokenizerV62
|
| 15 |
+
from core.tokenizer import ByteTokenizerV62
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class B2NLTokenizer:
|
| 19 |
+
"""์ค์ ๋ก ์๋ํ๋ B2NL ํ ํฌ๋์ด์ """
|
| 20 |
+
|
| 21 |
+
def __init__(self, checkpoint_path: str = None):
|
| 22 |
+
"""
|
| 23 |
+
Args:
|
| 24 |
+
checkpoint_path: ์ฒดํฌํฌ์ธํธ ๊ฒฝ๋ก (์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ)
|
| 25 |
+
"""
|
| 26 |
+
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 27 |
+
|
| 28 |
+
# ๊ธฐ๋ณธ ์ฒดํฌํฌ์ธํธ ๊ฒฝ๋ก
|
| 29 |
+
if checkpoint_path is None:
|
| 30 |
+
checkpoint_path = "D:/intelligent-tokenizer/intelligent-tokenizer_v6.2.1/checkpoints/v62/16.0/epoch_100.pt"
|
| 31 |
+
|
| 32 |
+
# ๋ชจ๋ธ ๋ก๋
|
| 33 |
+
self.model = IntelligentTokenizerV62()
|
| 34 |
+
checkpoint = torch.load(checkpoint_path, map_location=self.device, weights_only=False)
|
| 35 |
+
self.model.load_state_dict(checkpoint['model_state_dict'])
|
| 36 |
+
self.model = self.model.to(self.device)
|
| 37 |
+
self.model.eval()
|
| 38 |
+
|
| 39 |
+
print(f"Model loaded successfully on {self.device}")
|
| 40 |
+
|
| 41 |
+
def compress(self, text: str) -> dict:
|
| 42 |
+
"""ํ
์คํธ๋ฅผ ์์ถ"""
|
| 43 |
+
return self.model.compress(text)
|
| 44 |
+
|
| 45 |
+
def reconstruct(self, text: str, temperature: float = 0.1) -> str:
|
| 46 |
+
"""
|
| 47 |
+
ํ
์คํธ๋ฅผ ์์ถ ํ ๋ณต์ (์ค์ ์๋ํ๋ ๋ฒ์ )
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
text: ์
๋ ฅ ํ
์คํธ
|
| 51 |
+
temperature: ์์ฑ ์จ๋ (๋ฎ์์๋ก ๊ฒฐ์ ์ )
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
๋ณต์๋ ํ
์คํธ
|
| 55 |
+
"""
|
| 56 |
+
# 1. ํ
์คํธ ์ธ์ฝ๋ฉ
|
| 57 |
+
tokenizer = self.model.tokenizer
|
| 58 |
+
encoded = tokenizer.encode(text)
|
| 59 |
+
|
| 60 |
+
if isinstance(encoded, dict):
|
| 61 |
+
input_ids = encoded['input_ids'].unsqueeze(0) if encoded['input_ids'].dim() == 1 else encoded['input_ids']
|
| 62 |
+
attention_mask = encoded['attention_mask'].unsqueeze(0) if encoded['attention_mask'].dim() == 1 else encoded['attention_mask']
|
| 63 |
+
else:
|
| 64 |
+
input_ids = encoded.unsqueeze(0) if encoded.dim() == 1 else encoded
|
| 65 |
+
attention_mask = torch.ones_like(input_ids)
|
| 66 |
+
|
| 67 |
+
input_ids = input_ids.to(self.device)
|
| 68 |
+
attention_mask = attention_mask.to(self.device)
|
| 69 |
+
|
| 70 |
+
# 2. ์ธ์ฝ๋๋ก ์์ถ
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
encoder_outputs = self.model.encoder(
|
| 73 |
+
input_ids=input_ids,
|
| 74 |
+
attention_mask=attention_mask
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# ๋ชจ๋ ํ๋ ์คํ
์ดํธ ์ค๋น
|
| 78 |
+
if 'all_hidden_states' in encoder_outputs:
|
| 79 |
+
encoder_all_hidden = encoder_outputs['all_hidden_states']
|
| 80 |
+
else:
|
| 81 |
+
compressed = encoder_outputs.get('compressed', encoder_outputs.get('hidden_states'))
|
| 82 |
+
encoder_all_hidden = [compressed] * 4
|
| 83 |
+
|
| 84 |
+
# 3. ์๋ํ๊ท ๋์ฝ๋ฉ (์ค์ ์๋ํ๋ ๋ฐฉ์)
|
| 85 |
+
batch_size = input_ids.size(0)
|
| 86 |
+
max_length = 48
|
| 87 |
+
|
| 88 |
+
# BOS ํ ํฐ์ผ๋ก ์์
|
| 89 |
+
generated = torch.full((batch_size, 1), tokenizer.BOS, device=self.device)
|
| 90 |
+
|
| 91 |
+
for step in range(max_length - 1):
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
# ํ์ฌ๊น์ง ์์ฑ๋ ์ํ์ค๋ก ๋์ฝ๋ฉ
|
| 94 |
+
decoder_outputs = self.model.decoder(
|
| 95 |
+
encoder_all_hidden=encoder_all_hidden,
|
| 96 |
+
decoder_input_ids=generated,
|
| 97 |
+
attention_mask=torch.ones_like(generated),
|
| 98 |
+
use_cache=False
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# ๋ค์ ํ ํฐ ์์ธก
|
| 102 |
+
logits = decoder_outputs['logits'][:, -1, :] / temperature
|
| 103 |
+
|
| 104 |
+
# Top-k ์ํ๋ง
|
| 105 |
+
top_k = 10
|
| 106 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 107 |
+
logits[indices_to_remove] = float('-inf')
|
| 108 |
+
|
| 109 |
+
# ํ๋ฅ ๊ณ์ฐ ๋ฐ ์ํ๋ง
|
| 110 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)
|
| 111 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 112 |
+
|
| 113 |
+
# ์์ฑ๋ ์ํ์ค์ ์ถ๊ฐ
|
| 114 |
+
generated = torch.cat([generated, next_token], dim=1)
|
| 115 |
+
|
| 116 |
+
# EOS ํ ํฐ ์ฒดํฌ
|
| 117 |
+
if (next_token == tokenizer.EOS).all():
|
| 118 |
+
break
|
| 119 |
+
|
| 120 |
+
# 4. ํ
์คํธ๋ก ๋์ฝ๋ฉ
|
| 121 |
+
if generated.dim() > 1:
|
| 122 |
+
text = tokenizer.decode(generated[0])
|
| 123 |
+
else:
|
| 124 |
+
text = tokenizer.decode(generated)
|
| 125 |
+
|
| 126 |
+
return text
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_tokenizer():
|
| 130 |
+
"""ํ ํฌ๋์ด์ ํ
์คํธ"""
|
| 131 |
+
print("="*60)
|
| 132 |
+
print("B2NL-IntelligentTokenizer v6.2.1 ํ
์คํธ")
|
| 133 |
+
print("="*60)
|
| 134 |
+
|
| 135 |
+
# ํ ํฌ๋์ด์ ์ด๊ธฐํ
|
| 136 |
+
tokenizer = B2NLTokenizer()
|
| 137 |
+
|
| 138 |
+
# ํ
์คํธ ํ
์คํธ
|
| 139 |
+
test_texts = [
|
| 140 |
+
"Hello, world!",
|
| 141 |
+
"์๋
ํ์ธ์, ๋ฐ๊ฐ์ต๋๋ค.",
|
| 142 |
+
"The quick brown fox jumps over the lazy dog.",
|
| 143 |
+
"ไบบๅทฅๆบ่ฝๆๆฏๆญฃๅจๆนๅไธ็ใ",
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
for text in test_texts:
|
| 147 |
+
print(f"\n์๋ณธ: {text}")
|
| 148 |
+
|
| 149 |
+
# ์์ถ
|
| 150 |
+
compressed = tokenizer.compress(text)
|
| 151 |
+
print(f"์์ถ๋ฅ : {compressed['compression_ratio']:.1f}:1 ({compressed['num_tokens']} ํ ํฐ)")
|
| 152 |
+
|
| 153 |
+
# ๋ณต์
|
| 154 |
+
reconstructed = tokenizer.reconstruct(text, temperature=0.1)
|
| 155 |
+
print(f"๋ณต์: {reconstructed}")
|
| 156 |
+
|
| 157 |
+
# ์ ํ๋ ๊ณ์ฐ
|
| 158 |
+
min_len = min(len(text), len(reconstructed))
|
| 159 |
+
accuracy = sum(1 for i in range(min_len) if text[i] == reconstructed[i]) / len(text) * 100
|
| 160 |
+
print(f"์ ํ๋: {accuracy:.1f}%")
|
| 161 |
+
|
| 162 |
+
print("\n" + "="*60)
|
| 163 |
+
print("Test completed!")
|
| 164 |
+
print("="*60)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ์ฌ์ฉ ์์
|
| 168 |
+
def example_usage():
|
| 169 |
+
"""๊ฐ๋จํ ์ฌ์ฉ ์์ """
|
| 170 |
+
# 1. ํ ํฌ๋์ด์ ์ด๊ธฐํ
|
| 171 |
+
tokenizer = B2NLTokenizer()
|
| 172 |
+
|
| 173 |
+
# 2. ํ
์คํธ ์์ถ
|
| 174 |
+
text = "์๋
ํ์ธ์, ๋ฐ๊ฐ์ต๋๋ค!"
|
| 175 |
+
compressed = tokenizer.compress(text)
|
| 176 |
+
print(f"์์ถ ๊ฒฐ๊ณผ: {compressed['compression_ratio']:.1f}:1")
|
| 177 |
+
|
| 178 |
+
# 3. ํ
์คํธ ๋ณต์
|
| 179 |
+
reconstructed = tokenizer.reconstruct(text)
|
| 180 |
+
print(f"๋ณต์ ๊ฒฐ๊ณผ: {reconstructed}")
|
| 181 |
+
|
| 182 |
+
return tokenizer
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
test_tokenizer()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|