File size: 12,343 Bytes
7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 1e5945c 7f390c3 e8b3f86 7f390c3 37ba2d7 7f390c3 37ba2d7 1289019 63584a6 37ba2d7 1e5945c 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 37ba2d7 7f390c3 |
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
import tensorflow as tf
from tensorflow.keras import layers, Model
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras import mixed_precision
import sentencepiece as spm
import os, json
import requests
print('1')
tf.get_logger().setLevel("ERROR")
SEED = 42
tf.random.set_seed(SEED)
np.random.seed(SEED)
max_len = 150 # ๊ธฐ์กด ์ฝ๋์์ 200์ผ๋ก ์ค์ ๋จ
batch_size = 128
# TPU ์ด๊ธฐํ (๊ธฐ์กด ์ฝ๋์ ๋์ผ)
try:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu="local")
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
print("โ
TPU ์ด๊ธฐํ ์๋ฃ:", resolver.cluster_spec().as_dict())
on_tpu = True
except Exception as e:
print("โ ๏ธ TPU ๋ฏธ์ฌ์ฉ, GPU/CPU๋ก ์งํ:", e)
strategy = tf.distribute.get_strategy()
on_tpu = False
# Mixed precision (๊ธฐ์กด ์ฝ๋์ ๋์ผ)
policy = mixed_precision.Policy("mixed_bfloat16" if on_tpu else "float32")
mixed_precision.set_global_policy(policy)
print("โ
Mixed precision:", policy)
# =======================
# 1) ํ์ผ ๋ค์ด๋ก๋ ๋ฐ ํ ํฌ๋์ด์ ์ด๊ธฐํ (๊ธฐ์กด ์ฝ๋์ ๋์ผ)
# =======================
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} ์ ์ฅ๋จ")
DATA_PATH = "converted.jsonl"
TOKENIZER_PATH = "ko_unigram.model"
if not os.path.exists(DATA_PATH):
download_file(
"https://huggingface.co/datasets/Yuchan5386/TinyInst/resolve/main/output.jsonl?download=true",
DATA_PATH
)
if not os.path.exists(TOKENIZER_PATH):
download_file(
"https://huggingface.co/datasets/Yuchan5386/TinyInst/resolve/main/ko_unigram.model?download=true",
TOKENIZER_PATH
)
sp = spm.SentencePieceProcessor(TOKENIZER_PATH)
pad_id = sp.piece_to_id("<pad>") if sp.piece_to_id("<pad>") != -1 else 0
start_id = sp.piece_to_id("<start>")
sep_id = sp.piece_to_id("<sep>")
end_id = sp.piece_to_id("<end>")
unk_id = sp.piece_to_id("<unk>")
vocab_size = sp.get_piece_size()
print(f"โ
Vocabulary size: {vocab_size}")
def text_to_ids(text):
return sp.encode(text, out_type=int)
def ids_to_text(ids):
return sp.decode(ids)
# =======================
# 3) ๋ชจ๋ธ ๋ ์ด์ด (๊ธฐ์กด ์ฝ๋ ์ ์ง)
# =======================
class SwiGLU(layers.Layer):
def __init__(self, d_model, d_ff):
super().__init__()
self.proj = layers.Dense(d_ff)
self.out = layers.Dense(d_model)
def call(self, x):
x_proj = self.proj(x)
x_val, x_gate = tf.split(x_proj, 2, axis=-1)
return self.out(x_val * tf.nn.silu(x_gate))
class gMLPBlock(layers.Layer):
def __init__(self, d_model, seq_len, dropout=0.1):
super().__init__()
self.d_model = d_model
self.seq_len = seq_len
self.norm = layers.LayerNormalization(epsilon=1e-6)
# FFN: Channel Expansion
# d_model * 4๋ก ํ์ฅ
self.channel_proj = layers.Dense(d_model * 4, use_bias=True)
self.dropout = layers.Dropout(dropout)
# Spatial Gating Unit (SGU)
self.sgu_norm = layers.LayerNormalization(epsilon=1e-6)
self.sgu_proj = layers.Dense(seq_len, use_bias=False)
# ์ถ๋ ฅ ์ฐจ์์ d_model * 2 (U์ ์ฐจ์)๋ก ์ค์
self.sgu_final = layers.Dense(d_model * 2, use_bias=True)
self.out_proj = layers.Dense(d_model, use_bias=True)
def call(self, x, training=False):
# 1. Norm and Channel Expansion
residual = x
x_norm = self.norm(x)
x_proj = self.channel_proj(x_norm) # Shape: (B, L, 4*D)
# 2. Split (U and V streams)
u, v = tf.split(x_proj, 2, axis=-1) # u, v Shape: (B, L, 2*D)
# 3. Spatial Gating Unit (SGU)
v_norm = self.sgu_norm(v)
v_norm_T = tf.transpose(v_norm, perm=[0, 2, 1]) # (B, 2D, L)
# ๐ก ํ ํฐ ๋ฏน์ฑ ๋ฐ์ (์ํ์ค ์ถ์ผ๋ก Dense ์ ์ฉ)
v_proj = self.sgu_proj(v_norm_T) # (B, 2D, L)
v_proj_T = tf.transpose(v_proj, perm=[0, 2, 1]) # (B, L, 2D)
# 4. Activation and Gate Generation
# ํ์ค gMLP๋ U์ GELU๋ฅผ ์ ์ฉํ๊ณ V๋ ์ ํ ๊ฒ์ดํธ๋ก ์ฌ์ฉ
# ์ฌ๊ธฐ์๋ U์ GELU๋ฅผ ์ ์ฉ
u_act = tf.nn.gelu(u)
v_gate = self.sgu_final(v_proj_T) # Shape: (B, L, 2*D)
# 5. Gating and Contraction
z = u_act * v_gate # ๊ฒ์ดํ
z = self.dropout(z, training=training)
out = self.out_proj(z) # Shape: (B, L, D)
# 6. Residual Connection
return residual + out
class CrossBlock(layers.Layer):
def __init__(self, clip_value=5.0, eps=1e-6): # ๐ก d_model ์ธ์ ์ถ๊ฐ
super().__init__()
self.clip_value = clip_value
self.eps = eps
# ๐ก ์์ : ์ถ๋ ฅ ์ฐจ์์ 1์์ d_model๋ก ๋ณ๊ฒฝ
def call(self, x, z):
# a์ shape: (Batch, Seq_len, D_model)
g_q = (tf.nn.tanh(x) + 1.0) / 2.0
g_k = (tf.nn.tanh(z) + 1.0) / 2.0
score = (g_q * g_k)
score = tf.cumsum(score, axis=1)
seq_len = tf.shape(score)[1]
# [1, 2, 3, ..., L]์ D_model ์ฐจ์์ผ๋ก ํ์ฅ
count_for_mean = tf.cast(tf.range(seq_len) + 1, score.dtype)
count_for_mean = tf.reshape(count_for_mean, (1, seq_len, 1))
# ๋์ ํฉ์ ํ์ฌ๊น์ง์ ํ ํฐ ๊ฐ์๋ก ๋๋์ด ํ๊ท ๋์ ํฉ ๊ณ์ฐ (B, L, D)
score_mean = score / count_for_mean
# ์ ๊ทํ ๋ถ๋ชจ ์ค์
denom = tf.maximum(score_mean, self.eps)
score_norm = score / denom
# -----------------------------------------------
score_clipped = tf.clip_by_value(score_norm, -self.clip_value, self.clip_value)
y = score_clipped * z
return y
class LoU(layers.Layer):
def __init__(self, d_model, clip_value=5.0, eps=1e-6):
super().__init__()
self.d_model = d_model
self.clip_value = float(clip_value)
self.mha = layers.MultiHeadAttention(8, 20)
self.norm1 = layers.LayerNormalization(epsilon=1e-5, dtype='float32')
self.norm = layers.LayerNormalization(epsilon=1e-5, dtype='float32')
self.glu = SwiGLU(d_model, 320)
self.cross = CrossBlock()
def call(self, x, z):
x_f32 = tf.cast(x, tf.float32)
residual = x_f32
x = self.norm1(x)
x_comb = self.mha(x, x, x, use_causal_mask=True)
out = self.norm(x_comb + residual)
out = self.cross(out, z)
out = self.glu(out)
return tf.cast(out, x.dtype)
# =======================
# 4) AlphaS2S ๋ชจ๋ธ (๊ธฐ์กด ์ฝ๋ ์ ์ง)
# =======================
class AlphaS2S(tf.keras.Model):
def __init__(self, num_layers, d_model, num_heads, input_vocab_size, target_vocab_size, max_len=200, dropout=0.1):
super().__init__()
self.max_len = max_len
self.d_model = d_model
# ์ธ์ฝ๋์ ๋์ฝ๋ ์๋ฒ ๋ฉ ๋ฐ ์์น ์๋ฒ ๋ฉ์ ๋ชจ๋ max_len์ ์ฌ์ฉ
self.enc_embedding = layers.Embedding(input_vocab_size, d_model)
self.enc_pos_embedding = layers.Embedding(max_len, d_model)
self.dec_embedding = layers.Embedding(target_vocab_size, d_model)
self.dec_pos_embedding = layers.Embedding(max_len, d_model)
# EncoderBlock๊ณผ LoU๋ ๊ธฐ์กด ์ฝ๋์ ๋์ผํ ๊ตฌ์กฐ
self.enc_layers = [gMLPBlock(d_model, seq_len=max_len) for _ in range(num_layers)]
self.dec_layers = [LoU(d_model) for _ in range(num_layers)]
self.final_layer = layers.Dense(target_vocab_size, use_bias=False)
def call(self, inputs, training=False):
# enc_inputs์ dec_inputs๋ ๋์ผํ ์ํ์ค (Unified Input)
enc_inputs = inputs["enc_inputs"]
dec_inputs = inputs["dec_inputs"]
enc_pos = tf.range(tf.shape(enc_inputs)[1])[tf.newaxis, :]
dec_pos = tf.range(tf.shape(dec_inputs)[1])[tf.newaxis, :]
# ์ธ์ฝ๋ ์คํ
x = self.enc_embedding(enc_inputs) + self.enc_pos_embedding(enc_pos)
# Note: ๋ง์คํฌ ์์ -> Bi-directional (BERT-like Encoder)
for layer in self.enc_layers: x = layer(x, training=training)
enc_out = x # ์ธ์ฝ๋์ ์ต์ข
์ถ๋ ฅ (๋์ฝ๋์ 'z' ์
๋ ฅ)
# ๋์ฝ๋ ์คํ
y = self.dec_embedding(dec_inputs) + self.dec_pos_embedding(dec_pos)
# Note: LoU๋ ๋ด๋ถ์ ์ผ๋ก EMA๋ฅผ ์ฌ์ฉํ๋ฉฐ, ์ผ๋ฐ์ ์ธ Cross-Attention ๋ธ๋ก์ ์ญํ ์ ์ํ
for layer in self.dec_layers: y = layer(y, enc_out, training=training)
return self.final_layer(y)
# ๊ฐ์ค์น ์ ์ฅ
chat_model = AlphaS2S(num_layers=4, d_model=160, num_heads=8,
input_vocab_size=vocab_size, target_vocab_size=vocab_size, max_len=max_len)
dummy_input = {
"enc_inputs": tf.zeros((1, max_len), dtype=tf.int32),
"dec_inputs": tf.zeros((1, max_len), dtype=tf.int32)
}
_ = chat_model(dummy_input)
chat_model.load_weights('/kaggle/working/chat_model.weights.h5')
print("๋ชจ๋ธ ๊ฐ์ค์น ๋ก๋ ์๋ฃ!")
# =======================
# 6) ์ถ๋ก ํจ์ (๊ธฐ์กด ์ฝ๋ ์ ์ง)
# =======================
def generate_text_topp(model, prompt, max_len=150, max_gen=100, p=0.9, temperature=0.8, min_len=20):
# ์ธ์ฝ๋ ์
๋ ฅ์ <start> Prompt <sep> ๋ง ์ฌ์ฉ
model_input = text_to_ids(f"<start> {prompt} <sep>")
model_input = model_input[:max_len]
generated = list(model_input)
for step in range(max_gen):
current_len = len(generated)
# ํ์ฌ๊น์ง ์์ฑ๋ ์ํ์ค๋ฅผ ์
๋ ฅ์ผ๋ก ์ฌ์ฉ
if current_len > max_len:
input_seq = generated[-max_len:]
else:
input_seq = generated
# ํจ๋ฉ
input_padded = np.pad(input_seq, (0, max_len - len(input_seq)), constant_values=pad_id)
input_tensor = tf.convert_to_tensor([input_padded])
# ๋ชจ๋ธ ์ถ๋ก (enc_inputs, dec_inputs ๋ชจ๋ ๋์ผํ ์ํ์ค๋ฅผ ์ฌ์ฉ)
dummy_input = {
"enc_inputs": input_tensor,
"dec_inputs": input_tensor
}
logits = model(dummy_input, training=False)
# ๋ค์ ํ ํฐ์ ๋ก์ง์ ์ํ์ค์ ๋ง์ง๋ง ํ ํฐ ์์น์์ ๊ฐ์ ธ์ด (0-based index: current_len - 1)
# ํ์ง๋ง ํจ๋ฉ ํ input_tensor์ ์ค์ ์ํ์ค ๊ธธ์ด๋ len(input_seq)
next_token_logits = logits[0, len(input_seq) - 1].numpy()
# ํน์ ํ ํฐ ์์ฑ ์ต์
next_token_logits[end_id] -= 5.0
next_token_logits[pad_id] -= 10.0
probs = tf.nn.softmax(next_token_logits / temperature).numpy()
sorted_indices = np.argsort(probs)[::-1]
sorted_probs = probs[sorted_indices]
# Top-p (Nucleus) Sampling
cumulative_probs = np.cumsum(sorted_probs)
cutoff = np.searchsorted(cumulative_probs, p)
top_indices = sorted_indices[:cutoff + 1]
top_probs = sorted_probs[:cutoff + 1]
top_probs /= np.sum(top_probs)
next_token_id = np.random.choice(top_indices, p=top_probs)
if next_token_id == end_id and len(generated) >= min_len:
break
generated.append(int(next_token_id))
# <start> ํ ํฐ ์ ๊ฑฐ ๋ฐ <sep> ์ด์ ๋ถ๋ถ ์ ๊ฑฐ
try:
sep_index = generated.index(sep_id)
# <sep> ์ดํ๋ถํฐ <end> ์ด์ ๊น์ง์ ์๋ต๋ง ๋ฐํ
result_ids = generated[sep_index + 1:]
try:
end_index = result_ids.index(end_id)
result_ids = result_ids[:end_index]
except ValueError:
pass
return ids_to_text(result_ids)
except ValueError:
return ids_to_text(generated) # <sep>์ด ์์ผ๋ฉด ์ ์ฒด ๋ฐํ
print("\n\n===== ์์ฑ ๊ฒฐ๊ณผ =====")
# ๋ชจ๋ธ์ด 1 epoch๋ง ํ์ต๋์์ผ๋ฏ๋ก ์๋ฏธ ์๋ ๊ฒฐ๊ณผ๊ฐ ์๋ ์ ์์ต๋๋ค.
print(generate_text_topp(chat_model, "์ ๊ฐ ์ด๋ฐ๊ฐ ๋ฒ์ค๋ฅผ ํ์ผ ํด์ ์ค๋น ์ข ํด์ผ๊ฒ ์ด์. ์ฌ๋ฏธ์๋ ๋ํ์์ต๋๋ค!", p=0.9))
|