File size: 6,289 Bytes
905c972 |
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 |
"""
B2NL-IntelligentTokenizer v6.2.1 - ์ค์ ์๋ํ๋ ์ถ๋ก ์ฝ๋
์ด ํ์ผ์ด ๋ฉ์ธ ์ฌ์ฉ๋ฒ์
๋๋ค.
"""
import torch
import sys
from pathlib import Path
# ๊ฒฝ๋ก ์ถ๊ฐ
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "intelligent-tokenizer_v6.2.1"))
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "intelligent-tokenizer_v6.2.1/core"))
from core.unified_model import IntelligentTokenizerV62
from core.tokenizer import ByteTokenizerV62
class B2NLTokenizer:
"""์ค์ ๋ก ์๋ํ๋ B2NL ํ ํฌ๋์ด์ """
def __init__(self, checkpoint_path: str = None):
"""
Args:
checkpoint_path: ์ฒดํฌํฌ์ธํธ ๊ฒฝ๋ก (์์ผ๋ฉด ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ)
"""
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# ๊ธฐ๋ณธ ์ฒดํฌํฌ์ธํธ ๊ฒฝ๋ก
if checkpoint_path is None:
checkpoint_path = "D:/intelligent-tokenizer/intelligent-tokenizer_v6.2.1/checkpoints/v62/16.0/epoch_100.pt"
# ๋ชจ๋ธ ๋ก๋
self.model = IntelligentTokenizerV62()
checkpoint = torch.load(checkpoint_path, map_location=self.device, weights_only=False)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.model = self.model.to(self.device)
self.model.eval()
print(f"Model loaded successfully on {self.device}")
def compress(self, text: str) -> dict:
"""ํ
์คํธ๋ฅผ ์์ถ"""
return self.model.compress(text)
def reconstruct(self, text: str, temperature: float = 0.1) -> str:
"""
ํ
์คํธ๋ฅผ ์์ถ ํ ๋ณต์ (์ค์ ์๋ํ๋ ๋ฒ์ )
Args:
text: ์
๋ ฅ ํ
์คํธ
temperature: ์์ฑ ์จ๋ (๋ฎ์์๋ก ๊ฒฐ์ ์ )
Returns:
๋ณต์๋ ํ
์คํธ
"""
# 1. ํ
์คํธ ์ธ์ฝ๋ฉ
tokenizer = self.model.tokenizer
encoded = tokenizer.encode(text)
if isinstance(encoded, dict):
input_ids = encoded['input_ids'].unsqueeze(0) if encoded['input_ids'].dim() == 1 else encoded['input_ids']
attention_mask = encoded['attention_mask'].unsqueeze(0) if encoded['attention_mask'].dim() == 1 else encoded['attention_mask']
else:
input_ids = encoded.unsqueeze(0) if encoded.dim() == 1 else encoded
attention_mask = torch.ones_like(input_ids)
input_ids = input_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
# 2. ์ธ์ฝ๋๋ก ์์ถ
with torch.no_grad():
encoder_outputs = self.model.encoder(
input_ids=input_ids,
attention_mask=attention_mask
)
# ๋ชจ๋ ํ๋ ์คํ
์ดํธ ์ค๋น
if 'all_hidden_states' in encoder_outputs:
encoder_all_hidden = encoder_outputs['all_hidden_states']
else:
compressed = encoder_outputs.get('compressed', encoder_outputs.get('hidden_states'))
encoder_all_hidden = [compressed] * 4
# 3. ์๋ํ๊ท ๋์ฝ๋ฉ (์ค์ ์๋ํ๋ ๋ฐฉ์)
batch_size = input_ids.size(0)
max_length = 48
# BOS ํ ํฐ์ผ๋ก ์์
generated = torch.full((batch_size, 1), tokenizer.BOS, device=self.device)
for step in range(max_length - 1):
with torch.no_grad():
# ํ์ฌ๊น์ง ์์ฑ๋ ์ํ์ค๋ก ๋์ฝ๋ฉ
decoder_outputs = self.model.decoder(
encoder_all_hidden=encoder_all_hidden,
decoder_input_ids=generated,
attention_mask=torch.ones_like(generated),
use_cache=False
)
# ๋ค์ ํ ํฐ ์์ธก
logits = decoder_outputs['logits'][:, -1, :] / temperature
# Top-k ์ํ๋ง
top_k = 10
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = float('-inf')
# ํ๋ฅ ๊ณ์ฐ ๋ฐ ์ํ๋ง
probs = torch.nn.functional.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
# ์์ฑ๋ ์ํ์ค์ ์ถ๊ฐ
generated = torch.cat([generated, next_token], dim=1)
# EOS ํ ํฐ ์ฒดํฌ
if (next_token == tokenizer.EOS).all():
break
# 4. ํ
์คํธ๋ก ๋์ฝ๋ฉ
if generated.dim() > 1:
text = tokenizer.decode(generated[0])
else:
text = tokenizer.decode(generated)
return text
def test_tokenizer():
"""ํ ํฌ๋์ด์ ํ
์คํธ"""
print("="*60)
print("B2NL-IntelligentTokenizer v6.2.1 ํ
์คํธ")
print("="*60)
# ํ ํฌ๋์ด์ ์ด๊ธฐํ
tokenizer = B2NLTokenizer()
# ํ
์คํธ ํ
์คํธ
test_texts = [
"Hello, world!",
"์๋
ํ์ธ์, ๋ฐ๊ฐ์ต๋๋ค.",
"The quick brown fox jumps over the lazy dog.",
"ไบบๅทฅๆบ่ฝๆๆฏๆญฃๅจๆนๅไธ็ใ",
]
for text in test_texts:
print(f"\n์๋ณธ: {text}")
# ์์ถ
compressed = tokenizer.compress(text)
print(f"์์ถ๋ฅ : {compressed['compression_ratio']:.1f}:1 ({compressed['num_tokens']} ํ ํฐ)")
# ๋ณต์
reconstructed = tokenizer.reconstruct(text, temperature=0.1)
print(f"๋ณต์: {reconstructed}")
# ์ ํ๋ ๊ณ์ฐ
min_len = min(len(text), len(reconstructed))
accuracy = sum(1 for i in range(min_len) if text[i] == reconstructed[i]) / len(text) * 100
print(f"์ ํ๋: {accuracy:.1f}%")
print("\n" + "="*60)
print("Test completed!")
print("="*60)
# ์ฌ์ฉ ์์
def example_usage():
"""๊ฐ๋จํ ์ฌ์ฉ ์์ """
# 1. ํ ํฌ๋์ด์ ์ด๊ธฐํ
tokenizer = B2NLTokenizer()
# 2. ํ
์คํธ ์์ถ
text = "์๋
ํ์ธ์, ๋ฐ๊ฐ์ต๋๋ค!"
compressed = tokenizer.compress(text)
print(f"์์ถ ๊ฒฐ๊ณผ: {compressed['compression_ratio']:.1f}:1")
# 3. ํ
์คํธ ๋ณต์
reconstructed = tokenizer.reconstruct(text)
print(f"๋ณต์ ๊ฒฐ๊ณผ: {reconstructed}")
return tokenizer
if __name__ == "__main__":
test_tokenizer() |