File size: 13,676 Bytes
cafd528
 
90a6174
 
 
f82693c
90a6174
f82693c
 
 
 
 
 
 
 
c41b0cf
7f12cbc
f82693c
90a6174
f82693c
 
 
 
 
 
 
 
 
 
 
 
90a6174
f82693c
 
 
 
 
90a6174
f82693c
 
 
 
 
 
 
 
 
 
 
 
ab6754e
f82693c
 
 
6c265e3
f82693c
 
 
 
6c265e3
f82693c
 
ab6754e
 
6c265e3
ab6754e
 
f82693c
 
41c502c
f82693c
 
41c502c
 
 
f82693c
 
 
 
41c502c
 
 
 
 
 
 
 
f82693c
 
 
 
 
 
41c502c
 
 
 
 
 
90a6174
a638654
90a6174
f82693c
 
 
 
41c502c
 
a638654
 
 
 
41c502c
a638654
 
 
 
 
41c502c
a638654
 
 
 
 
41c502c
a638654
 
 
 
 
 
 
 
 
 
 
 
 
 
f82693c
a638654
 
 
f82693c
 
 
a638654
 
 
 
f82693c
 
a638654
90a6174
 
 
 
f82693c
 
 
 
90a6174
a638654
 
90a6174
 
 
 
cafd528
 
 
133d2fa
cafd528
696479e
 
 
 
cafd528
696479e
 
87b968d
c41b0cf
696479e
 
 
 
 
 
 
859ea70
696479e
 
 
 
 
cafd528
c41b0cf
 
696479e
 
 
 
 
 
 
 
 
859ea70
696479e
 
 
 
 
 
c41b0cf
cafd528
 
 
ee9c45d
 
 
 
696479e
 
b68669a
cafd528
696479e
cafd528
 
 
 
 
696479e
cafd528
696479e
cafd528
b826d8a
90a6174
 
4f620b3
 
0c4369c
4f620b3
 
 
 
 
 
 
 
 
 
0c4369c
4f620b3
 
 
 
 
 
 
 
0c4369c
 
 
 
 
 
 
 
b826d8a
90a6174
 
41947ce
90a6174
 
 
 
 
 
 
 
 
 
 
 
 
 
4f620b3
ac9ca0c
90a6174
 
 
 
0c4369c
 
90a6174
 
cc8e480
094d892
cc8e480
 
 
2f67ef0
 
cc8e480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f67ef0
0c4369c
cc8e480
 
 
 
2f67ef0
cc8e480
 
094d892
cc8e480
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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 = 128 # κΈ°μ‘΄ μ½”λ“œμ—μ„œ 200으둜 섀정됨
batch_size = 64

# 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"
TOKENIZER_PATH1 = "en_bpe.model"

if not os.path.exists(DATA_PATH):
    download_file(
        "https://huggingface.co/datasets/Yuchan5386/Translation-set/resolve/main/shuffled.jsonl?download=true",
        DATA_PATH
    )
if not os.path.exists(TOKENIZER_PATH):
    download_file(
        "https://huggingface.co/datasets/Yuchan5386/Translation-set/resolve/main/unigram.model?download=true",
        TOKENIZER_PATH
    )
if not os.path.exists(TOKENIZER_PATH1):
    download_file(
        "https://huggingface.co/datasets/Yuchan5386/Translation-set/resolve/main/bpe.model?download=true",
        TOKENIZER_PATH1
    )

sp = spm.SentencePieceProcessor(TOKENIZER_PATH)
sp_en = spm.SentencePieceProcessor(TOKENIZER_PATH1)

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}")

epad_id = sp_en.piece_to_id("<pad>") if sp.piece_to_id("<pad>") != -1 else 0
estart_id = sp_en.piece_to_id("<start>")
esep_id = sp_en.piece_to_id("<sep>")
eend_id = sp_en.piece_to_id("<end>")
eunk_id = sp_en.piece_to_id("<unk>")
evocab_size = sp_en.get_piece_size()
print(f"βœ… Vocabulary size: {evocab_size}")

def text_to_ids(text):
    return sp.encode(text, out_type=int)

def ids_to_text(ids):
    return sp.decode(ids)

def etext_to_ids(text):
    return sp_en.encode(text, out_type=int)

def eids_to_text(ids):
    return sp_en.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)
            prompt = data["ko"]
            answer = data["en"]

            # =======================
            # Encoder input: ID λ ˆλ²¨μ—μ„œ 특수 토큰 λͺ…μ‹œ
            # =======================
            enc_ids = text_to_ids(prompt)
            enc_ids = enc_ids[:max_len]  # max_len μ œν•œ

            # =======================
            # Decoder input: <sos> + answer
            # =======================
            dec_input_ids = [estart_id] + text_to_ids(answer)
            dec_input_ids = dec_input_ids[:max_len]

            # =======================
            # Target: answer + <eos>
            # =======================
            target_ids = etext_to_ids(answer) + [eend_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//num_heads)
        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 + x)
        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//num_heads)
        self.cross_mha = layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model//num_heads)
        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 + x)
        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=128, dropout=0.1):
        super().__init__()
        self.max_len = max_len
        self.d_model = d_model
        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)
        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=6, d_model=256, num_heads=4, dff=768, input_vocab_size=vocab_size, target_vocab_size=evocab_size, max_len=128, 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)
    # μ˜΅ν‹°λ§ˆμ΄μ € μ„€μ •
    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_translation_beam(model, input_text, max_len=128, beam_width=5):
    # Encoder input
    enc_ids = text_to_ids(input_text)
    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)

    # Beam μ΄ˆκΈ°ν™”
    beams = [( [start_id], 0.0 )]  # (generated_ids, log_prob)

    for _ in range(max_len):
        all_candidates = []

        for seq, score in beams:
            if seq[-1] == end_id:
                all_candidates.append((seq, score))
                continue

            dec_input = seq[-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)
            next_logits = logits[0, len(dec_input) - 1].numpy()
            next_logits[pad_id] = -1e9  # νŒ¨λ”© μ–΅μ œ

            # μƒμœ„ beam_width 후보 선택
            top_indices = np.argsort(next_logits)[-beam_width:][::-1]
            top_probs = tf.nn.softmax(next_logits[top_indices]).numpy()

            for token_id, prob in zip(top_indices, top_probs):
                candidate = (seq + [int(token_id)], score + np.log(prob + 1e-9))
                all_candidates.append(candidate)

        # Score κΈ°μ€€ μƒμœ„ beam_width μœ μ§€
        beams = sorted(all_candidates, key=lambda x: x[1], reverse=True)[:beam_width]

        # λͺ¨λ“  beam λλ‚¬μœΌλ©΄ μ’…λ£Œ
        if all(seq[-1] == end_id for seq, _ in beams):
            break

    # 졜고 점수 beam 선택
    best_seq = beams[0][0]
    # start_id 제거 ν›„ decode
    return eids_to_text(best_seq[1:])

# μ‚¬μš© μ˜ˆμ‹œ
src_text = "μ•ˆλ…•ν•˜μ„Έμš”! 였늘 λ‚ μ”¨λŠ” μ–΄λ•Œμš”?"
translation = generate_translation_beam(chat_model, src_text, max_len=128, beam_width=5)
print("λ²ˆμ—­ κ²°κ³Ό:", translation)