File size: 10,291 Bytes
7d7e323
 
63439a6
7d7e323
 
63439a6
 
 
 
7d7e323
63439a6
be37607
 
 
 
 
 
 
63439a6
 
 
 
 
7d7e323
63439a6
 
 
 
 
 
be37607
 
 
 
 
 
 
 
 
 
 
 
7d7e323
63439a6
 
7d7e323
63439a6
 
7d7e323
63439a6
 
 
7d7e323
63439a6
 
 
 
 
 
7d7e323
63439a6
7d7e323
63439a6
7d7e323
 
63439a6
 
7d7e323
63439a6
 
 
7d7e323
 
 
63439a6
7d7e323
 
63439a6
 
 
 
7d7e323
63439a6
7d7e323
 
 
63439a6
7d7e323
63439a6
7d7e323
63439a6
 
 
 
e33316b
 
 
 
63439a6
e33316b
 
63439a6
 
e33316b
 
 
63439a6
e33316b
 
 
 
 
 
 
 
 
 
 
 
7d7e323
 
 
e33316b
 
 
 
 
 
 
7d7e323
e33316b
 
 
 
63439a6
 
7d7e323
 
63439a6
7d7e323
 
 
 
63439a6
 
7d7e323
 
63439a6
7d7e323
 
 
63439a6
 
 
7d7e323
63439a6
7d7e323
 
 
 
 
 
 
 
 
 
 
 
63439a6
e33316b
 
 
 
 
 
 
 
 
 
7d7e323
e33316b
 
 
 
 
 
 
 
 
7d7e323
63439a6
 
7d7e323
63439a6
7d7e323
 
 
 
 
63439a6
 
7d7e323
63439a6
 
7d7e323
63439a6
7d7e323
 
 
 
 
 
 
 
63439a6
 
7d7e323
63439a6
7d7e323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63439a6
7d7e323
 
 
 
 
 
 
 
63439a6
7d7e323
63439a6
 
7d7e323
 
 
 
 
 
 
 
 
63439a6
 
7d7e323
63439a6
7d7e323
 
e33316b
 
 
 
 
 
 
7d7e323
63439a6
 
7d7e323
63439a6
 
7d7e323
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
# TPU ์ตœ์ ํ™” Flax + JAX ReLM
import os, math, numpy as np, sentencepiece as spm, requests, tqdm
from functools import partial
from typing import Any
import jax, jax.numpy as jnp
from jax import random
from flax import linen as nn
from flax.training import train_state, checkpoints
import optax
import requests

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} ์ €์žฅ๋จ")
# ------------------
# Config
# ------------------
SEQ_LEN = 512
GLOBAL_BATCH = 256
LIMIT = 200_000
VOCAB_MODEL = "ko_unigram.model"
CORPUS_PATH = "corpus.txt"
SEED = 42
LEARNING_RATE = 1e-4
EPOCHS = 1

if not os.path.exists(CORPUS_PATH):
    download_file(
        "https://huggingface.co/datasets/Yuchan5386/Prototype/resolve/main/corpus_ko.txt?download=true",
        CORPUS_PATH
    )

if not os.path.exists(VOCAB_MODEL):
    download_file(
        "https://huggingface.co/Yuchan5386/inlam-100m/resolve/main/ko_unigram.model?download=true",
        VOCAB_MODEL
    )

DTYPE = jnp.bfloat16 if jax.local_devices()[0].platform == "tpu" else jnp.float32
NUM_DEVICES = jax.device_count()
PER_DEVICE_BATCH = GLOBAL_BATCH // NUM_DEVICES
print("devices:", jax.devices(), "dtype:", DTYPE)

# ------------------
# Tokenizer
# ------------------
sp = spm.SentencePieceProcessor()
sp.load(VOCAB_MODEL)
pad_id = sp.piece_to_id("<pad>") if sp.piece_to_id("<pad>")!=-1 else 0
start_id = sp.piece_to_id("<start>")
end_id = sp.piece_to_id("<end>")
vocab_size = sp.get_piece_size()
print("vocab_size:", vocab_size, "pad_id:", pad_id, "start_id:", start_id, "end_id:", end_id)

# ------------------
# Data pipeline
# ------------------
def line_to_ids(line, max_len=SEQ_LEN):
    ids = sp.encode(line.strip(), out_type=int)
    if len(ids) > max_len-1: ids = ids[:max_len-1]
    ids += [end_id] + [pad_id]*(max_len-len(ids)-1)
    return np.array(ids, dtype=np.int32)

def build_dataset(corpus_path, limit=LIMIT):
    arr = []
    with open(corpus_path, "r", encoding="utf-8") as f:
        for i, line in enumerate(f):
            if i>=limit: break
            line=line.strip()
            if not line: continue
            arr.append(line_to_ids(line))
    data = np.stack(arr, axis=0)
    print("Loaded dataset:", data.shape)
    return data

data_np = build_dataset(CORPUS_PATH, LIMIT)
inputs = data_np
targets = np.concatenate([data_np[:,1:], np.full((data_np.shape[0],1), pad_id, np.int32)], axis=1)

