Spaces:
Running
Running
File size: 6,458 Bytes
1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 a8ba472 1a0a3d9 |
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 |
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import sentencepiece as spm
import gradio as gr
import requests
import os
# ----------------------
# ํ์ผ ๋ค์ด๋ก๋ ์ ํธ
# ----------------------
def download_file(url, save_path):
r = requests.get(url, stream=True)
r.raise_for_status()
with open(save_path, "wb") as f:
for chunk in r.iter_content(8192*2):
f.write(chunk)
print(f"โ
{save_path} ์ ์ฅ๋จ")
MODEL_PATH = "encoder.weights.h5"
TOKENIZER_PATH = "bpe.model"
if not os.path.exists(MODEL_PATH):
download_file(
"https://huggingface.co/OpenLab-NLP/openlem-prototype/resolve/main/encoder_simcse.weights.h5?download=true",
MODEL_PATH
)
if not os.path.exists(TOKENIZER_PATH):
download_file(
"https://huggingface.co/OpenLab-NLP/openlem-prototype/resolve/main/bpe.model?download=true",
TOKENIZER_PATH
)
MAX_LEN = 128
EMBED_DIM = 384
LATENT_DIM = 384
DROPOUT_RATE = 0.01
# ===============================
# 1๏ธโฃ ํ ํฌ๋์ด์ ๋ก๋ฉ
# ===============================
sp = spm.SentencePieceProcessor(TOKENIZER_PATH)
pad_id = sp.piece_to_id("<pad>") if sp.piece_to_id("<pad>") != -1 else 0
vocab_size = sp.get_piece_size()
def encode_sentence(sentence, max_len=MAX_LEN):
return sp.encode(sentence, out_type=int)[:max_len]
def pad_sentence(tokens):
return tokens + [pad_id]*(MAX_LEN - len(tokens))
class EncoderBlock(tf.keras.layers.Layer):
def __init__(self, embed_dim=EMBED_DIM, ff_dim=1152, seq_len=MAX_LEN):
super().__init__()
self.embed_dim = embed_dim
self.seq_len = seq_len
self.fc1 = layers.Dense(ff_dim)
self.fc2 = layers.Dense(embed_dim)
self.fc3 = layers.Dense(ff_dim//2)
self.fc4 = layers.Dense(embed_dim)
self.attn = layers.Dense(1)
self.token_mixer = layers.Dense(seq_len)
self.token_gate = layers.Dense(seq_len, activation='sigmoid')
self.ln = layers.LayerNormalization(epsilon=1e-5)
self.ln1 = layers.LayerNormalization(epsilon=1e-5)
self.ln2 = layers.LayerNormalization(epsilon=1e-5)
self.ln3 = layers.LayerNormalization(epsilon=1e-5)
self.ln4 = layers.LayerNormalization(epsilon=1e-5)
def call(self, x, mask):
mask = mask
# x: (B, L, D)
x_norm = self.ln(x)
h = self.fc1(x_norm)
g, v = tf.split(h, 2, axis=-1)
h = tf.nn.silu(g) * v
h = self.fc2(h)
h = x + self.ln1(h)
scores = self.attn(h)
scores = tf.where(tf.equal(mask[..., tf.newaxis], 0), -1e9, scores)
scores = tf.nn.softmax(scores, axis=1)
attn = h + self.ln2(h * scores)
v = tf.transpose(attn, [0, 2, 1])
v = self.token_mixer(v) * self.token_gate(v)
v = tf.transpose(v, [0, 2, 1])
x_norm = attn + self.ln3(v)
x = self.fc3(x_norm)
x = tf.nn.silu(x)
x = self.fc4(x)
return x_norm + self.ln4(x)
class L2NormLayer(layers.Layer):
def __init__(self, axis=1, epsilon=1e-10, **kwargs):
super().__init__(**kwargs)
self.axis = axis
self.epsilon = epsilon
def call(self, inputs):
return tf.math.l2_normalize(inputs, axis=self.axis, epsilon=self.epsilon)
def get_config(self):
return {"axis": self.axis, "epsilon": self.epsilon, **super().get_config()}
class SentenceEncoder(tf.keras.Model):
def __init__(self, vocab_size, embed_dim=384, latent_dim=384, max_len=128, pad_id=pad_id):
super().__init__()
self.pad_id = pad_id
self.embed = layers.Embedding(vocab_size, embed_dim)
self.pos_embed = layers.Embedding(input_dim=max_len, output_dim=embed_dim)
self.blocks = [EncoderBlock() for _ in range(2)]
self.attn_pool = layers.Dense(1)
self.ln_f = layers.LayerNormalization(epsilon=1e-5, dtype=tf.float32)
self.latent = layers.Dense(latent_dim, activation=None) # tanh ์ ๊ฑฐ
self.l2norm = L2NormLayer() # ์ถ๊ฐ
def call(self, x):
positions = tf.range(tf.shape(x)[1])[tf.newaxis, :]
x_embed = self.embed(x) + self.pos_embed(positions)
mask = tf.cast(tf.not_equal(x, self.pad_id), tf.float32)
x = x_embed
for block in self.blocks:
x = block(x, mask)
x = self.ln_f(x)
scores = self.attn_pool(x)
scores = tf.where(tf.equal(mask[..., tf.newaxis], 0), -1e9, scores)
scores = tf.nn.softmax(scores, axis=1)
pooled = tf.reduce_sum(x * scores, axis=1)
latent = self.latent(pooled)
return self.l2norm(latent) # L2 ์ ๊ทํ ํ ๋ฐํ
# 3๏ธโฃ ๋ชจ๋ธ ๋ก๋
# ===============================
encoder = SentenceEncoder(vocab_size=vocab_size)
encoder(np.zeros((1, MAX_LEN), dtype=np.int32)) # ๋ชจ๋ธ ๋น๋
encoder.load_weights(MODEL_PATH)
# ===============================
# 4๏ธโฃ ๋ฒกํฐํ ํจ์
# ===============================
def get_sentence_vector(sentence):
tokens = pad_sentence(encode_sentence(sentence))
vec = encoder(np.array([tokens])).numpy()[0]
return vec / np.linalg.norm(vec)
# ===============================
# 5๏ธโฃ ๊ฐ์ฅ ๋น์ทํ ๋ฌธ์ฅ ์ฐพ๊ธฐ
# ===============================
def find_most_similar(query, s1, s2, s3):
candidates = [s1, s2, s3]
candidate_vectors = np.stack([get_sentence_vector(c) for c in candidates]).astype(np.float32)
query_vector = get_sentence_vector(query)
sims = candidate_vectors @ query_vector # cosine similarity
top_idx = np.argmax(sims)
return {
"๊ฐ์ฅ ๋น์ทํ ๋ฌธ์ฅ": candidates[top_idx],
"์ ์ฌ๋": float(sims[top_idx])
}
# ===============================
# 6๏ธโฃ Gradio UI
# ===============================
with gr.Blocks() as demo:
gr.Markdown("## ๐ ๋ฌธ์ฅ ์ ์ฌ๋ ๊ฒ์๊ธฐ (์ฟผ๋ฆฌ 1๊ฐ + ํ๋ณด 3๊ฐ)")
with gr.Row():
query_input = gr.Textbox(label="๊ฒ์ํ ๋ฌธ์ฅ (Query)", placeholder="์ฌ๊ธฐ์ ์
๋ ฅ")
with gr.Row():
s1_input = gr.Textbox(label="๊ฒ์ ํ๋ณด 1")
s2_input = gr.Textbox(label="๊ฒ์ ํ๋ณด 2")
s3_input = gr.Textbox(label="๊ฒ์ ํ๋ณด 3")
output = gr.JSON(label="๊ฒฐ๊ณผ")
search_btn = gr.Button("๊ฐ์ฅ ๋น์ทํ ๋ฌธ์ฅ ์ฐพ๊ธฐ")
search_btn.click(
fn=find_most_similar,
inputs=[query_input, s1_input, s2_input, s3_input],
outputs=output
)
demo.launch() |