Upload train.py with huggingface_hub
Browse files106 unmodified lines1071081091101101111121131141151161161171181191201 unmodified line1221231241251261271281291271301311321331341351311361371381391401416 unmodified lines1481491501441511521461531541551561571491581591601611621521531631641651661671681697 unmodified lines1771781791671801811821831701711721731741751761771841851861871881891901911921931941953 unmodified lines199200201187202203204205106 unmodified lines
def _encode_stream(ds, tok, key, max_tok, ratio=1.0): out, total = [], 0 target = int(max_tok * ratio); V = len(tok) target = int(max_tok * ratio) V = len(tok) for item in ds: if total >= target: break text = item.get(key, "") if not text: continue ids = tok.encode(text)[:2048] + [tok.eos_token_id] ids = [i for i in ids if 0 <= i < V] if any(i < 0 or i >= V for i in ids): continue out.extend(ids); total += len(ids) return out
1 unmodified line os.makedirs(cfg.data_dir, exist_ok=True) t = AutoTokenizer.from_pretrained(cfg.tokenizer_name, trust_remote_code=True) if t.pad_token is None: t.pad_token = t.eos_token V = len(t) print(f"tokenizer vocab = {V}") p = os.path.join(cfg.data_dir, "code.npy") if not os.path.exists(p): ds = load_dataset("nick007x/github-code-2025", split="train", streaming=True) np.save(p, np.array(_encode_stream(ds, t, "content", cfg.max_tokens_code), dtype=np.uint32)) arr = np.array(_encode_stream(ds, t, "content", cfg.max_tokens_code), dtype=np.uint32) assert arr.max() < V, f"code 越界: max={arr.max()}, V={V}" np.save(p, arr) p = os.path.join(cfg.data_dir, "math.npy") if not os.path.exists(p): ds = load_dataset("open-web-math/open-web-math", split="train", streaming=True) np.save(p, np.array(_encode_stream(ds, t, "text", cfg.max_tokens_math), dtype=np.uint32)) arr = np.array(_encode_stream(ds, t, "text", cfg.max_tokens_math), dtype=np.uint32) assert arr.max() < V, f"math 越界: max={arr.max()}, V={V}" np.save(p, arr) p = os.path.join(cfg.data_dir, "general.npy") if not os.path.exists(p): all_ids = []6 unmodified lines text = item.get("text", "") if not text: continue ids = t.encode(text)[:2048] + [t.eos_token_id] ids = [i for i in ids if 0 <= i < len(t)] if any(i < 0 or i >= V for i in ids): continue all_ids.extend(ids); total += len(ids) np.save(p, np.array(all_ids, dtype=np.uint32)) arr = np.array(all_ids, dtype=np.uint32) assert arr.max() < V, f"general 越界: max={arr.max()}, V={V}" np.save(p, arr)
class TokenDataset(Dataset): def __init__(self, ids, L): self.ids=ids; self.L=L; self.n=max(0,(len(ids)-1)//L) def __init__(self, ids, L, vocab_size): self.ids = ids; self.L = L; self.vocab_size = vocab_size self.n = max(0, (len(ids) - 1) // L) def __len__(self): return self.n def __getitem__(self, i): s=i*self.L; c=self.ids[s:s+self.L+1] return torch.tensor(c[:-1],dtype=torch.long), torch.tensor(c[1:],dtype=torch.long) s = i * self.L c = self.ids[s:s + self.L + 1].astype(np.int64) c = np.clip(c, 0, self.vocab_size - 1) return torch.tensor(c[:-1], dtype=torch.long), torch.tensor(c[1:], dtype=torch.long)
def _cycle(loader): while True:7 unmodified linesdef train(cfg): set_seed(cfg.seed) _t = AutoTokenizer.from_pretrained(cfg.tokenizer_name, trust_remote_code=True) cfg.vocab_size = len(_t); print(f"vocab={cfg.vocab_size}") cfg.vocab_size = len(_t) print(f"cfg.vocab_size = {cfg.vocab_size}") device = torch.device(cfg.device) prepare_data(cfg) g_ids = np.load(os.path.join(cfg.data_dir,"general.npy")) c_ids = np.load(os.path.join(cfg.data_dir,"code.npy")) m_ids = np.load(os.path.join(cfg.data_dir,"math.npy")) for name, ids in [("general",g_ids),("code",c_ids),("math",m_ids)]: bad = np.sum((ids<0)|(ids>=cfg.vocab_size)); print(f"{name}: {len(ids)} tokens, 越界 {bad}") assert bad==0 ld = lambda ids,sh: DataLoader(TokenDataset(ids,cfg.max_seq_len), batch_size=cfg.batch_size, shuffle=sh, drop_last=True) g_it,c_it,m_it = _cycle(ld(g_ids,True)),_cycle(ld(c_ids,True)),_cycle(ld(m_ids,True)) g_ids = np.load(os.path.join(cfg.data_dir, "general.npy")) c_ids = np.load(os.path.join(cfg.data_dir, "code.npy")) m_ids = np.load(os.path.join(cfg.data_dir, "math.npy")) for name, ids in [("general", g_ids), ("code", c_ids), ("math", m_ids)]: print(f"{name}: {len(ids)} tokens, max={ids.max()}") assert ids.max() < cfg.vocab_size, f"{name} 越界" ld = lambda ids, sh: DataLoader(TokenDataset(ids, cfg.max_seq_len, cfg.vocab_size), batch_size=cfg.batch_size, shuffle=sh, drop_last=True) g_it, c_it, m_it = _cycle(ld(g_ids, True)), _cycle(ld(c_ids, True)), _cycle(ld(m_ids, True)) model = FallbackMoE(cfg).to(device) print(f"params: {sum(p.numel() for p in model.parameters())/1e6:.1f}M") opt = torch.optim.AdamW(model.parameters(), lr=cfg.lr, betas=(0.9,0.95), weight_decay=0.1)3 unmodified lines if mod in (0,2): x,y=next(g_it); is_g=True elif mod==1: x,y=next(c_it); is_g=False else: x,y=next(m_it); is_g=False x,y = x.to(device),y.to(device); B=x.shape[0] x,y = x.to(device), y.to(device); B=x.shape[0] lg_no,lg_fb,rl = model.forward_both(x) def chunked_ce(logits,targets): V_=logits.shape[-1]; logits=logits.view(-1,V_); targets=targets.reshape(-1)train.py+34-19