def create_batch_iter(inputs, targets, batch_size, rng):
    idx = np.arange(inputs.shape[0]); rng.shuffle(idx)
    for i in range(0,len(idx)-batch_size+1,batch_size):
        batch_idx = idx[i:i+batch_size]
        yield inputs[batch_idx], targets[batch_idx]

def shard(xs): return xs.reshape(NUM_DEVICES, -1, xs.shape[1])

class SwiGLU(nn.Module):
    d_model: int
    @nn.compact
    def __call__(self, x):
        x_f32 = x.astype(jnp.float32)
        proj = nn.Dense(self.d_model*2, dtype=jnp.float32)(x_f32)
        x_val, x_gate = jnp.split(proj, 2, axis=-1)
        out = x_val * nn.silu(x_gate)
        out = nn.Dense(self.d_model, dtype=jnp.float32)(out)
        return out.astype(x.dtype)

class LoU(nn.Module):
    d_model: int
    clip_value: float = 5.0
    eps: float = 1e-6
    @nn.compact
    def __call__(self, x):
        x_f32 = x.astype(jnp.float32)
        residual = x_f32
        x_norm = nn.LayerNorm(epsilon=1e-5, dtype=jnp.float32)(x_f32)
        Q = nn.Dense(self.d_model, dtype=jnp.float32)
        K = nn.Dense(self.d_model, dtype=jnp.float32)
        V = nn.Dense(self.d_model, dtype=jnp.float32)
        q,k,v = Q(x_norm), K(x_norm), V(x_norm)
        g_q = (jnp.tanh(q)+1)/2
        g_k = (jnp.tanh(k)+1)/2
        score = g_q * g_k
        alpha_dynamic = nn.Dense(1, dtype=jnp.float32)(x_norm)
        # EMA scan along seq axis
        score_t = jnp.transpose(score,(1,0,2))
        alpha_t = jnp.transpose(alpha_dynamic,(1,0,2))
        def step(prev, cur):
            s, a = cur
            new = a*s + (1-a)*prev
            return new,new
        init = score_t[0]
        _, ema_seq = jax.lax.scan(step, init, (score_t[1:], alpha_t[1:]))
        ema_full = jnp.concatenate([init[None,...], ema_seq], 0)
        ema = jnp.transpose(ema_full,(1,0,2))
        out = v * ema + residual
        out = nn.LayerNorm(epsilon=1e-5, dtype=jnp.float32)(out)
        return SwiGLU(self.d_model)(out).astype(x.dtype)


class Lo(nn.Module):
    d_model:int
    dtype:Any=DTYPE
    @nn.compact
    def __call__(self,x):
        h=nn.Dense(64,dtype=self.dtype)(x); h=nn.silu(h)
        h=nn.Dense(self.d_model,dtype=self.dtype)(h)
        return nn.LayerNorm(epsilon=1e-5,dtype=self.dtype)(h)+x

class Block(nn.Module):
    d_model:int
    dtype:Any=DTYPE
    @nn.compact
    def __call__(self,x):
        x=LoU(self.d_model,self.dtype)(x)
        x=Lo(self.d_model,self.dtype)(x)
        return x

class ReLM(nn.Module):
    vocab_size:int; max_seq_len:int; d_model:int; n_layers:int; dtype:Any=DTYPE
    def setup(self):
        self.token_embed = nn.Embed(self.vocab_size,self.d_model,dtype=self.dtype)
        self.pos_embed = nn.Embed(self.max_seq_len,self.d_model,dtype=self.dtype)
        self.blocks=[Block(self.d_model,self.dtype) for _ in range(self.n_layers)]
        self.ln_f=nn.LayerNorm(epsilon=1e-5,dtype=self.dtype)
    def __call__(self,x,deterministic=True):
        b,seq=x.shape
        pos=jnp.arange(seq)[None,:]
        x=self.token_embed(x)+self.pos_embed(pos)
        for blk in self.blocks: x=blk(x)
        x=self.ln_f(x)
        logits=jnp.einsum("bld,vd->blv",x,self.token_embed.embedding)
        return logits

def smoothed_ce(logits, targets, pad_id, eps=0.1):
    logits = logits.astype(jnp.float32)
    targets = targets.astype(jnp.int32)
    vocab = logits.shape[-1]
    mask = (targets != pad_id).astype(jnp.float32)
    one_hot = jax.nn.one_hot(targets, vocab)
    smooth = (1-eps)*one_hot + eps/vocab
    log_probs = jax.nn.log_softmax(logits, axis=-1)
    loss = -jnp.sum(smooth * log_probs, axis=-1) * mask
    return jnp.sum(loss) / (jnp.sum(mask)+1e-8)

def masked_ppl(logits, targets, pad_id, eps=0.1):
    logits = logits.astype(jnp.float32)
    targets = targets.astype(jnp.int32)
    vocab = logits.shape[-1]
    mask = (targets != pad_id).astype(jnp.float32)
    one_hot = jax.nn.one_hot(targets, vocab)
    smooth = (1-eps)*one_hot + eps/vocab
    log_probs = jax.nn.log_softmax(logits, axis=-1)
    loss = -jnp.sum(smooth*log_probs, axis=-1) * mask
    return jnp.exp(jnp.sum(loss)/(jnp.sum(mask)+1e-8))

