File size: 13,524 Bytes
cafd528 90a6174 f82693c 90a6174 f82693c 42abc8c a004b22 f82693c 90a6174 f82693c 90a6174 f82693c 90a6174 f82693c 19949b0 f82693c 19949b0 f82693c 19949b0 f82693c 90a6174 a638654 90a6174 f82693c a638654 f82693c a638654 f82693c a638654 f82693c a638654 90a6174 f82693c 90a6174 a638654 90a6174 cafd528 133d2fa cafd528 696479e cafd528 696479e 87b968d 696479e 1bf639d 696479e cafd528 696479e 1bf639d 696479e 6866f20 cafd528 5a66735 696479e b68669a cafd528 696479e cafd528 696479e cafd528 696479e cafd528 b826d8a 90a6174 4f620b3 0c4369c 4f620b3 0c4369c 4f620b3 0c4369c b826d8a 90a6174 876bffc 90a6174 0c4369c 90a6174 4f620b3 ac9ca0c 90a6174 0c4369c 90a6174 2f67ef0 0c4369c 2f67ef0 0c4369c 2f67ef0 0c4369c 2f67ef0 0c4369c 2f67ef0 0c4369c 2f67ef0 0c4369c 2f67ef0 |
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 329 330 331 332 333 |
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 = 256 # κΈ°μ‘΄ μ½λμμ 200μΌλ‘ μ€μ λ¨
batch_size = 16
# 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/Multiturn/resolve/main/dataset_shuffled.jsonl?download=true",
DATA_PATH
)
if not os.path.exists(TOKENIZER_PATH):
download_file(
"https://huggingface.co/datasets/Yuchan5386/Multiturn/resolve/main/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("<sos>")
context_s_id = sp.piece_to_id("<context>")
context_e_id = sp.piece_to_id("</context>")
user_s_id = sp.piece_to_id("<user>")
user_e_id = sp.piece_to_id("</user>")
end_id = sp.piece_to_id("<eos>")
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)
# =======================
# JSONL β TF Dataset λ‘λ (ID λ 벨 νΉμ ν ν° ν¬ν¨)
# =======================
def jsonl_stream(file_path):
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
data = json.loads(line)
context = data["context"]
prompt = data["prompt"]
answer = data["answer"]
# =======================
# Encoder input: ID λ 벨μμ νΉμ ν ν° λͺ
μ
# =======================
enc_ids = [context_s_id] + text_to_ids(context) + [context_e_id] + \
[user_s_id] + text_to_ids(prompt) + [user_e_id]
enc_ids = enc_ids[:max_len] # max_len μ ν
# =======================
# Decoder input: <sos> + answer
# =======================
dec_input_ids = [start_id] + text_to_ids(answer)
dec_input_ids = dec_input_ids[:max_len]
# =======================
# Target: answer + <eos>
# =======================
target_ids = text_to_ids(answer) + [end_id]
target_ids = target_ids[:max_len]
# =======================
# Padding
# =======================
enc_ids += [pad_id] * (max_len - len(enc_ids))
dec_input_ids += [pad_id] * (max_len - len(dec_input_ids))
target_ids += [pad_id] * (max_len - len(target_ids))
yield (
tf.convert_to_tensor(enc_ids, dtype=tf.int32),
tf.convert_to_tensor(dec_input_ids, dtype=tf.int32),
tf.convert_to_tensor(target_ids, dtype=tf.int32),
)
# =======================
# TF Dataset μμ±
# =======================
dataset = tf.data.Dataset.from_generator(
lambda: jsonl_stream(DATA_PATH),
output_signature=(
tf.TensorSpec(shape=(max_len,), dtype=tf.int32), # enc_inputs
tf.TensorSpec(shape=(max_len,), dtype=tf.int32), # dec_inputs
tf.TensorSpec(shape=(max_len,), dtype=tf.int32), # target
)
)
# νμ΅μ μν΄ λμ
λ리 ννλ‘ λ§€ν
def map_fn(enc_input, dec_input, dec_target):
return {"enc_inputs": enc_input, "dec_inputs": dec_input}, dec_target
dataset = dataset.map(map_fn, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.shuffle(1000, seed=SEED).batch(batch_size, drop_remainder=True).prefetch(tf.data.AUTOTUNE)
with strategy.scope():
dist_dataset = strategy.experimental_distribute_dataset(dataset)
print("β
ID λ 벨 νΉμ ν ν° μ μ© Dataset λ‘λ μλ£:", dist_dataset)
# =======================
# 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 EncoderBlock(layers.Layer):
def __init__(self, d_model, num_heads, dff, dropout=0.1):
super().__init__()
self.mha = layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model)
self.ffn = SwiGLU(d_model, dff)
self.norm1 = layers.LayerNormalization(epsilon=1e-6)
self.norm2 = layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = layers.Dropout(dropout)
self.dropout2 = layers.Dropout(dropout)
def call(self, x, mask=None, training=False):
attn_out = self.dropout1(self.mha(x, x, x, attention_mask=mask), training=training)
out1 = self.norm1(attn_out)
ffn_out = self.dropout2(self.ffn(out1), training=training)
return self.norm2(out1 + ffn_out)
class DecoderBlock(layers.Layer):
def __init__(self, d_model, num_heads, dff, dropout=0.1):
super().__init__()
self.self_mha = layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model)
self.cross_mha = layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model)
self.ffn = SwiGLU(d_model, dff)
self.norm1 = layers.LayerNormalization(epsilon=1e-6)
self.norm2 = layers.LayerNormalization(epsilon=1e-6)
self.norm3 = layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = layers.Dropout(dropout)
self.dropout2 = layers.Dropout(dropout)
self.dropout3 = layers.Dropout(dropout)
def call(self, x, enc_out, training=False):
attn1 = self.dropout1(self.self_mha(x, x, x, use_causal_mask=True), training=training)
out1 = self.norm1(attn1)
attn2 = self.dropout2(self.cross_mha(out1, enc_out, enc_out), training=training)
out2 = self.norm2(out1 + attn2)
ffn_out = self.dropout3(self.ffn(out2), training=training)
return self.norm3(out2 + ffn_out)
class Transformer(tf.keras.Model):
def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size, target_vocab_size, max_len=256, dropout=0.1):
super().__init__()
self.max_len = max_len
self.d_model = d_model
self.enc_embedding = layers.Embedding(input_vocab_size, 256)
self.enc_pos_embedding = layers.Embedding(max_len, 256)
self.dec_embedding = layers.Embedding(target_vocab_size, 256)
self.dec_pos_embedding = layers.Embedding(max_len, 256)
self.enc_layers = [EncoderBlock(d_model, num_heads, dff, dropout) for _ in range(num_layers)]
self.dec_layers = [DecoderBlock(d_model, num_heads, dff, dropout) for _ in range(num_layers)]
self.final_layer = layers.Dense(target_vocab_size, use_bias=False)
def call(self, inputs, training=False):
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)
for layer in self.enc_layers: x = layer(x, training=training)
enc_out = x
y = self.dec_embedding(dec_inputs) + self.dec_pos_embedding(dec_pos)
for layer in self.dec_layers: y = layer(y, enc_out, training=training)
return self.final_layer(y)
# 5) νμ΅ μ€μ λ° μ€ν
# =======================
def smoothed_loss_keras(y_true, y_pred, eps=0.1):
y_true = tf.cast(y_true, tf.int32)
mask = tf.cast(tf.not_equal(y_true, pad_id), tf.float32)
vocab = tf.shape(y_pred)[-1]
y_true_oh = tf.one_hot(y_true, depth=vocab, dtype=tf.float32)
y_true_ls = (1.0 - eps) * y_true_oh + eps / tf.cast(vocab, tf.float32)
log_probs = tf.nn.log_softmax(y_pred, axis=-1)
per_tok = -tf.reduce_sum(y_true_ls * log_probs, axis=-1)
per_tok = per_tok * mask
return tf.reduce_sum(per_tok) / (tf.reduce_sum(mask) + 1e-8)
def masked_perplexity(y_true, y_pred, eps=0.1):
y_true = tf.cast(y_true, tf.int32)
mask = tf.cast(tf.not_equal(y_true, pad_id), tf.float32)
vocab = tf.shape(y_pred)[-1]
y_true_oh = tf.one_hot(y_true, depth=vocab, dtype=tf.float32)
y_true_ls = (1.0 - eps) * y_true_oh + eps / tf.cast(vocab, tf.float32)
log_probs = tf.nn.log_softmax(y_pred, axis=-1)
per_tok = -tf.reduce_sum(y_true_ls * log_probs, axis=-1)
per_tok = per_tok * mask
mean_loss = tf.reduce_sum(per_tok) / (tf.reduce_sum(mask) + 1e-8)
return tf.exp(mean_loss)
def create_lr_schedule(initial_lr=5e-5, decay_steps=10000, decay_rate=0.9):
return tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=initial_lr,
decay_steps=decay_steps,
decay_rate=decay_rate,
staircase=False
)
with strategy.scope():
# β οΈ μμ : chat_vocab_size λμ μ μλ vocab_size μ¬μ©
chat_model = Transformer(num_layers=2, d_model=384, num_heads=6, dff=1216, input_vocab_size=vocab_size, target_vocab_size=vocab_size, max_len=256, dropout=0.1)
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)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction='none')
# μ΅ν°λ§μ΄μ μ€μ
optimizer = tf.keras.optimizers.Adam(
learning_rate=create_lr_schedule(),
beta_1=0.9,
beta_2=0.95,
epsilon=1e-8,
clipnorm=1.0
)
chat_model.compile(optimizer=optimizer, loss=smoothed_loss_keras, metrics=[masked_perplexity])
chat_model.summary()
print("β
λͺ¨λΈ μ»΄νμΌ μλ£, νμ΅ μμ...")
# β οΈ νμ΅ μ€ν
history = chat_model.fit(dataset, epochs=1, verbose=1)
# κ°μ€μΉ μ μ₯
chat_model.save_weights("chat_model.weights.h5")
print("\nβ
λͺ¨λΈ κ°μ€μΉ μ μ₯ μλ£!")
def generate_text_topp(model, context, prompt, max_len=256, max_gen=100, p=0.9, temperature=0.8, min_len=20):
# Encoder input: ID λ λ²¨λ‘ νΉμ ν ν° μ½μ
enc_ids = [context_s_id] + text_to_ids(context) + [context_e_id] + \
[user_s_id] + text_to_ids(prompt) + [user_e_id]
enc_ids = enc_ids[-max_len:] # κΈΈμ΄ μ ν
enc_tensor = tf.convert_to_tensor([np.pad(enc_ids, (0, max_len - len(enc_ids)), constant_values=pad_id)], dtype=tf.int32)
# Decoder input: <sos>λ‘ μμ
generated = [start_id]
for step in range(max_gen):
dec_input = generated[-max_len:] # max_len μ μ§
dec_tensor = tf.convert_to_tensor([np.pad(dec_input, (0, max_len - len(dec_input)), constant_values=pad_id)], dtype=tf.int32)
# λͺ¨λΈ μΆλ‘
logits = model({"enc_inputs": enc_tensor, "dec_inputs": dec_tensor}, training=False)
# λ§μ§λ§ ν ν° μμΉ logits μ¬μ©
next_token_logits = logits[0, len(dec_input) - 1].numpy()
# νΉμ ν ν° μ΅μ
next_token_logits[pad_id] -= 10.0
next_token_logits[context_s_id] -= 5.0
next_token_logits[context_e_id] -= 5.0
next_token_logits[user_s_id] -= 5.0
next_token_logits[user_e_id] -= 5.0
# Softmax + Top-p
probs = tf.nn.softmax(next_token_logits / temperature).numpy()
sorted_indices = np.argsort(probs)[::-1]
sorted_probs = probs[sorted_indices]
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))
# <sos> μ κ±° ν ν
μ€νΈλ‘ λ³ν
result_ids = generated[1:] # 첫 ν ν° <sos> μ κ±°
return ids_to_text(result_ids)
# μμ μ¬μ©
print("\n\n===== μμ± κ²°κ³Ό =====")
print(generate_text_topp(chat_model, "λν μμ", "μλ
νμΈμ! μ΄λ»κ² μ§λ΄μ
¨λμ?", p=0.9))
|