Upload 5 files
Browse files- generate_data.py +36 -0
- model.pt +3 -0
- requirements.txt +2 -0
- train.py +55 -0
- vocab.json +1 -0
generate_data.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random, json
|
| 2 |
+
random.seed(42)
|
| 3 |
+
|
| 4 |
+
def make_example():
|
| 5 |
+
t=random.choice(['add','subtract','multiply','compare','sequence','logic'])
|
| 6 |
+
if t=='add':
|
| 7 |
+
a,b=random.randint(1,99),random.randint(1,99); c=a+b
|
| 8 |
+
return {'question':f'What is {a} plus {b}?','answer':f'{a} plus {b} equals {c}. The answer is {c}.'}
|
| 9 |
+
if t=='subtract':
|
| 10 |
+
a,b=random.randint(1,99),random.randint(1,a if False else 99)
|
| 11 |
+
if b>a:a,b=b,a
|
| 12 |
+
c=a-b
|
| 13 |
+
return {'question':f'What is {a} minus {b}?','answer':f'Subtract {b} from {a}. The answer is {c}.'}
|
| 14 |
+
if t=='multiply':
|
| 15 |
+
a,b=random.randint(2,12),random.randint(2,12); c=a*b
|
| 16 |
+
return {'question':f'What is {a} times {b}?','answer':f'Multiply {a} by {b}. The answer is {c}.'}
|
| 17 |
+
if t=='compare':
|
| 18 |
+
a,b=random.randint(1,100),random.randint(1,100)
|
| 19 |
+
larger=max(a,b)
|
| 20 |
+
return {'question':f'Which number is larger, {a} or {b}?','answer':f'Compare {a} and {b}. {larger} is larger.'}
|
| 21 |
+
if t=='sequence':
|
| 22 |
+
start=random.randint(0,30); step=random.randint(1,10); seq=[start+i*step for i in range(4)]; nxt=seq[-1]+step
|
| 23 |
+
return {'question':f'Find the next number in this sequence: {seq[0]}, {seq[1]}, {seq[2]}, {seq[3]}.','answer':f'The sequence increases by {step} each time. The next number is {nxt}.'}
|
| 24 |
+
# simple valid deductive patterns
|
| 25 |
+
animal=random.choice(['cats','birds','robots','students','flowers']); category=random.choice(['mammals','living things','machines','objects'])
|
| 26 |
+
if animal=='cats': category='mammals'
|
| 27 |
+
if animal=='birds': category='animals'
|
| 28 |
+
if animal=='robots': category='machines'
|
| 29 |
+
if animal=='students': category='people'
|
| 30 |
+
if animal=='flowers': category='plants'
|
| 31 |
+
return {'question':f'All {animal} are {category}. A thing is a {animal}. What can we conclude?','answer':f'All {animal} belong to the group {category}. Therefore, the thing is a {category}.'}
|
| 32 |
+
|
| 33 |
+
if __name__=='__main__':
|
| 34 |
+
with open('dataset.jsonl','w',encoding='utf8') as f:
|
| 35 |
+
for _ in range(12000): f.write(json.dumps(make_example(),ensure_ascii=False)+'\n')
|
| 36 |
+
print('Created 12,000 original synthetic examples in dataset.jsonl')
|
model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8811a0285f7d5703e52bbd8164e10bf520d2fb0d60f271fa5729cfbeb6b8dcce
|
| 3 |
+
size 3192323
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
gradio
|
train.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, re, math, random, os
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
+
|
| 6 |
+
random.seed(42); torch.manual_seed(42)
|
| 7 |
+
DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
|
| 8 |
+
SPECIAL=['<pad>','<bos>','<eos>','<unk>']
|
| 9 |
+
def tokenize(s): return re.findall(r"[\w]+|[^\w\s]", s.lower())
|
| 10 |
+
|
| 11 |
+
with open('dataset.jsonl',encoding='utf8') as f: rows=[json.loads(x) for x in f]
|
| 12 |
+
texts=[tokenize(r['question'])+tokenize(r['answer']) for r in rows]
|
| 13 |
+
vocab={t:i for i,t in enumerate(SPECIAL)}
|
| 14 |
+
for text in texts:
|
| 15 |
+
for t in text:
|
| 16 |
+
if t not in vocab: vocab[t]=len(vocab)
|
| 17 |
+
with open('vocab.json','w',encoding='utf8') as f: json.dump(vocab,f)
|
| 18 |
+
|
| 19 |
+
class PairDataset(Dataset):
|
| 20 |
+
def __len__(self): return len(rows)
|
| 21 |
+
def __getitem__(self,i):
|
| 22 |
+
r=rows[i]; enc=[vocab.get(t,3) for t in tokenize(r['question'])]
|
| 23 |
+
dec=[1]+[vocab.get(t,3) for t in tokenize(r['answer'])]+[2]
|
| 24 |
+
return enc,dec
|
| 25 |
+
|
| 26 |
+
def collate(batch):
|
| 27 |
+
def pad(seqs):
|
| 28 |
+
m=max(map(len,seqs)); return torch.tensor([s+[0]*(m-len(s)) for s in seqs])
|
| 29 |
+
return pad([x[0] for x in batch]),pad([x[1] for x in batch])
|
| 30 |
+
|
| 31 |
+
class MiniReason(nn.Module):
|
| 32 |
+
def __init__(self,vocab_size,d_model=128,nhead=4,layers=2):
|
| 33 |
+
super().__init__(); self.emb=nn.Embedding(vocab_size,d_model,padding_idx=0); self.pos=nn.Embedding(512,d_model)
|
| 34 |
+
self.net=nn.Transformer(d_model=d_model,nhead=nhead,num_encoder_layers=layers,num_decoder_layers=layers,dim_feedforward=256,batch_first=True)
|
| 35 |
+
self.out=nn.Linear(d_model,vocab_size)
|
| 36 |
+
def forward(self,src,tgt):
|
| 37 |
+
sp=torch.arange(src.size(1),device=src.device)[None,:]; tp=torch.arange(tgt.size(1),device=tgt.device)[None,:]
|
| 38 |
+
se=self.emb(src)+self.pos(sp); te=self.emb(tgt)+self.pos(tp)
|
| 39 |
+
causal=torch.triu(torch.ones(tgt.size(1),tgt.size(1),device=tgt.device,dtype=torch.bool),1)
|
| 40 |
+
z=self.net(se,te, tgt_mask=causal, src_key_padding_mask=src.eq(0), tgt_key_padding_mask=tgt.eq(0), memory_key_padding_mask=src.eq(0))
|
| 41 |
+
return self.out(z)
|
| 42 |
+
|
| 43 |
+
model=MiniReason(len(vocab)).to(DEVICE)
|
| 44 |
+
loader=DataLoader(PairDataset(),batch_size=64,shuffle=True,collate_fn=collate)
|
| 45 |
+
opt=torch.optim.AdamW(model.parameters(),lr=0.001)
|
| 46 |
+
loss_fn=nn.CrossEntropyLoss(ignore_index=0)
|
| 47 |
+
EPOCHS=int(os.environ.get('EPOCHS','8'))
|
| 48 |
+
for epoch in range(EPOCHS):
|
| 49 |
+
model.train(); total=0
|
| 50 |
+
for src,dec in loader:
|
| 51 |
+
src,dec=src.to(DEVICE),dec.to(DEVICE); inp=dec[:,:-1]; target=dec[:,1:]
|
| 52 |
+
opt.zero_grad(); logits=model(src,inp); loss=loss_fn(logits.reshape(-1,len(vocab)),target.reshape(-1)); loss.backward(); nn.utils.clip_grad_norm_(model.parameters(),1.0); opt.step(); total+=loss.item()
|
| 53 |
+
print(f'Epoch {epoch+1}/{EPOCHS} loss={total/len(loader):.4f}')
|
| 54 |
+
torch.save(model.state_dict(),'model.pt')
|
| 55 |
+
print('Training complete; saved model.pt and vocab.json')
|
vocab.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"<pad>": 0, "<bos>": 1, "<eos>": 2, "<unk>": 3, "all": 4, "cats": 5, "are": 6, "mammals": 7, ".": 8, "a": 9, "thing": 10, "is": 11, "what": 12, "can": 13, "we": 14, "conclude": 15, "?": 16, "belong": 17, "to": 18, "the": 19, "group": 20, "therefore": 21, ",": 22, "robots": 23, "machines": 24, "95": 25, "minus": 26, "18": 27, "subtract": 28, "from": 29, "answer": 30, "77": 31, "87": 32, "plus": 33, "equals": 34, "182": 35, "find": 36, "next": 37, "number": 38, "in": 39, "this": 40, "sequence": 41, ":": 42, "2": 43, "12": 44, "22": 45, "32": 46, "increases": 47, "by": 48, "10": 49, "each": 50, "time": 51, "42": 52, "which": 53, "larger": 54, "5": 55, "or": 56, "4": 57, "compare": 58, "and": 59, "28": 60, "30": 61, "58": 62, "19": 63, "20": 64, "21": 65, "1": 66, "23": 67, "6": 68, "15": 69, "24": 70, "33": 71, "9": 72, "29": 73, "8": 74, "11": 75, "90": 76, "55": 77, "35": 78, "times": 79, "multiply": 80, "98": 81, "44": 82, "54": 83, "49": 84, "61": 85, "46": 86, "45": 87, "91": 88, "students": 89, "people": 90, "71": 91, "132": 92, "birds": 93, "animals": 94, "13": 95, "43": 96, "36": 97, "59": 98, "7": 99, "26": 100, "3": 101, "27": 102, "31": 103, "39": 104, "60": 105, "120": 106, "88": 107, "48": 108, "73": 109, "101": 110, "flowers": 111, "plants": 112, "66": 113, "97": 114, "16": 115, "17": 116, "93": 117, "181": 118, "69": 119, "157": 120, "84": 121, "38": 122, "56": 123, "94": 124, "37": 125, "50": 126, "70": 127, "68": 128, "119": 129, "104": 130, "105": 131, "85": 132, "25": 133, "47": 134, "57": 135, "67": 136, "86": 137, "76": 138, "147": 139, "108": 140, "53": 141, "0": 142, "52": 143, "146": 144, "128": 145, "63": 146, "34": 147, "75": 148, "62": 149, "137": 150, "65": 151, "14": 152, "80": 153, "40": 154, "79": 155, "92": 156, "82": 157, "89": 158, "109": 159, "72": 160, "81": 161, "74": 162, "136": 163, "78": 164, "99": 165, "196": 166, "107": 167, "83": 168, "138": 169, "64": 170, "100": 171, "165": 172, "117": 173, "103": 174, "106": 175, "41": 176, "51": 177, "160": 178, "111": 179, "118": 180, "96": 181, "135": 182, "127": 183, "112": 184, "180": 185, "161": 186, "152": 187, "113": 188, "169": 189, "110": 190, "123": 191, "114": 192, "191": 193, "148": 194, "163": 195, "124": 196, "115": 197, "156": 198, "129": 199, "159": 200, "116": 201, "141": 202, "151": 203, "134": 204, "168": 205, "145": 206, "102": 207, "139": 208, "121": 209, "144": 210, "125": 211, "193": 212, "162": 213, "140": 214, "179": 215, "154": 216, "131": 217, "174": 218, "122": 219, "149": 220, "126": 221, "130": 222, "158": 223, "188": 224, "142": 225, "133": 226, "143": 227, "155": 228, "166": 229, "187": 230, "153": 231, "175": 232, "173": 233, "167": 234, "150": 235, "164": 236, "176": 237, "177": 238, "184": 239, "189": 240, "190": 241, "183": 242, "178": 243, "171": 244, "185": 245, "186": 246, "170": 247, "192": 248, "197": 249, "172": 250}
|