# ------------------
# Train state
# ------------------
class TrainState(train_state.TrainState): pass
def create_train_state(rng,model,lr):
    params=model.init(rng,jnp.zeros((1,SEQ_LEN),dtype=jnp.int32))["params"]
    tx=optax.chain(optax.clip_by_global_norm(1.0),optax.adamw(lr,b1=0.9,b2=0.95,eps=1e-8))
    return TrainState.create(apply_fn=model.apply,params=params,tx=tx)

# ------------------
# pmap step
# ------------------
@partial(jax.pmap, axis_name="batch")
def train_step(state,bx,by,rngs):
    def loss_fn(params):
        logits=state.apply_fn({"params":params},bx,deterministic=False)
        return smoothed_ce(logits,by,pad_id),logits
    (loss,logits),grads=jax.value_and_grad(loss_fn,has_aux=True)(state.params)
    grads=jax.lax.pmean(grads,"batch")
    state=state.apply_gradients(grads=grads)
    metrics={"loss":loss,"ppl":masked_ppl(logits,by,pad_id)}
    metrics=jax.lax.pmean(metrics,"batch")
    return state,metrics

# ------------------
# Top-p sampling (JAX-native)
# ------------------
def top_p_sample(rng, logits, p=0.9, temperature=1.0):
    probs=jax.nn.softmax(logits/temperature)
    sorted_probs,sorted_idx=jax.lax.top_k(probs,logits.shape[-1])
    cum_probs=jnp.cumsum(sorted_probs)
    mask=cum_probs<=p
    top_probs=jnp.where(mask,sorted_probs,0.0)
    top_probs=top_probs/jnp.sum(top_probs)
    return int(sorted_idx[jax.random.categorical(rng,jnp.log(top_probs))])

def generate_text(state,prompt,max_gen=256,p=0.9,temperature=0.8,min_len=20):
    params=jax.tree_map(lambda x: np.array(x[0]),state.params)
    tokens=sp.encode("<start> "+prompt,out_type=int)
    generated=tokens.copy()
    rng=random.PRNGKey(SEED)
    for step in range(max_gen):
        cur=generated[-SEQ_LEN:]
        if len(cur)<SEQ_LEN: cur=cur+[pad_id]*(SEQ_LEN-len(cur))
        x=jnp.array([cur],dtype=jnp.int32)
        logits=model.apply({"params":params},x,deterministic=True)[0,len(generated)-1]
        logits=logits.at[end_id].add(-5.0).at[pad_id].add(-10.0)
        next_id=top_p_sample(rng,logits,p,temperature)
        generated.append(next_id)
        if next_id==end_id and len(generated)>=min_len: break
    return sp.decode(generated)

# ------------------
# Training
# ------------------
rng=random.PRNGKey(SEED)
rng,init_rng=random.split(rng)
model=ReLM(vocab_size=vocab_size,max_seq_len=SEQ_LEN,d_model=512,n_layers=9,dtype=DTYPE)
state=create_train_state(init_rng,model,LEARNING_RATE)
state=jax.device_put_replicated(state,jax.local_devices())

global_step=0
for epoch in range(EPOCHS):
    print(f"Epoch {epoch+1}/{EPOCHS}")
    np_rng=np.random.default_rng(SEED+epoch)
    batch_iter=create_batch_iter(inputs,targets,GLOBAL_BATCH,np_rng)
    pbar=tqdm.tqdm(batch_iter,total=max(1,inputs.shape[0]//GLOBAL_BATCH))
    for bx,by in pbar:
        bx_sh,by_sh=shard(bx),shard(by)
        state,metrics=train_step(state,bx_sh,by_sh,jax.random.split(rng,NUM_DEVICES))
        m=jax.tree_util.tree_map(lambda x:x[0],metrics)
        pbar.set_postfix(loss=float(m["loss"]),ppl=float(m["ppl"]))
        global_step+=1

# ------------------
# Save
# ------------------
save_dir="./checkpoints"
os.makedirs(save_dir,exist_ok=True)
# ๊ธฐ์กด
# checkpoints.save_checkpoint(save_dir,jax.tree_map(lambda x:np.array(x),state),step=global_step,keep=3)

# ์ˆ˜์ •
import jax.tree_util
checkpoints.save_checkpoint(save_dir, jax.tree_util.tree_map(lambda x: np.array(x), state), step=global_step, keep=3)

print("Saved checkpoint to",save_dir)

# ------------------
# Generate
# ------------------
print("\n\n===== ์ƒ์„ฑ ๊ฒฐ๊ณผ =====")
print(generate_text(state,"์ง€๋‚œ 2๋…„ ๋™์•ˆ ์ถœ์—ฐ์—ฐ์ด ๊ตญ๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์—ฐ๊ตฌ๋ฅผ",p=0.9))