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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from tensorflow.keras import layers
|
| 4 |
+
import sentencepiece as spm
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import requests
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# ----------------------
|
| 10 |
+
# 파일 다운로드 유틸
|
| 11 |
+
# ----------------------
|
| 12 |
+
def download_file(url, save_path):
|
| 13 |
+
r = requests.get(url, stream=True)
|
| 14 |
+
r.raise_for_status()
|
| 15 |
+
with open(save_path, "wb") as f:
|
| 16 |
+
for chunk in r.iter_content(8192*2):
|
| 17 |
+
f.write(chunk)
|
| 18 |
+
print(f"✅ {save_path} 저장됨")
|
| 19 |
+
|
| 20 |
+
MODEL_PATH = "encoder.weights.h5"
|
| 21 |
+
TOKENIZER_PATH = "bpe.model"
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(MODEL_PATH):
|
| 24 |
+
download_file(
|
| 25 |
+
"https://huggingface.co/OpenLab-NLP/openlem2/resolve/main/encoder_fit.weights.h5?download=true",
|
| 26 |
+
MODEL_PATH
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
if not os.path.exists(TOKENIZER_PATH):
|
| 30 |
+
download_file(
|
| 31 |
+
"https://huggingface.co/OpenLab-NLP/openlem2/resolve/main/bpe.model?download=true",
|
| 32 |
+
TOKENIZER_PATH
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
MAX_LEN = 384
|
| 36 |
+
EMBED_DIM = 512
|
| 37 |
+
LATENT_DIM = 512
|
| 38 |
+
BATCH_SIZE = 768 # global batch size (Keras/TPU가 replica-wise로 나눠서 처리)
|
| 39 |
+
EPOCHS = 1
|
| 40 |
+
SHUFFLE_BUFFER = 200000
|
| 41 |
+
LEARNING_RATE = 1e-4
|
| 42 |
+
TEMPERATURE = 0.05
|
| 43 |
+
DROPOUT_AUG = 0.1
|
| 44 |
+
EMBED_DROPOUT = 0.1
|
| 45 |
+
SEED = 42
|
| 46 |
+
DROPOUT_AUG = 0.1
|
| 47 |
+
EMBED_DROPOUT = 0.1
|
| 48 |
+
# ===============================
|
| 49 |
+
# 1️⃣ 토크나이저 로딩
|
| 50 |
+
# ===============================
|
| 51 |
+
sp = spm.SentencePieceProcessor(TOKENIZER_PATH)
|
| 52 |
+
pad_id = sp.piece_to_id("<pad>") if sp.piece_to_id("<pad>") != -1 else 0
|
| 53 |
+
vocab_size = sp.get_piece_size()
|
| 54 |
+
|
| 55 |
+
def encode_sentence(sentence, max_len=MAX_LEN):
|
| 56 |
+
return sp.encode(sentence, out_type=int)[:max_len]
|
| 57 |
+
|
| 58 |
+
def pad_sentence(tokens):
|
| 59 |
+
return tokens + [pad_id]*(MAX_LEN - len(tokens))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DynamicConv(layers.Layer):
|
| 63 |
+
def __init__(self, d_model, k=7):
|
| 64 |
+
super().__init__()
|
| 65 |
+
assert k % 2 == 1
|
| 66 |
+
self.k = k
|
| 67 |
+
self.dense = layers.Dense(d_model, activation='silu')
|
| 68 |
+
self.proj = layers.Dense(d_model)
|
| 69 |
+
self.generator = layers.Dense(k, dtype='float32')
|
| 70 |
+
def call(self, x):
|
| 71 |
+
x_in = x
|
| 72 |
+
x = tf.cast(x, tf.float32)
|
| 73 |
+
|
| 74 |
+
B = tf.shape(x)[0]
|
| 75 |
+
L = tf.shape(x)[1]
|
| 76 |
+
D = tf.shape(x)[2]
|
| 77 |
+
|
| 78 |
+
kernels = self.generator(self.dense(x))
|
| 79 |
+
kernels = tf.nn.softmax(kernels, axis=-1)
|
| 80 |
+
|
| 81 |
+
pad = (self.k - 1) // 2
|
| 82 |
+
x_pad = tf.pad(x, [[0,0],[pad,pad],[0,0]])
|
| 83 |
+
|
| 84 |
+
x_pad_4d = tf.expand_dims(x_pad, axis=1)
|
| 85 |
+
patches = tf.image.extract_patches(
|
| 86 |
+
images=x_pad_4d,
|
| 87 |
+
sizes=[1,1,self.k,1],
|
| 88 |
+
strides=[1,1,1,1],
|
| 89 |
+
rates=[1,1,1,1],
|
| 90 |
+
padding='VALID'
|
| 91 |
+
)
|
| 92 |
+
patches = tf.reshape(patches, [B, L, self.k, D])
|
| 93 |
+
|
| 94 |
+
kernels_exp = tf.expand_dims(kernels, axis=-1)
|
| 95 |
+
out = tf.reduce_sum(patches * kernels_exp, axis=2)
|
| 96 |
+
out = self.proj(out)
|
| 97 |
+
|
| 98 |
+
# 🔥 원래 dtype으로 돌려줌
|
| 99 |
+
return tf.cast(out, x_in.dtype)
|
| 100 |
+
|
| 101 |
+
class EncoderBlock(tf.keras.layers.Layer):
|
| 102 |
+
def __init__(self, embed_dim=EMBED_DIM, ff_dim=1152, seq_len=MAX_LEN, num_conv_layers=2):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.embed_dim = embed_dim
|
| 105 |
+
self.seq_len = seq_len
|
| 106 |
+
|
| 107 |
+
# MLP / FFN
|
| 108 |
+
self.fc1 = layers.Dense(ff_dim)
|
| 109 |
+
self.fc2 = layers.Dense(embed_dim)
|
| 110 |
+
self.blocks = [DynamicConv(d_model=embed_dim, k=7) for _ in range(num_conv_layers)]
|
| 111 |
+
# LayerNorm
|
| 112 |
+
self.ln = layers.LayerNormalization(epsilon=1e-5) # 입력 정규화
|
| 113 |
+
self.ln1 = layers.LayerNormalization(epsilon=1e-5) # Conv residual
|
| 114 |
+
self.ln2 = layers.LayerNormalization(epsilon=1e-5) # FFN residual
|
| 115 |
+
|
| 116 |
+
def call(self, x, mask=None):
|
| 117 |
+
# 입력 정규화
|
| 118 |
+
x_norm = self.ln(x)
|
| 119 |
+
|
| 120 |
+
# DynamicConv 여러 층 통과
|
| 121 |
+
out = x_norm
|
| 122 |
+
for block in self.blocks: out = block(out)
|
| 123 |
+
# Conv residual 연결
|
| 124 |
+
x = x_norm + self.ln1(out)
|
| 125 |
+
|
| 126 |
+
# FFN / GLU
|
| 127 |
+
v = out
|
| 128 |
+
h = self.fc1(v)
|
| 129 |
+
g, v_split = tf.split(h, 2, axis=-1)
|
| 130 |
+
h = tf.nn.silu(g) * v_split
|
| 131 |
+
h = self.fc2(h)
|
| 132 |
+
|
| 133 |
+
# FFN residual 연결
|
| 134 |
+
x = x + self.ln2(h)
|
| 135 |
+
|
| 136 |
+
return x
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class L2NormLayer(layers.Layer):
|
| 140 |
+
def __init__(self, axis=1, epsilon=1e-10, **kwargs):
|
| 141 |
+
super().__init__(**kwargs)
|
| 142 |
+
self.axis = axis
|
| 143 |
+
self.epsilon = epsilon
|
| 144 |
+
def call(self, inputs):
|
| 145 |
+
return tf.math.l2_normalize(inputs, axis=self.axis, epsilon=self.epsilon)
|
| 146 |
+
|
| 147 |
+
class SentenceEncoder(tf.keras.Model):
|
| 148 |
+
def __init__(self, vocab_size, embed_dim=EMBED_DIM, latent_dim=LATENT_DIM, max_len=MAX_LEN, pad_id=pad_id, dropout_rate=EMBED_DROPOUT):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.pad_id = pad_id
|
| 151 |
+
self.embed = layers.Embedding(vocab_size, embed_dim)
|
| 152 |
+
self.pos_embed = layers.Embedding(input_dim=max_len, output_dim=embed_dim)
|
| 153 |
+
self.dropout = layers.Dropout(dropout_rate)
|
| 154 |
+
self.blocks = [EncoderBlock() for _ in range(2)]
|
| 155 |
+
self.attn_pool = layers.Dense(1)
|
| 156 |
+
self.ln_f = layers.LayerNormalization(epsilon=1e-5, dtype=tf.float32)
|
| 157 |
+
self.latent = layers.Dense(latent_dim, activation=None)
|
| 158 |
+
self.l2norm = L2NormLayer(axis=1)
|
| 159 |
+
|
| 160 |
+
def call(self, x, training=None):
|
| 161 |
+
positions = tf.range(tf.shape(x)[1])[tf.newaxis, :]
|
| 162 |
+
x_embed = self.embed(x) + self.pos_embed(positions)
|
| 163 |
+
x_embed = self.dropout(x_embed, training=training)
|
| 164 |
+
|
| 165 |
+
mask = tf.cast(tf.not_equal(x, self.pad_id), tf.float32)
|
| 166 |
+
|
| 167 |
+
h = x_embed
|
| 168 |
+
for block in self.blocks:
|
| 169 |
+
h = block(h, training=training)
|
| 170 |
+
|
| 171 |
+
h = self.ln_f(h)
|
| 172 |
+
|
| 173 |
+
# 🔥 scores를 float32 강제
|
| 174 |
+
scores = self.attn_pool(h)
|
| 175 |
+
scores = tf.cast(scores, tf.float32)
|
| 176 |
+
|
| 177 |
+
scores = tf.where(mask[..., tf.newaxis] == 0, tf.constant(-1e9, tf.float32), scores)
|
| 178 |
+
scores = tf.nn.softmax(scores, axis=1)
|
| 179 |
+
|
| 180 |
+
pooled = tf.reduce_sum(h * scores, axis=1)
|
| 181 |
+
latent = self.latent(pooled)
|
| 182 |
+
latent = self.l2norm(latent)
|
| 183 |
+
|
| 184 |
+
# 🔥 출력만 float32
|
| 185 |
+
return tf.cast(latent, tf.float32)
|
| 186 |
+
|
| 187 |
+
# 3️⃣ 모델 로드
|
| 188 |
+
# ===============================
|
| 189 |
+
encoder = SentenceEncoder(vocab_size=vocab_size)
|
| 190 |
+
encoder(np.zeros((1, MAX_LEN), dtype=np.int32)) # 모델 빌드
|
| 191 |
+
encoder.load_weights(MODEL_PATH)
|
| 192 |
+
|
| 193 |
+
# ===============================
|
| 194 |
+
# 4️⃣ 벡터화 함수
|
| 195 |
+
# ===============================
|
| 196 |
+
def get_sentence_vector(sentence):
|
| 197 |
+
tokens = pad_sentence(encode_sentence(sentence))
|
| 198 |
+
vec = encoder(np.array([tokens])).numpy()[0]
|
| 199 |
+
return vec / np.linalg.norm(vec)
|
| 200 |
+
|
| 201 |
+
# ===============================
|
| 202 |
+
# 5️⃣ 가장 비슷한 문장 찾기
|
| 203 |
+
# ===============================
|
| 204 |
+
def find_most_similar(query, s1, s2, s3):
|
| 205 |
+
candidates = [s1, s2, s3]
|
| 206 |
+
candidate_vectors = np.stack([get_sentence_vector(c) for c in candidates]).astype(np.float32)
|
| 207 |
+
query_vector = get_sentence_vector(query)
|
| 208 |
+
|
| 209 |
+
sims = candidate_vectors @ query_vector # cosine similarity
|
| 210 |
+
top_idx = np.argmax(sims)
|
| 211 |
+
|
| 212 |
+
return {
|
| 213 |
+
"가장 비슷한 문장": candidates[top_idx],
|
| 214 |
+
"유사도": float(sims[top_idx])
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
# ===============================
|
| 218 |
+
# 6️⃣ Gradio UI
|
| 219 |
+
# ===============================
|
| 220 |
+
with gr.Blocks() as demo:
|
| 221 |
+
gr.Markdown("## 🔍 문장 유사도 검색기 (쿼리 1개 + 후보 3개)")
|
| 222 |
+
with gr.Row():
|
| 223 |
+
query_input = gr.Textbox(label="검색할 문장 (Query)", placeholder="여기에 입력")
|
| 224 |
+
with gr.Row():
|
| 225 |
+
s1_input = gr.Textbox(label="검색 후보 1")
|
| 226 |
+
s2_input = gr.Textbox(label="검색 후보 2")
|
| 227 |
+
s3_input = gr.Textbox(label="검색 후보 3")
|
| 228 |
+
output = gr.JSON(label="결과")
|
| 229 |
+
|
| 230 |
+
search_btn = gr.Button("가장 비슷한 문장 찾기")
|
| 231 |
+
search_btn.click(
|
| 232 |
+
fn=find_most_similar,
|
| 233 |
+
inputs=[query_input, s1_input, s2_input, s3_input],
|
| 234 |
+
outputs=output
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
demo.launch()
|