Upload train.py with huggingface_hub
Browse files106 unmodified lines1071081091101111121131141151161171181191 unmodified line1211221231241251261271281291301311321331346 unmodified lines1411421431441451461471481491501511521531541551567 unmodified lines1641651661671681691701711721731741751761771781791803 unmodified lines184185186187188189190106 unmodified linesdef _encode_stream(ds, tok, key, max_tok, ratio=1.0):out, total = [], 0target = int(max_tok * ratio); V = len(tok)for item in ds:if total >= target: breaktext = item.get(key, "")if not text: continueids = tok.encode(text)[:2048] + [tok.eos_token_id]ids = [i for i in ids if 0 <= i < V]out.extend(ids); total += len(ids)return out1 unmodified lineos.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_tokenp = 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))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))p = os.path.join(cfg.data_dir, "general.npy")if not os.path.exists(p):all_ids = []6 unmodified linestext = item.get("text", "")if not text: continueids = t.encode(text)[:2048] + [t.eos_token_id]ids = [i for i in ids if 0 <= i < len(t)]all_ids.extend(ids); total += len(ids)np.save(p, np.array(all_ids, dtype=np.uint32))class TokenDataset(Dataset):def __init__(self, ids, L): self.ids=ids; self.L=L; self.n=max(0,(len(ids)-1)//L)def __len__(self): return self.ndef __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)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}")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==0ld = 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))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 linesif mod in (0,2): x,y=next(g_it); is_g=Trueelif mod==1: x,y=next(c_it); is_g=Falseelse: x,y=next(m_it); is_g=Falsex,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)106 unmodified lines1071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401416 unmodified lines1481491501511521531541551561571581591601611621631641651661671681697 unmodified lines1771781791801811821831841851861871881891901911921931941953 unmodified lines199200201202203204205106 unmodified linesdef _encode_stream(ds, tok, key, max_tok, ratio=1.0):out, total = [], 0target = int(max_tok * ratio)V = len(tok)for item in ds:if total >= target: breaktext = item.get(key, "")if not text: continueids = tok.encode(text)[:2048] + [tok.eos_token_id]if any(i < 0 or i >= V for i in ids): continueout.extend(ids); total += len(ids)return out1 unmodified lineos.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_tokenV = 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)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)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 linestext = item.get("text", "")if not text: continueids = t.encode(text)[:2048] + [t.eos_token_id]if any(i < 0 or i >= V for i in ids): continueall_ids.extend(ids); total += len(ids)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, vocab_size):self.ids = ids; self.L = L; self.vocab_size = vocab_sizeself.n = max(0, (len(ids) - 1) // L)def __len__(self): return self.ndef __getitem__(self, i):s = i * self.Lc = 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"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)]: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 linesif mod in (0,2): x,y=next(g_it); is_g=Trueelif mod==1: x,y=next(c_it); is_g=Falseelse: x,y=next(m_it); is_g=Falsex,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