Vrel 0.1.0, 0.2.0 and 0.3.0
Browse filesFiles changed (46)
- 0.1.0/model.jsonAdded+12
- 0.1.0/tokenizer.jsonAdded+1
- 0.1.0/vrel.ptAdded+3
- 0.1.0/vrel/__init__.pyAdded+3
- 0.1.0/vrel/__main__.pyAdded+272
- 0.1.0/vrel/bigram.pyAdded+25
- 0.1.0/vrel/data.pyAdded+194
- 0.1.0/vrel/generate.pyAdded+114
- 0.1.0/vrel/model.pyAdded+366
- 0.1.0/vrel/optim.pyAdded+85
- 0.1.0/vrel/quant.pyAdded+25
- 0.1.0/vrel/stories.pyAdded+143
- 0.1.0/vrel/tokenizer.pyAdded+172
- 0.1.0/vrel/train.pyAdded+216
- 0.1.0/vrel/watch.pyAdded+141
- 0.2.0/model.jsonAdded+12
- 0.2.0/tokenizer.jsonAdded+1
- 0.2.0/vrel.ptAdded+3
- 0.2.0/vrel/__init__.pyAdded+3
- 0.2.0/vrel/__main__.pyAdded+272
- 0.2.0/vrel/bigram.pyAdded+25
- 0.2.0/vrel/data.pyAdded+194
- 0.2.0/vrel/generate.pyAdded+114
- 0.2.0/vrel/model.pyAdded+366
- 0.2.0/vrel/optim.pyAdded+85
- 0.2.0/vrel/quant.pyAdded+25
- 0.2.0/vrel/stories.pyAdded+143
- 0.2.0/vrel/tokenizer.pyAdded+172
- 0.2.0/vrel/train.pyAdded+216
- 0.2.0/vrel/watch.pyAdded+141
- 0.3.0/model.jsonAdded+12
- 0.3.0/tokenizer.jsonAdded+1
- 0.3.0/vrel.ptAdded+3
- 0.3.0/vrel/__init__.pyAdded+3
- 0.3.0/vrel/__main__.pyAdded+272
- 0.3.0/vrel/bigram.pyAdded+25
- 0.3.0/vrel/data.pyAdded+194
- 0.3.0/vrel/generate.pyAdded+114
- 0.3.0/vrel/model.pyAdded+366
- 0.3.0/vrel/optim.pyAdded+85
- 0.3.0/vrel/quant.pyAdded+25
- 0.3.0/vrel/stories.pyAdded+143
- 0.3.0/vrel/tokenizer.pyAdded+172
- 0.3.0/vrel/train.pyAdded+216
- 0.3.0/vrel/watch.pyAdded+141
- README.mdAdded+73
123456789101112{
"name": "Vrel",
"version": "0.1.0",
"kind": "text-generator",
"entry": "vrel.generate:load",
"weights": "vrel.pt",
"tokenizer": "tokenizer.json",
"params": 13891584,
"context": 256,
"val_loss": 3.6365,
"trained_on": "public-domain books from Project Gutenberg"
}1{"format":"vrel-bpe-1","merges":[[32,116],[104,101],[32,97],[105,110],[32,115],[32,119],[256,257],[114,101],[226,128],[32,111],[110,100],[104,97],[111,117],[101,114],[101,100],[105,116],[32,98],[32,109],[105,115],[101,110],[111,110],[259,103],[32,102],[258,266],[32,99],[256,111],[265,102],[111,114],[97,115],[32,100],[108,108],[32,104],[101,115],[32,257],[97,114],[97,110],[32,259],[32,108],[32,112],[32,73],[97,116],[32,267],[32,110],[32,32],[264,156],[111,109],[267,116],[264,157],[108,101],[272,101],[111,116],[111,119],[264,153],[32,103],[117,116],[105,100],[261,284],[105,109],[115,116],[108,121],[118,101],[32,121],[108,100],[105,99],[115,101],[32,101],[32,271],[103,104],[256,302],[256,104],[317,268],[118,269],[275,116],[265,110],[99,101],[271,104],[97,121],[287,274],[32,117],[101,116],[32,263],[105,114],[105,276],[97,100],[261,331],[258,115],[117,114],[323,116],[97,108],[261,104],[297,100],[260,116],[278,283],[114,111],[268,318],[261,101],[260,97],[298,306],[111,111],[257,114],[99,104],[84,257],[114,105],[32,77],[258,116],[258,110],[289,114],[116,269],[287,313],[273,101],[32,72],[32,300],[46,303],[97,109],[107,101],[99,116],[32,274],[97,259],[105,286],[273,121],[260,101],[97,266],[263,100],[105,102],[260,111],[288,115],[105,108],[352,311],[116,104],[99,107],[111,263],[114,97],[112,112],[260,117],[32,65],[105,343],[299,299],[260,257],[297,316],[301,101],[264,148],[44,303],[32,83],[116,257],[334,112],[32,107],[32,357],[97,286],[272,310],[258,286],[285,111],[319,104],[114,301],[10,392],[98,304],[113,117],[103,101],[285,101],[409,32],[112,101],[116,111],[117,108],[260,104],[272,121],[327,121],[290,100],[32,114],[32,66],[108,102],[259,100],[32,87],[345,407],[268,116],[117,115],[117,314],[351,263],[298,101],[263,115],[261,257],[63,303],[268,115],[325,274],[280,276],[278,408],[117,110],[101,109],[291,116],[101,286],[268,114],[288,116],[354,100],[284,116],[101,108],[268,266],[321,120],[401,110],[276,103],[290,116],[298,111],[262,121],[273,291],[296,338],[265,114],[265,310],[293,105],[329,101],[354,107],[366,101],[32,67],[32,118],[261,350],[111,115],[276,101],[267,110],[111,108],[320,424],[359,114],[258,108],[307,110],[32,84],[271,116],[108,97],[274,116],[345,111],[97,107],[262,109],[258,98],[268,323],[305,275],[269,115],[262,263],[117,109],[280,350],[108,105],[369,101],[293,101],[114,121],[257,100],[296,101],[283,116],[258,103],[334,110],[434,110],[261,283],[118,275],[311,101],[32,80],[263,296],[112,116],[258,263],[105,316],[261,302],[97,103],[280,301],[32,379],[117,263],[33,303],[32,68],[262,337],[309,111],[111,314],[104,277],[264,152],[105,103],[119,332],[32,106],[32,420],[271,121],[32,411],[32,76],[278,97],[273,386],[97,410],[260,395],[313,101],[278,101],[116,101],[271,101],[97,117],[258,109],[259,107],[292,416],[326,114],[342,110],[116,355],[266,269],[361,121],[451,307],[476,304],[293,462],[97,370],[260,112],[258,102],[261,374],[32,70],[275,330],[102,101],[32,349],[111,100],[319,101],[280,291],[101,112],[285,311],[118,270],[110,101],[284,115],[105,101],[306,355],[107,270],[268,343],[376,101],[32,71],[110,116],[281,111],[482,428],[295,116],[460,370],[293,544],[97,263],[496,373],[102,386],[108,111],[119,101],[259,101],[291,330],[111,102],[260,267],[339,101],[114,117],[89,268],[265,327],[400,276],[256,469],[109,101],[97,385],[294,349],[105,436],[297,266],[298,307],[262,110],[256,119],[256,530],[272,114],[98,101],[285,474],[111,112],[260,332],[99,99],[97,98],[403,121],[258,114],[32,313],[334,115],[265,540],[10,10],[117,356],[433,115],[32,69],[110,103],[277,115],[119,110],[319,107],[112,269],[274,104],[100,101],[105,263],[32,275],[45,45],[108,270],[418,350],[110,381],[111,320],[111,266],[118,277],[287,307],[32,74],[32,78],[97,99],[102,417],[111,316],[296,355],[280,104],[423,310],[285,332],[109,328],[97,412],[101,290],[273,430],[117,286],[285,274],[263,101],[104,274],[258,100],[329,315],[358,270],[119,421],[102,283],[305,576],[309,114],[325,536],[105,304],[32,79],[548,363],[114,291],[273,583],[105,288],[273,611],[290,121],[258,388],[358,343],[269,116],[294,111],[274,115],[72,101],[321,121],[297,115],[336,109],[280,490],[46,46],[293,452],[389,356],[272,111],[110,277],[116,302],[309,446],[432,327],[97,112],[260,109],[32,95],[296,270],[596,111],[339,121],[294,269],[321,420],[260,99],[109,291],[379,101],[337,314],[272,590],[325,565],[282,102],[272,108],[261,332],[309,503],[273,391],[268,568],[32,518],[265,318],[290,107],[322,115],[116,121],[280,108],[105,318],[358,101],[118,288],[334,541],[390,266],[97,316],[257,110],[102,116],[280,395],[371,338],[325,114],[108,288],[376,441],[32,82],[112,115],[111,286],[294,263],[274,101],[364,471],[305,103],[265,616],[301,335],[289,339],[261,328],[259,116],[294,101],[268,320],[415,371],[275,270],[73,116],[97,356],[321,500],[280,267],[294,108],[278,693],[117,100],[256,114],[99,270],[105,315],[265,342],[258,520],[434,263],[467,115],[105,291],[305,116],[293,447],[111,318],[539,270],[103,270],[309,108],[509,112],[98,269],[336,112],[670,288],[108,381],[105,270],[104,121],[521,430],[105,410],[289,263],[351,286],[294,453],[276,115],[384,277],[101,327],[117,101],[398,257],[265,98],[309,335],[110,306],[273,332],[265,112],[10,414],[291,103],[526,330],[102,102],[294,477],[119,104],[709,266],[305,99],[262,320],[336,115],[294,561],[347,374],[294,114],[338,115],[99,105],[97,378],[305,277],[352,119],[285,288],[260,415],[607,112],[296,104],[438,116],[285,276],[114,307],[110,269],[278,108],[293,335],[284,101],[283,100],[344,107],[256,443],[353,517],[99,288],[406,283],[116,270],[101,371],[119,331],[545,270],[301,328],[321,327],[534,320],[472,115],[257,115],[273,546],[298,391],[32,370],[340,428],[273,516],[278,786],[32,387],[519,110],[32,585],[336,116],[260,729],[718,483],[261,442],[263,110],[263,116],[119,284],[103,335],[582,286],[520,115],[108,277],[294,310],[66,310],[261,296],[297,114],[278,449],[553,301],[326,614],[499,100],[115,104],[273,425],[450,112],[101,119],[448,116],[438,115],[325,277],[103,103],[293,692],[273,819],[720,270],[121,268],[480,277],[116,277],[65,266],[328,315],[100,275],[97,337],[99,108],[296,363],[258,603],[309,306],[601,304],[666,373],[98,121],[307,270],[101,120],[554,121],[321,290],[289,453],[402,263],[360,116],[111,385],[388,270],[329,330],[287,734],[32,665],[569,107],[115,111],[32,75],[105,112],[263,119],[293,391],[321,266],[325,483],[352,589],[32,328],[109,270],[105,120],[341,564],[489,101],[361,563],[359,290],[99,493],[117,112],[295,110],[256,546],[402,121],[297,388],[105,323],[524,533],[515,277],[278,443],[99,121],[292,314],[289,421],[313,288],[98,310],[531,448],[109,121],[261,425],[280,403],[261,114],[115,115],[491,715],[97,118],[260,296],[261,301],[275,115],[294,433],[97,119],[273,275],[260,108],[273,283],[593,115],[87,302],[473,842],[784,330],[89,288],[99,276],[99,301],[257,263],[465,111],[109,516],[44,308],[317,335],[361,115],[733,874],[259,381],[651,115],[271,355],[268,98],[285,478],[278,856],[101,378],[112,304],[365,291],[105,122],[422,449],[283,121],[306,104],[269,121],[294,304],[325,627],[376,99],[727,291],[274,493],[375,471],[325,615],[456,121],[637,708],[259,270],[417,116],[376,275],[261,97],[552,371],[46,308],[345,656],[325,646],[273,259],[280,290],[280,111],[457,115],[256,101],[274,270],[287,111],[260,269],[260,501],[278,425],[834,517],[349,925],[389,388],[285,468],[260,342],[401,425],[380,276],[99,111],[319,116],[260,335],[260,382],[373,270],[426,101],[109,269],[97,311],[263,314],[280,444],[451,855],[287,283],[260,259],[280,342],[271,338],[297,424],[273,111],[278,290],[258,99],[287,444],[642,115],[115,117],[280,701],[347,114],[644,121],[111,370],[78,111],[77,114],[97,330],[117,266],[256,755],[359,668],[274,363],[499,107],[117,385],[280,650],[354,108],[677,121],[309,506],[477,385],[294,750],[280,469],[292,116],[432,119],[104,313],[389,263],[294,485],[110,111],[267,722],[305,902],[256,387],[347,446],[106,816],[267,114],[260,337],[310,101],[97,310],[108,112],[273,290],[534,343],[281,318],[337,108],[387,119],[112,114],[267,100],[108,377],[115,269],[285,704],[489,270],[79,104],[105,118],[293,111],[293,635],[320,108],[321,118],[107,115],[402,110],[109,288],[779,275],[336,314],[622,483],[105,98],[117,344],[275,320],[398,116],[935,678],[413,290],[117,433],[307,269],[285,379],[575,314],[105,378],[290,110],[306,116],[307,115],[259,115],[417,290],[480,275],[32,86],[120,116],[109,115],[87,443],[97,388],[97,504],[752,363],[111,306],[578,275],[102,495],[100,269],[263,339],[438,102],[450,99],[509,109],[840,355],[102,1022],[263,335],[271,115],[105,335],[390,110],[100,332],[271,270],[298,296],[944,555],[265,603],[289,290],[432,290],[787,821],[98,108],[659,412],[280,875],[304,557],[467,270],[258,337],[284,104],[479,304],[499,318],[112,453],[278,723],[328,304],[280,257],[309,713],[108,391],[287,395],[287,487],[347,101],[440,103],[104,425],[275,269],[366,274],[929,291],[110,307],[272,349],[309,1059],[280,304],[314,377],[313,112],[263,369],[1007,320],[256,539],[847,100],[268,100],[292,620],[389,98],[426,302],[362,471],[545,277],[280,283],[577,385],[256,269],[964,284],[296,277],[284,363],[256,810],[111,121],[272,429],[531,119],[667,283],[280,114],[422,636],[271,356],[107,277],[497,116],[327,115],[330,504],[369,112],[667,732],[100,868],[273,871],[319,344],[321,109],[648,100],[297,629],[111,541],[278,621],[291,121],[293,534],[473,945],[542,771],[612,270],[101,121],[103,115],[105,344],[256,263],[290,115],[760,1066],[98,98],[293,332],[298,283],[97,382],[289,1055],[309,468],[357,263],[371,283],[295,102],[294,342],[309,117],[194,160],[494,315],[672,441],[389,1184],[390,108],[752,1104],[826,557],[97,304],[98,879],[115,112],[284,276],[328,115],[422,440],[103,114],[258,119],[292,100],[298,490],[785,407],[285,953],[328,338],[292,363],[336,102],[260,119],[790,270],[32,40],[32,358],[105,269],[473,452],[344,564],[532,266],[102,363],[432,1097],[83,257],[97,122],[84,302],[291,107],[305,1144],[309,387],[309,1136],[307,277],[524,445],[604,315],[631,111],[1101,373],[309,105],[321,738],[1047,316],[101,795],[268,108],[272,270],[406,288],[598,563],[648,118],[103,269],[117,378],[276,116],[470,1075],[336,339],[373,116],[273,276],[630,772],[1179,382],[263,568],[272,1037],[280,574],[281,951],[290,412],[293,381],[278,636],[440,116],[341,115],[112,108],[321,108],[535,452],[639,115],[267,316],[567,554],[107,275],[285,335],[851,115],[345,533],[475,302],[492,277],[101,118],[272,263],[578,378],[683,403],[1159,270],[101,99],[256,374],[256,584],[272,962],[363,115],[260,449],[268,384],[389,110],[413,339],[366,1270],[531,335],[32,501],[291,101],[73,110],[278,369],[846,269],[1071,710],[311,269],[335,104],[336,605],[269,110],[475,301],[532,378],[115,501],[475,104],[532,1006],[382,288],[465,274],[475,647],[98,114],[115,257],[119,283],[256,1095],[259,117],[97,371],[101,107],[278,444],[345,301],[560,121],[87,101],[278,114],[347,377],[598,565],[987,415],[260,107],[278,386],[291,99],[293,687],[330,105],[429,270],[271,117],[775,1064],[261,290],[278,644],[296,356],[336,103],[111,304],[273,563],[357,121],[100,111],[116,275],[1232,116],[413,99],[366,307],[489,370],[426,714],[99,592],[111,118],[688,1046],[272,445],[280,577],[450,116],[948,1299],[287,342],[399,121],[1010,330],[292,99],[296,269],[347,453],[799,480],[922,307],[109,275],[260,328],[371,270],[390,116],[84,647],[261,619],[349,301],[121,277],[281,1111],[296,115],[330,270],[390,115],[923,270],[285,349],[296,288],[833,755],[1044,276],[32,85],[280,808],[487,112],[285,621],[399,263],[256,528],[261,1190],[263,687],[336,99],[336,344],[1021,452],[260,495],[278,403],[347,1126],[111,98],[382,270],[509,277],[633,493],[102,108],[257,339],[278,1103],[342,356],[357,110],[396,303],[450,735],[317,1018],[491,447],[610,610],[422,291],[513,283],[283,115],[287,911],[347,584],[741,332],[110,391],[426,104],[931,328],[119,269],[293,478],[337,100],[468,121],[292,118],[314,269],[556,777],[648,109],[102,319],[271,277],[602,115],[531,290],[63,308],[69,82],[119,302],[398,111],[914,307],[260,1030],[311,288],[607,508],[99,381],[273,339],[294,373],[418,495],[632,111],[711,1152],[33,308],[309,263],[337,99],[292,1327],[309,1145],[413,557],[260,1128],[268,110],[476,277],[802,1335],[280,503],[87,764],[311,270],[1027,378],[1372,320],[119,943],[278,342],[285,114],[285,358],[547,337],[578,263],[739,277],[32,89],[310,104],[592,315],[256,358],[260,1262],[344,115],[740,114],[258,371],[635,378],[413,801],[562,318],[109,276],[342,277],[1350,559],[108,462],[261,810],[526,371],[98,270],[422,117],[341,107],[376,97],[482,115],[1216,759],[1313,97],[272,342],[32,288],[32,374],[112,349],[260,578],[260,831],[105,551],[273,274],[294,97],[1254,338],[77,121],[109,98],[256,918],[293,1280],[464,104],[473,890],[1116,560],[1286,320],[1304,101],[269,277],[275,101],[287,276],[524,1115],[1020,492],[612,338],[657,110],[995,1061],[310,288],[423,101],[456,805],[689,771],[829,115],[44,396],[102,408],[273,311],[283,804],[304,120],[305,1054],[316,108],[382,523],[441,504],[988,118],[1141,291],[265,388],[282,1362],[284,107],[336,1224],[508,110],[724,116],[1151,290],[99,358],[100,117],[117,320],[272,879],[304,121],[261,446],[670,101],[283,110],[421,115],[479,320],[491,713],[1217,315],[304,116],[654,449],[674,674],[268,410],[366,275],[287,754],[473,468],[293,307],[966,628],[114,283],[119,350],[291,115],[294,470],[319,1094],[328,121],[398,99],[398,337],[78,306],[117,388],[256,268],[274,102],[359,121],[359,663],[384,274],[869,115],[1087,552],[1172,950],[321,284],[550,283],[645,99],[916,442],[32,308],[267,266],[334,320],[432,270],[256,275],[273,478],[290,277],[292,115],[311,328],[317,288],[356,277],[72,307],[429,104],[480,288],[640,115],[1038,766],[97,500],[103,111],[117,343],[117,541],[117,783],[413,118],[460,316],[547,1023],[664,642],[1218,555],[102,381],[114,116],[473,1407],[664,1261],[948,1437],[87,714],[105,328],[119,374],[293,516],[296,116],[347,557],[65,115],[273,335],[274,277],[287,1476],[345,121],[390,286],[477,313],[73,102],[99,823],[311,551],[348,103],[379,417],[384,483],[609,115],[993,627],[104,307],[108,319],[260,391],[340,259],[558,110],[833,539],[99,267],[273,1169],[275,103],[305,108],[322,471],[374,270],[436,377],[837,330],[429,493],[553,339],[613,109],[613,614],[72,65],[117,605],[261,692],[272,290],[294,408],[314,114],[562,119],[697,446],[83,111],[84,1450],[280,628],[280,754],[297,116],[105,429],[260,110],[261,708],[272,503],[280,1465],[284,338],[336,100],[606,109],[674,46],[857,1319],[910,121],[110,121],[273,342],[1016,992],[272,288],[294,1086],[373,115],[387,371],[524,617],[291,813],[358,410],[451,474],[934,307],[277,315],[321,952],[1557,706],[100,274],[105,97],[285,1060],[293,339],[384,467],[399,109],[562,102],[854,108],[98,111],[109,259],[369,288],[464,1051],[664,349],[826,504],[972,837],[283,492],[111,103],[114,277],[256,650],[289,318],[292,411],[32,337],[99,350],[99,395],[261,1242],[271,661],[389,783],[272,462],[347,111],[365,263],[513,111],[1057,269],[114,332],[272,117],[274,276],[278,259],[280,310],[297,337],[442,115],[606,116],[111,732],[112,263],[327,344],[475,111],[608,270],[1119,511],[268,387],[272,271],[295,115],[652,109],[959,270],[1001,551],[100,304],[406,277],[757,339],[80,1681],[98,377],[289,927],[293,377],[347,332],[1672,1766],[32,310],[103,277],[284,270],[287,429],[481,1318],[525,117],[807,363],[836,270],[1193,323],[688,977],[1472,270],[260,277],[491,1090],[117,103],[347,1113],[348,116],[482,635],[632,307],[1258,500],[78,307],[99,417],[104,734],[266,270],[388,277],[406,1210],[582,100],[1316,746],[1352,620],[67,1771],[261,276],[273,668],[278,506],[448,115],[1135,877],[273,864],[280,682],[306,338],[325,1666],[872,701],[920,277],[1298,480],[115,99],[421,275],[426,443],[981,1536],[1127,315],[99,291],[104,110],[111,327],[112,290],[280,344],[335,115],[399,337],[467,1012],[779,736],[65,116],[87,104],[108,619],[109,386],[259,277],[293,932],[387,99],[727,259],[121,589],[121,628],[272,339],[290,492],[336,415],[342,344],[426,374],[433,104],[506,315],[622,103],[285,781],[376,1753],[387,311],[441,112],[562,330],[769,1584],[834,918],[966,838],[1017,115],[306,101],[434,540],[438,99],[582,114],[628,276],[880,384],[981,1053],[101,339],[267,109],[286,270],[487,98],[491,97],[526,337],[102,977],[273,429],[379,319],[112,270],[348,109],[476,270],[553,320],[584,504],[750,766],[258,410],[259,371],[263,109],[336,687],[401,277],[406,103],[436,315],[606,449],[787,490],[100,100],[261,403],[606,358],[68,111],[268,378],[294,447],[384,115],[413,1139],[508,269],[508,288],[509,1105],[757,561],[1252,691],[111,337],[260,900],[278,519],[280,470],[363,110],[683,656],[1087,1445],[98,271],[110,270],[115,395],[259,663],[280,97],[365,335],[366,269],[724,118],[740,337],[105,290],[319,564],[345,274],[349,111],[438,118],[464,1257],[1556,291],[99,770],[105,369],[259,457],[263,108],[272,1091],[358,641],[418,307],[278,665],[305,1836],[103,493],[260,1081],[273,1440],[319,288],[675,269],[899,105],[928,1591],[65,1629],[380,715],[525,1858],[657,560],[39,115],[256,864],[276,121],[335,121],[382,277],[392,392],[538,471],[677,296],[758,291],[1160,1050],[115,267],[115,735],[116,530],[273,1308],[281,616],[285,893],[294,290],[339,270],[379,102],[388,269],[272,519],[272,665],[275,277],[276,288],[285,387],[285,1154],[294,296],[309,1814],[390,1545],[598,277],[744,1574],[891,277],[1596,1276],[119,714],[441,328],[898,956],[1937,1920],[260,411],[278,579],[285,1107],[636,579],[347,494],[356,1034],[1775,1767],[65,104],[260,121],[280,992],[348,651],[361,120],[440,101],[717,115],[789,735],[929,275],[958,115],[1157,315],[112,627],[119,443],[259,330],[690,290],[1121,1690],[1193,1930],[1200,288],[259,288],[273,635],[278,447],[524,290],[548,1847],[1429,306],[1435,533],[95,44],[101,101],[102,447],[108,269],[266,277],[314,446],[336,108],[361,103],[372,1063],[413,344],[423,114],[477,330],[602,277],[667,385],[1180,457],[1464,275],[1707,315],[261,267],[294,358],[465,374],[652,100],[655,277],[941,116],[99,469],[100,121],[280,101],[449,270],[521,111],[1329,271],[98,666],[109,277],[112,104],[291,915],[982,650],[1575,492],[1833,363],[260,930],[293,1005],[1009,320],[1025,115],[1343,277],[1353,559],[1510,99],[115,109],[278,577],[387,391],[508,373],[1256,1819],[1645,270],[265,1620],[280,492],[336,998],[442,315],[924,452],[1001,328],[1164,805],[1432,385],[32,270],[115,1005],[259,805],[280,1057],[285,612],[294,117],[328,270],[591,98],[606,1098],[1342,1269],[1739,885],[273,269],[292,102],[478,270],[720,115],[1845,269],[105,470],[114,478],[299,32],[317,642],[426,764],[499,384],[1188,270],[1473,511],[1917,412],[70,283],[79,110],[102,97],[115,288],[119,111],[310,338],[379,116],[429,115],[460,722],[523,97],[645,1100],[1898,306],[99,1165],[118,111],[121,270],[122,101],[259,338],[321,1867],[458,1106],[550,781],[637,1421],[789,470],[1167,511],[32,316],[109,112],[117,98],[256,659],[566,277],[741,373],[954,580],[508,270],[744,1486],[785,111],[1000,116],[103,108],[119,617],[294,644],[365,442],[389,109],[418,310],[464,470],[465,1678],[1156,277],[1336,315],[110,97],[285,1497],[305,290],[307,485],[347,358],[349,118],[521,743],[599,275],[911,98],[1251,316],[112,291],[278,1034],[351,1337],[365,109],[1014,559],[1688,104],[97,603],[260,313],[280,377],[287,1143],[313,328],[325,617],[491,339],[1039,330],[1110,276],[84,104],[108,544],[256,468],[280,263],[373,277],[526,118],[607,1935],[1546,1650],[112,271],[278,646],[361,313],[399,110],[406,1198],[444,115],[624,412],[659,103],[677,120],[787,395],[859,445],[287,601],[291,745],[294,999],[306,823],[321,411],[359,283],[604,428],[776,865],[934,391],[1016,411],[1038,381],[1235,304],[115,415],[260,339],[260,1471],[267,388],[321,304],[337,116],[1170,277],[1482,271],[99,304],[103,110],[105,107],[107,110],[293,270],[306,115],[348,840],[560,327],[672,704],[740,2045],[959,101],[1671,1829],[1768,121],[32,88],[101,103],[109,271],[116,276],[259,416],[280,723],[293,494],[438,2024],[450,369],[599,576],[657,104],[669,263],[792,332],[1456,579],[1517,618],[273,579],[309,893],[319,605],[321,296],[413,112],[423,1032],[432,1457],[460,629],[596,1585],[898,621],[1039,412],[1239,327],[99,257],[108,452],[258,314],[278,900],[294,275],[300,518],[359,339],[374,97],[426,331],[487,314],[515,318],[591,112],[1142,369],[1226,678],[1513,335],[32,81],[65,110],[105,710],[260,1153],[260,1983],[269,109],[280,804],[285,763],[285,2069],[337,109],[351,480],[398,532],[775,489],[108,259],[111,859],[112,111],[116,469],[118,344],[274,416],[487,759],[620,378],[751,97],[775,1050],[852,350],[1243,270],[1467,344],[1777,915],[1839,685],[73,73],[101,270],[296,506],[336,1417],[380,108],[418,462],[513,114],[552,378],[672,1002],[838,905],[846,356],[884,270],[1857,112],[97,102],[121,444],[273,1233],[284,320],[296,511],[319,270],[411,445],[432,952],[502,283],[599,378],[608,1080],[798,112],[906,276],[910,736],[1109,2058],[73,115],[118,274],[295,266],[311,867],[344,384],[359,2101],[382,115],[443,97],[450,1181],[800,1875],[837,356],[852,892],[854,1533],[1079,315],[1121,342],[1348,277],[97,1244],[100,474],[114,369],[278,1842],[283,109],[285,445],[376,424],[416,1111],[438,314],[622,99],[729,517],[779,2108],[98,115],[101,420],[287,306],[290,356],[314,1595],[330,315],[347,2055],[443,307],[449,115],[466,110],[488,110],[794,344],[976,271],[106,430],[195,169],[284,493],[354,320],[450,618],[460,101],[465,2083],[591,1393],[632,306],[800,495],[1149,1291],[1628,283],[1781,315],[1900,511],[97,104],[104,516],[112,561],[256,1296],[259,363],[289,1618],[298,468],[415,266],[418,428],[543,115],[697,773],[883,1233],[99,328],[99,342],[103,121],[103,259],[108,115],[256,1018],[278,277],[286,277],[290,109],[347,743],[464,1981],[496,111],[552,717],[920,615],[1119,1840],[2023,335],[99,277],[103,117],[105,327],[114,339],[119,725],[285,562],[309,1247],[336,1498],[363,277],[521,1171],[1042,471],[102,449],[260,1726],[285,1742],[304,119],[325,429],[336,118],[347,263],[502,349],[547,111],[548,102],[574,114],[758,1192],[830,986],[931,551],[1589,551],[32,49],[103,503],[122,122],[260,271],[398,1835],[426,446],[574,568],[581,102],[1373,387],[1535,725],[1626,580],[1969,377],[106,1171],[121,269],[256,492],[269,118],[293,579],[297,614],[429,338],[460,559],[525,809],[577,301],[1586,2091],[102,1026],[271,457],[274,517],[280,604],[287,374],[348,384],[389,2179],[467,277],[547,306],[659,107],[872,301],[1354,109],[1479,540],[2008,764],[97,415],[104,446],[273,1328],[283,112],[285,310],[430,301],[476,275],[794,605],[1380,270],[98,263],[98,335],[107,1148],[112,277],[116,114],[278,296],[287,311],[320,116],[321,783],[321,1893],[486,576],[521,444],[536,277],[645,112],[785,656],[1663,307],[84,111],[103,288],[109,391],[263,114],[281,112],[292,1418],[294,495],[320,411],[1040,443],[1149,370],[1166,1705],[1424,270],[1543,1763],[1598,121],[1689,2249],[281,114],[297,314],[459,1325],[470,1053],[591,618],[617,2127],[658,951],[1082,1113],[1523,2084],[1699,501],[100,311],[107,121],[110,485],[278,440],[290,564],[356,111],[390,1244],[1123,315],[171,118],[195,2515],[280,447],[285,574],[293,1662],[321,391],[344,1131],[384,565],[418,877],[450,2135],[485,276],[525,687],[695,115],[1131,338],[1333,384],[2027,304],[2261,100],[2521,2516],[103,756],[105,275],[269,528],[278,349],[337,706],[432,385],[432,2144],[463,263],[499,320],[567,263],[603,381],[1011,592],[1134,428],[1638,115],[2299,2545],[101,344],[112,2021],[115,332],[275,381],[276,448],[280,1257],[311,412],[320,101],[330,506],[336,902],[347,961],[366,290],[465,344],[477,119],[707,1158],[883,1549],[964,808],[1137,269],[1432,859],[1812,2012],[2237,315],[10,2085],[33,396],[99,875],[107,425],[256,1242],[272,1439],[280,328],[280,387],[344,523],[359,291],[495,440],[513,101],[562,342],[880,315],[1273,1891],[2242,276],[103,290],[294,1849],[296,257],[325,893],[382,116],[502,101],[502,2103],[809,1908],[1403,717],[97,106],[101,717],[109,110],[285,275],[294,104],[304,384],[418,892],[502,335],[502,2502],[550,2269],[614,2599],[697,381],[707,2183],[872,809],[1213,381],[2167,1215],[2411,614],[41,44],[72,69],[77,290],[87,331],[98,448],[100,288],[101,1073],[103,387],[109,1544],[111,101],[114,276],[122,275],[284,511],[286,105],[294,1702],[311,315],[612,277],[682,1358],[707,1129],[744,430],[904,2247],[1108,381],[1482,1114],[1703,315],[2604,2460],[72,274],[269,1046],[278,2042],[294,344],[294,1221],[379,763],[413,489],[440,107],[465,290],[741,291],[751,115],[784,745],[910,950],[1045,276],[1346,121],[1375,650],[1560,745],[1834,678],[101,500],[102,269],[109,583],[115,276],[260,276],[273,554],[273,1615],[278,379],[280,268],[285,1068],[294,332],[349,112],[370,121],[467,523],[631,1721],[683,111],[721,111],[798,1559],[802,114],[857,1368],[976,1446],[1065,626],[1302,382],[1392,276],[1403,371],[1828,111],[2412,2363],[2628,276],[104,754],[109,97],[109,377],[260,304],[280,821],[293,604],[401,668],[464,114],[465,291],[487,270],[491,291],[550,2321],[572,315],[690,1529],[711,2015],[769,121],[770,2581],[983,296],[1035,115],[1949,338],[97,616],[108,447],[258,412],[261,501],[272,1529],[278,391],[325,1439],[342,121],[359,453],[421,270],[478,115],[509,288],[552,1667],[631,1314],[654,307],[1079,1548],[1212,1996],[1535,986],[1822,109],[33,34],[71,446],[79,560],[272,1249],[280,1182],[293,379],[310,511],[336,738],[352,118],[436,288],[464,283],[697,425],[781,117],[985,97],[1091,275],[1149,339],[1234,1874],[1499,277],[1714,661],[2054,283],[2074,1255],[2260,973],[99,804],[101,284],[108,332],[109,668],[112,433],[257,453],[260,489],[271,685],[273,310],[273,561],[352,552],[363,1117],[458,100],[553,385],[622,2432],[625,269],[696,319],[758,304],[878,735],[1072,382],[1212,1019],[1797,307],[1856,1322],[2477,1340],[65,286],[114,319],[261,968],[276,315],[278,263],[278,477],[278,1495],[285,117],[334,266],[415,2464],[426,2677],[489,122],[619,640],[760,315],[764,115],[792,306],[799,864],[2153,957],[97,327],[110,2202],[111,415],[263,103],[263,589],[269,2380],[273,270],[330,286],[356,1717],[380,304],[491,1198],[496,646],[683,1415],[724,112],[916,1861],[1110,377],[2786,1369],[32,445],[68,276],[83,116],[99,490],[344,270],[347,468],[352,370],[398,395],[413,102],[417,706],[548,2390],[733,1026],[743,868],[757,580],[790,338],[1396,885],[2474,495],[97,717],[110,283],[112,337],[119,257],[260,344],[320,441],[389,2543],[415,378],[441,111],[525,121],[817,428],[1256,101],[1258,629],[1590,356],[1784,270],[2061,2201],[2243,270],[2258,315],[2519,384],[65,1244],[107,269],[111,378],[260,1148],[293,1379],[294,1825],[422,311],[487,328],[539,277],[560,119],[574,116],[625,485],[652,899],[976,1118],[1438,275],[1713,277],[1780,277],[1904,974],[86,963],[99,114],[111,107],[114,483],[117,288],[273,704],[278,315],[305,286],[367,518],[376,296],[418,306],[438,560],[632,2681],[758,108],[880,115],[981,1030],[985,1320],[1187,98],[1438,736],[1999,2344],[2029,641],[2149,961],[2246,490],[2610,384],[105,433],[106,111],[114,311],[117,99],[261,274],[272,449],[285,313],[293,1390],[309,349],[365,108],[411,101],[464,276],[502,114],[525,335],[547,1728],[792,259],[1072,2314],[1135,307],[1167,442],[1187,112],[1412,275],[1509,314],[1772,363],[2154,304],[2325,378],[77,668],[101,266],[105,283],[110,296],[110,445],[115,2337],[116,1306],[117,412],[259,121],[296,319],[309,440],[382,327],[422,407],[473,1651],[495,270],[513,276],[588,107],[1623,382],[1887,559],[2579,523],[32,34],[66,121],[98,590],[99,290],[99,1393],[101,356],[107,288],[109,430],[112,335],[275,580],[277,277],[293,1086],[293,1158],[298,290],[347,601],[352,316],[389,1223],[440,356],[491,103],[501,378],[672,2511],[709,102],[807,1306],[985,541],[1115,121],[1125,319],[1323,921],[1757,412],[2017,492],[2911,276],[67,395],[95,46],[298,2274],[347,1154],[418,386],[470,2801],[526,331],[557,277],[652,384],[773,275],[982,1926],[1105,440],[1150,115],[1554,2960],[1740,315],[1989,592],[103,446],[105,722],[109,284],[272,387],[273,1808],[280,1356],[294,523],[389,618],[426,445],[508,773],[1069,559],[1166,1580],[1925,301],[2203,474],[112,714],[115,121],[115,270],[116,304],[256,441],[260,617],[261,271],[281,651],[289,115],[325,349],[347,617],[347,795],[353,101],[380,318],[413,103],[423,121],[552,448],[657,102],[658,2649],[794,1944],[826,121],[878,116],[1014,276],[1041,115],[1378,263],[1697,109],[1865,629],[1965,616],[100,277],[100,478],[105,415],[267,115],[278,2727],[280,1091],[298,342],[309,403],[317,2346],[320,99],[360,1243],[396,300],[422,1641],[547,533],[613,420],[672,373],[777,517],[891,1848],[944,1933],[1039,756],[1530,444],[1576,277],[1723,738],[2268,283],[67,276],[104,283],[256,646],[260,1352],[265,1885],[274,107],[274,109],[276,270],[278,2528],[305,296],[349,320],[358,288],[375,1442],[384,536],[423,2532],[438,870],[450,478],[475,2419],[487,101],[545,115],[618,283],[633,304],[714,115],[1009,2095],[1187,504],[1292,2742],[1506,2500],[1590,905],[1722,719],[1792,1914],[2128,270],[101,288],[116,2096],[260,735],[271,793],[278,1665],[280,584],[293,271],[294,516],[297,1905],[359,1269],[376,266],[390,114],[480,270],[543,2175],[574,2743],[904,1685],[922,1092],[1364,1475],[1598,746],[1611,2754],[1841,1922],[2028,118],[2234,663],[2304,1715],[2461,121],[99,444],[105,2667],[116,115],[272,403],[273,701],[278,1272],[296,1324],[347,337],[389,2929],[405,877],[417,436],[429,517],[454,320],[467,533],[513,2276],[542,468],[682,270],[982,492],[1121,906],[1406,634],[1444,337],[1921,1368],[2255,2964],[39,116],[103,494],[109,283],[111,559],[258,259],[261,377],[278,2264],[293,2733],[294,2781],[295,2635],[375,314],[401,374],[403,270],[442,641],[532,275],[604,2318],[632,283],[654,561],[794,112],[830,112],[1252,1383],[1473,1085],[2410,470],[79,102],[84,301],[102,1495],[256,403],[271,99],[287,501],[294,590],[341,1128],[353,555],[401,1665],[423,275],[432,2415],[464,2676],[599,277],[723,121],[744,953],[751,560],[798,621],[1216,2305],[1316,382],[1400,2954],[1619,277],[1738,115],[1868,319],[2113,559],[2125,624],[2814,315],[32,327],[63,396],[76,335],[87,943],[100,276],[101,283],[105,370],[116,319],[119,328],[256,503],[272,275],[275,813],[287,2730],[288,1455],[293,313],[297,286],[314,468],[336,316],[348,1004],[353,2301],[411,274],[438,330],[440,678],[524,101],[547,328],[607,109],[682,485],[683,1023],[794,551],[1206,115],[1546,121],[1904,2811],[1986,2116],[2425,691],[99,344],[114,457],[256,447],[271,663],[309,2441],[413,1134],[422,1668],[613,100],[633,121],[699,269],[790,641],[846,1612],[854,612],[1254,793],[1500,277],[1531,315],[1583,555],[1663,452],[2072,2950],[2487,117],[2760,532],[2761,270],[65,108],[121,110],[280,1493],[291,1696],[292,870],[294,801],[296,283],[298,555],[352,382],[390,1715],[413,2684],[418,601],[441,759],[465,328],[697,307],[792,1745],[846,905],[904,1547],[1009,1580],[1167,270],[1228,574],[1347,314],[1928,736],[2006,363],[32,831],[32,940],[98,315],[99,725],[102,786],[273,337],[278,446],[294,440],[314,557],[372,110],[374,101],[398,104],[449,269],[550,408],[730,115],[733,3066],[799,270],[880,2909],[1016,1181],[1297,259],[1671,1063],[1676,725],[1936,763],[2141,1177],[2792,328],[3143,714],[97,783],[99,821],[104,487],[111,288],[114,449],[257,318],[273,495],[293,884],[444,277],[465,999],[473,2334],[526,813],[567,1328],[784,813],[924,2463],[942,1105],[1014,283],[1175,530],[1213,421],[1550,555],[1670,3057],[1786,115],[1787,1990],[2794,2596],[109,425],[109,611],[115,296],[117,371],[119,446],[258,1134],[267,112],[271,528],[278,271],[278,1348],[278,2408],[293,627],[316,263],[445,121],[454,1885],[480,269],[502,2547],[690,1154],[729,918],[790,277],[792,501],[883,590],[936,395],[999,338],[1458,490],[1722,1563],[1731,1089],[1980,634],[2118,115],[2490,519],[2706,801],[2941,319],[97,318],[99,269],[102,304],[107,1093],[111,283],[119,425],[260,1544],[273,382],[309,284],[325,121],[326,384],[413,1655],[502,290],[521,1402],[525,338],[847,109],[1007,116],[1014,629],[1056,650],[1070,315],[1251,330],[1373,2789],[1396,316],[1480,536],[1481,316],[1719,296],[1731,337],[2052,2457],[2132,2552],[2182,511],[2267,756],[2384,485],[2662,957],[3061,121],[65,263],[73,78],[101,927],[103,291],[114,442],[256,1089],[259,533],[293,871],[294,869],[306,706],[316,577],[336,411],[342,100],[351,636],[356,1421],[538,115],[654,1253],[800,349],[878,112],[916,1877],[1060,2030],[1203,277],[1333,107],[1488,1402],[1499,270],[1510,2776],[1550,442],[1552,2924],[1552,3106],[1741,1210],[2989,618],[32,269],[100,448],[103,301],[104,259],[112,470],[119,114],[274,338],[283,661],[289,286],[309,275],[351,108],[369,270],[398,109],[426,943],[426,1177],[438,2489],[448,316],[465,373],[507,772],[515,100],[525,101],[550,900],[654,377],[983,327],[998,327],[1020,2934],[1135,1253],[1272,580],[1433,270],[1737,269],[2180,270],[2542,121],[2824,270],[2839,2793],[66,101],[97,520],[103,2848],[280,296],[284,288],[285,492],[289,391],[314,101],[325,268],[359,386],[369,328],[376,500],[418,884],[422,373],[423,1838],[547,2176],[582,415],[596,555],[637,111],[637,1717],[698,115],[743,270],[789,974],[857,2944],[988,592],[1205,384],[1357,421],[1408,723],[1649,506],[1719,421],[1732,276],[1746,968],[2195,121],[2678,315],[3395,963],[69,420],[102,693],[115,277],[115,611],[258,717],[269,316],[272,328],[274,288],[285,1196],[294,283],[297,532],[300,95],[309,490],[313,259],[320,275],[333,116],[359,276],[401,3271],[402,320],[436,270],[467,511],[526,974],[550,378],[631,417],[719,104],[798,330],[924,1854],[1048,316],[1292,816],[1464,121],[1916,618],[2505,2973],[3258,876],[32,311],[102,633],[109,332],[116,373],[119,809],[259,314],[259,745],[261,1090],[336,385],[341,501],[347,884],[359,2214],[399,320],[406,2622],[430,270],[454,410],[460,710],[487,410],[515,288],[582,589],[598,373],[604,1320],[664,263],[859,3371],[1044,117],[1200,1520],[1844,641],[2166,444],[2171,344],[2413,1291],[2557,102],[32,1693],[98,759],[99,808],[114,580],[259,99],[261,628],[268,274],[278,387],[290,746],[292,1045],[309,494],[352,266],[384,2859],[398,101],[405,307],[453,355],[464,291],[489,103],[499,564],[513,617],[584,100],[613,2778],[622,441],[683,1945],[799,2930],[854,1196],[941,99],[954,342],[1011,3094],[1109,1118],[1361,283],[1759,3131],[2428,2592],[2737,270],[2899,577],[3049,592],[3126,963],[46,396],[105,885],[109,819],[116,528],[278,628],[285,369],[290,915],[291,563],[292,1760],[294,382],[317,1567],[339,118],[347,457],[349,339],[376,1821],[385,270],[432,103],[440,815],[465,447],[497,102],[497,2744],[535,1247],[553,581],[659,1267],[931,867],[1110,440],[1564,115],[1586,3082],[1601,315],[1607,546],[1637,304],[1844,2122],[1865,710],[2312,766],[2496,1704],[3040,457],[3158,1914],[32,42],[72,713],[97,271],[97,629],[98,276],[98,554],[103,373],[108,116],[116,263],[119,442],[256,452],[260,477],[301,115],[309,290],[319,115],[319,1634],[347,290],[380,3004],[384,615],[389,1952],[454,725],[454,1222],[464,3382],[525,1726],[599,3273],[666,270],[942,112],[996,626],[1375,116],[1516,2535],[1751,270],[1892,270],[2313,751],[2565,634],[2590,3518],[44,34],[99,1493],[115,342],[256,121],[273,381],[278,539],[285,430],[293,306],[293,750],[309,304],[336,2881],[342,605],[347,349],[390,921],[448,381],[475,2612],[526,382],[536,304],[543,277],[547,1107],[567,3171],[591,1628],[689,1222],[727,440],[800,296],[806,2139],[1072,1225],[1285,332],[1400,110],[1429,751],[1466,277],[1485,335],[1517,1351],[1550,1749],[1600,1493],[1649,2735],[1783,304],[2332,349],[2437,277],[68,311],[103,612],[111,603],[260,1455],[263,371],[273,1320],[280,1068],[292,1325],[293,1032],[294,562],[305,447],[311,277],[312,110],[359,332],[374,277],[448,275],[458,2275],[473,506],[504,338],[513,3569],[515,1125],[525,3265],[631,313],[632,2827],[633,719],[667,1745],[718,430],[721,2968],[904,356],[993,1129],[1076,277],[1203,270],[1266,3129],[1326,283],[1412,277],[1470,745],[1699,1455],[1718,291],[2729,641],[3118,678],[3219,551],[3310,270],[108,283],[109,759],[115,107],[263,270],[268,112],[278,344],[283,483],[287,519],[294,2273],[294,2347],[304,266],[307,1567],[321,447],[335,532],[348,330],[376,685],[376,1761],[423,3494],[469,107],[513,311],[550,3225],[596,3409],[613,500],[613,3036],[844,865],[895,3364],[958,277],[990,277],[1019,388],[1031,277],[1051,100],[1096,291],[1266,328],[1284,478],[1307,115],[1682,1012],[1901,444],[1949,793],[2298,270],[2607,277],[3073,448],[97,342],[98,290],[99,355],[99,503],[105,528],[109,290],[262,101],[265,358],[273,306],[294,3192],[298,579],[325,259],[334,114],[548,977],[566,107],[718,474],[787,301],[789,112],[806,296],[872,1610],[898,269],[904,3155],[1009,1705],[1264,110],[1744,708],[1758,363],[2266,2985],[2361,442],[2615,562],[2644,592],[2661,706],[2774,370],[78,1054],[79,78],[102,2290],[105,500],[258,1283],[258,2105],[259,97],[260,1249],[261,579],[261,2292],[267,424],[280,462],[280,516],[286,121],[289,2315],[294,335],[296,764],[309,445],[332,115],[355,1165],[374,121],[377,441],[379,121],[382,429],[421,276],[422,277],[429,277],[465,2980],[513,117],[547,3726],[591,316],[688,1498],[696,269],[762,315],[1019,378],[1047,559],[1056,1926],[1197,288],[1234,118],[1347,1419],[1537,2785],[1723,1417],[2190,338],[2414,869],[3764,2381],[3789,3812],[65,82],[69,83],[99,701],[103,506],[116,354],[118,105],[278,3541],[282,2290],[287,2912],[296,469],[313,1225],[329,288],[339,100],[347,3586],[354,304],[357,320],[366,1838],[369,277],[384,646],[426,382],[497,762],[542,1222],[568,276],[654,296],[654,474],[723,307],[789,2691],[870,1959],[883,328],[1001,327],[1011,1276],[1072,1648],[1122,277],[1197,269],[1228,634],[1284,511],[1676,986],[1694,528],[2037,973],[2067,412],[2147,619],[2307,869],[2374,270],[2594,3309],[2690,968],[2798,795],[2938,804],[2999,646],[3403,1734],[3810,3868],[33,95],[67,104],[100,379],[111,104],[263,112],[272,554],[278,1240],[280,2462],[286,275],[290,320],[294,1005],[347,1595],[348,745],[361,110],[385,115],[403,1197],[422,430],[422,483],[422,725],[429,288],[451,884],[451,3068],[508,103],[591,118],[814,115],[1064,118],[1108,1648],[1302,821],[1375,492],[1435,111],[1560,330],[1697,1106],[1850,315],[1910,277],[1912,328],[2072,2422],[2387,121],[2431,3269],[2574,115],[2726,815],[3679,554],[87,374],[99,470],[102,403],[102,1280],[256,349],[257,421],[260,624],[261,386],[272,307],[272,377],[272,574],[272,877],[272,1107],[280,436],[285,580],[293,554],[293,1742],[294,821],[319,685],[359,429],[423,1414],[426,284],[445,270],[450,3270],[453,270],[464,395],[465,470],[475,342],[497,2200],[554,283],[567,2367],[604,719],[677,421],[744,373],[857,3194],[910,275],[924,1446],[1185,115],[1236,2098],[1369,1177],[1470,363],[1480,2643],[1589,121],[1750,319],[1807,528],[1832,2433],[2035,1774],[2356,1515],[2771,411],[2994,296],[3123,641],[3202,101],[89,444],[102,271],[105,554],[108,692],[117,436],[269,559],[269,2963],[272,358],[273,1356],[278,494],[278,3486],[280,523],[309,2367],[313,115],[314,584],[325,3722],[341,3823],[348,899],[373,815],[442,319],[547,1026],[552,1276],[591,559],[607,618],[770,1081],[801,3862],[804,115],[924,533],[941,102],[1040,349],[1166,358],[1166,1098],[1220,277],[1357,838],[1440,3376],[1751,640],[1783,1094],[1916,2826],[2821,271],[3019,320],[3093,320],[99,447],[100,301],[118,291],[256,642],[259,110],[260,911],[263,275],[269,710],[271,506],[272,1566],[273,656],[278,619],[285,773],[287,732],[292,106],[298,2435],[310,270],[314,374],[320,1520],[344,842],[351,2617],[366,403],[382,105],[400,2343],[497,528],[525,462],[526,1415],[664,2426],[849,115],[954,442],[1004,319],[1152,277],[1183,270],[1379,1199],[1514,115],[1588,517],[1670,2683],[1869,457],[1946,1946],[2102,1261],[2189,3420],[2213,88],[3077,3461],[3302,363],[3305,763],[58,623],[71,111],[83,337],[98,462],[100,1221],[104,429],[111,276],[117,1203],[121,421],[121,3955],[256,1206],[259,269],[260,452],[260,565],[267,286],[272,291],[273,296],[273,374],[273,1005],[275,110],[276,269],[284,442],[284,517],[294,3015],[306,270],[313,1075],[318,269],[319,751],[344,288],[361,1267],[382,1340],[443,121],[460,564],[469,116],[473,2386],[604,1548],[633,257],[659,756],[806,1143],[836,115],[861,115],[863,614],[983,447],[1027,332],[1100,1261],[1183,115],[1188,612],[1278,1112],[1331,563],[1925,304],[1951,286],[2132,259],[2359,270],[2672,663],[3298,1591],[3340,274],[3485,1685],[3610,773],[4089,4068],[48,48],[74,430],[78,772],[98,349],[105,445],[112,257],[117,120],[260,577],[273,508],[278,754],[280,906],[291,277],[294,337],[307,1106],[335,116],[339,277],[347,508],[356,121],[393,108],[476,719],[499,314],[502,2637],[511,315],[654,339],[654,494],[718,307],[752,1743],[881,115],[954,1877],[998,296],[1137,314],[1273,384],[1481,500],[1491,2040],[1509,763],[1530,445],[1558,315],[1575,4140],[1746,605],[1895,528],[2004,640],[2146,763],[2256,560],[2302,338],[2446,259],[2449,270],[2548,436],[2560,773],[2587,378],[2790,691],[2966,494],[3053,551],[3063,315],[3113,457],[46,34],[67,4062],[98,428],[103,1145],[109,478],[112,485],[116,462],[116,546],[258,1486],[272,604],[275,915],[291,2512],[293,290],[294,374],[297,500],[301,259],[317,101],[317,421],[320,286],[347,386],[347,1322],[358,448],[376,2342],[387,330],[390,263],[390,1283],[398,369],[412,276],[413,2373],[418,1831],[464,701],[502,3849],[631,430],[747,1318],[757,2181],[816,270],[904,3429],[916,114],[921,471],[1043,315],[1160,314],[1298,447],[1342,490],[1438,1963],[1485,444],[2688,270],[2979,276],[3189,269],[3531,956],[4188,315],[98,444],[99,283],[99,284],[103,306],[103,640],[105,867],[108,307],[116,119],[117,619],[119,1379],[121,304],[267,899],[272,386],[273,444],[276,330],[278,584],[280,519],[287,121],[296,399],[301,284],[305,421],[313,494],[327,110],[346,110],[347,906],[355,471],[365,296],[402,337],[497,3221],[508,646],[567,446],[601,115],[623,303],[633,355],[707,561],[760,349],[781,108],[800,1533],[811,277],[833,503],[927,121],[988,559],[993,269],[1096,3884],[1227,449],[1271,277],[1364,477],[1444,271],[1491,412],[1516,963],[1543,314],[1596,1667],[1718,1002],[1866,315],[1887,2272],[2088,121],[2142,412],[2182,1085],[2361,580],[2624,306],[2746,338],[3246,283],[3545,276],[4245,119],[65,78],[80,2637],[84,3734],[97,315],[99,382],[99,992],[105,487],[119,301],[260,1308],[261,449],[269,691],[271,269],[275,483],[280,1054],[280,1296],[280,2952],[288,101],[292,110],[294,467],[321,1004],[341,1178],[351,290],[356,708],[359,2698],[387,271],[389,3791],[415,108],[415,874],[417,115],[418,584],[450,1302],[465,519],[483,876],[535,311],[591,2652],[618,1046],[657,114],[699,445],[954,612],[996,315],[998,120],[1019,98],[1229,831],[1333,318],[1506,3374],[1571,276],[1886,115],[1936,2819],[2252,269],[2580,3929],[2796,528],[3089,494],[3111,763],[3254,115],[3329,102],[3436,534],[3711,457],[4263,1201],[32,50],[72,269],[98,277],[102,763],[105,485],[109,1169],[115,119],[116,274],[116,443],[121,286],[257,97],[273,97],[280,1034],[284,534],[285,831],[289,100],[294,271],[296,1085],[303,396],[305,3277],[308,44],[310,356],[311,115],[316,121],[321,808],[325,2537],[347,1201],[347,1622],[351,391],[351,663],[366,4012],[382,290],[390,104],[417,320],[423,3179],[475,4094],[491,290],[598,474],[604,4198],[637,259],[657,122],[765,555],[806,391],[810,277],[846,485],[942,277],[1040,1233],[1068,311],[1142,339],[1326,4246],[1365,772],[1433,277],[1466,270],[1469,277],[1600,2099],[1607,1095],[2184,344],[2467,1104],[2472,868],[3680,382],[3683,813],[4185,283],[79,85],[81,117],[98,342],[102,506],[104,1079],[114,2036],[118,592],[122,121],[256,313],[271,344],[285,97],[287,310],[294,617],[309,867],[311,523],[330,291],[347,869],[359,269],[366,339],[366,1032],[384,627],[398,4107],[403,115],[448,900],[460,288],[465,2197],[470,288],[525,932],[547,574],[550,4073],[633,523],[760,495],[792,1158],[794,328],[798,831],[878,99],[883,1799],[894,270],[895,270],[916,580],[983,738],[995,2443],[1048,382],[1172,121],[1192,771],[1313,284],[1353,316],[1797,1092],[2037,259],[2462,270],[2539,444],[2889,4226],[2895,3134],[3010,1268],[3571,457],[4362,3604],[67,1051],[68,114],[69,109],[71,554],[100,719],[102,444],[102,856],[105,284],[111,274],[112,310],[112,328],[112,495],[112,838],[117,330],[122,277],[259,1327],[260,2210],[261,2370],[285,105],[285,644],[285,2702],[293,2294],[309,4171],[334,1960],[358,919],[361,412],[366,344],[366,3689],[398,611],[398,4016],[413,2745],[451,2294],[474,270],[491,682],[519,493],[525,3532],[529,1451],[552,101],[584,98],[591,581],[613,4286],[798,1089],[826,275],[869,2094],[898,875],[923,277],[942,1496],[987,315],[1044,770],[1151,291],[1240,263],[1337,4358],[1353,118],[1396,112],[1456,1923],[1467,605],[1492,1673],[1501,115],[1534,315],[1660,337],[1660,3605],[1718,373],[1772,1324],[2082,436],[2169,122],[2184,605],[2208,528],[2250,275],[2266,3984],[2358,328],[2467,363],[2575,263],[2601,269],[2685,504],[2710,267],[2902,315],[3018,641],[3101,270],[3535,2378],[3707,3857],[4510,120],[10,409],[44,623],[68,283],[77,663],[98,1171],[100,1060],[106,2595],[112,288],[114,494],[115,391],[116,755],[116,3727],[261,1915],[265,618],[270,115],[270,277],[271,1975],[272,2846],[274,766],[278,335],[278,470],[280,421],[284,770],[290,384],[319,441],[342,116],[345,478],[347,2292],[348,706],[365,284],[422,494],[429,4195],[447,319],[534,100],[567,1743],[593,3426],[606,1126],[609,2398],[632,772],[654,284],[672,425],[707,4172],[799,99],[904,1712],[907,3596],[1137,1337],[1436,270],[1530,283],[1564,275],[1693,368],[1744,2589],[1909,1351],[1918,3501],[2566,304],[2747,328],[2755,485],[3009,1774],[3191,1081],[3385,104],[3818,311],[3920,624],[66,3912],[67,291],[73,266],[83,99],[98,117],[114,430],[257,314],[258,743],[271,288],[273,344],[273,446],[273,743],[273,1556],[280,477],[287,516],[293,2003],[315,277],[321,1902],[336,2556],[342,2787],[347,1608],[464,301],[475,259],[497,2984],[521,4169],[567,4301],[574,314],[577,118],[582,1178],[606,103],[688,3980],[691,121],[721,2099],[724,1243],[744,617],[898,503],[976,478],[1019,783],[1038,2324],[1069,103],[1188,1196],[1357,1094],[1406,277],[1757,410],[1864,843],[1969,1197],[2384,269],[2400,270],[2534,745],[2598,114],[2692,270],[3037,2820],[3176,356],[3249,315],[3412,115],[3496,270],[3547,3516],[3548,121],[3656,338],[3794,311],[4034,436],[100,335],[101,448],[101,952],[106,743],[109,563],[109,1872],[114,685],[119,708],[257,378],[263,1224],[265,599],[272,304],[273,900],[282,552],[292,267],[293,291],[296,905],[314,1861],[319,815],[341,4238],[347,2176],[366,713],[370,557],[418,474],[440,865],[450,1393],[464,4466],[482,377],[496,1943],[496,3719],[497,3459],[535,1561],[550,4547],[633,411],[683,443],[699,315],[757,2326],[802,259],[875,315],[878,1285],[914,1092],[976,710],[1000,865],[1082,374],[1329,766],[1441,4566],[1468,315],[1491,109],[1649,306],[1727,121],[1737,3615],[1804,277],[2028,445],[2125,304],[2130,1004],[2188,315],[2453,4164],[2562,115],[2584,968],[2862,277],[2991,626],[3520,843],[3721,320],[3757,562],[3854,4331],[69,120],[98,307],[100,358],[101,291],[112,750],[114,636],[114,1430],[119,1190],[121,101],[256,1615],[261,105],[272,374],[273,4052],[280,3431],[284,99],[288,1071],[291,313],[298,1721],[309,358],[318,301],[347,1182],[360,101],[389,271],[390,4049],[463,1618],[467,288],[513,4122],[519,115],[529,1478],[547,704],[567,503],[593,270],[657,70],[672,1701],[672,3119],[677,318],[700,121],[785,533],[798,618],[859,277],[872,4460],[876,101],[1056,492],[1097,276],[1181,338],[1206,270],[1292,3195],[1410,269],[1523,1421],[1603,115],[1647,115],[1938,315],[1987,270],[2056,314],[2071,277],[2185,4345],[2191,1385],[2255,117],[2368,270],[2431,269],[2466,480],[2496,580],[2497,640],[2584,2779],[2673,626],[2765,270],[2948,626],[2993,2750],[3154,624],[3490,506],[46,95],[58,396],[67,1257],[98,283],[98,311],[98,429],[98,443],[99,682],[100,704],[100,3117],[102,636],[103,1136],[108,579],[111,120],[111,388],[112,358],[115,490],[121,344],[195,167],[258,118],[261,387],[267,448],[269,344],[271,122],[273,373],[275,97],[280,1060],[281,1117],[284,382],[287,952],[290,114],[293,1182],[293,2355],[294,1915],[305,267],[309,332],[309,2946],[316,378],[336,3543],[347,296],[347,2331],[347,4237],[358,103],[380,2350],[387,1385],[398,3808],[399,762],[411,533],[413,385],[422,274],[426,350],[429,1080],[430,3201],[440,115],[450,267],[463,4003],[470,457],[473,1158],[497,3114],[519,103],[531,327],[550,636],[553,1863],[591,1457],[591,2405],[591,3675],[599,290],[599,1144],[608,1673],[758,263],[830,1641],[831,270],[847,626],[916,584],[982,1296],[995,4416],[1048,756],[1137,2617],[1153,320],[1175,3475],[1229,379],[1350,629],[1716,1318],[1787,440],[1802,270],[2190,270],[2624,442],[2666,115],[2755,1908],[3198,3805],[3222,555],[3274,291],[3287,528],[3477,961],[69,78],[83,532],[102,369],[102,621],[102,1103],[109,704],[112,276],[115,382],[118,328],[120,270],[121,97],[256,487],[256,1549],[261,445],[272,477],[276,3844],[278,624],[280,1101],[285,795],[290,899],[293,809],[294,259],[294,612],[294,1668],[294,1889],[310,363],[312,532],[313,1340],[314,1113],[337,277],[347,641],[366,4721],[398,296],[398,4531],[411,290],[415,1863],[426,421],[450,870],[464,523],[478,319],[502,269],[508,115],[513,2215],[567,114],[582,263],[589,266],[604,115],[606,921],[606,4101],[620,2485],[622,870],[632,855],[721,4579],[757,4883],[769,115],[850,269],[985,304],[1038,2717],[1072,328],[1100,642],[1151,327],[1187,1808],[1304,315],[1441,470],[1448,634],[1841,4323],[1952,283],[2008,4359],[2140,370],[2164,504],[2340,771],[2692,277],[2763,270],[2884,823],[2908,1840],[3232,270],[4046,315],[73,286],[74,111],[80,2103],[83,104],[83,1835],[97,618],[101,599],[103,468],[109,274],[109,871],[110,330],[112,1751],[112,1849],[114,344],[117,270],[117,968],[121,288],[260,444],[263,1496],[272,539],[272,644],[280,1645],[285,1390],[293,445],[293,468],[294,291],[296,961],[298,4026],[307,421],[309,1002],[313,508],[337,121],[342,580],[359,4290],[384,342],[393,100],[418,114],[418,743],[422,3481],[426,3652],[467,2169],[499,110],[502,104],[502,433],[531,101],[581,4504],[606,1006],[631,4518],[645,3417],[690,3099],[697,490],[707,2117],[721,467],[740,112],[802,328],[838,356],[927,274],[932,2433],[987,304],[997,269],[1142,687],[1204,277],[1218,2039],[1236,809],[1419,270],[1644,275],[1675,276],[1772,945],[1892,634],[2061,327],[2140,1178],[2974,316],[3349,315],[3521,640],[4146,1673],[4186,121],[4242,271],[32,408],[63,34],[70,408],[98,1037],[99,378],[99,574],[99,628],[101,275],[104,342],[109,546],[109,554],[110,115],[114,583],[256,1848],[261,725],[263,315],[265,100],[266,101],[267,629],[272,2408],[272,2946],[280,601],[280,893],[290,661],[293,1314],[294,1196],[295,4527],[297,384],[306,815],[309,97],[309,2098],[317,1495],[334,103],[336,2302],[356,110],[359,2916],[369,98],[376,4754],[377,121],[382,314],[382,687],[390,100],[411,1115],[417,457],[422,781],[432,4128],[445,319],[456,2509],[498,772],[531,4366],[613,4628],[622,118],[645,103],[683,453],[696,555],[740,259],[760,433],[792,732],[830,382],[847,2270],[857,328],[954,277],[985,738],[993,495],[1009,959],[1015,109],[1056,564],[1119,3646],[1142,885],[1207,762],[1346,259],[1380,624],[1399,344],[1470,330],[1503,259],[1537,4982],[1551,523],[1583,4572],[1682,3299],[1694,457],[1768,746],[1864,624],[1900,1085],[1989,2949],[2020,4142],[2032,1335],[2052,3109],[2079,3368],[2191,717],[2358,551],[2371,115],[2453,1285],[2490,816],[2498,746],[2669,1178],[2751,1324],[2759,269],[2978,2907],[3290,751],[3484,2034],[3588,319],[3608,288],[3655,412],[3694,259],[4214,2845],[4256,528],[4941,358],[5032,1862],[5088,2216],[5098,119],[32,555],[67,1981],[67,4708],[80,3332],[83,395],[103,442],[112,342],[112,477],[119,270],[256,391],[256,763],[261,335],[267,314],[271,511],[272,1554],[273,974],[285,2326],[285,2537],[289,349],[292,941],[293,97],[297,109],[309,477],[309,577],[314,1126],[321,4090],[328,344],[336,942],[336,4570],[341,104],[345,892],[347,1959],[348,1098],[376,1224],[404,2013],[410,109],[417,102],[418,709],[433,112],[447,270],[456,641],[465,3900],[467,601],[525,4733],[529,1222],[547,114],[550,4434],[560,1457],[567,111],[622,2331],[634,626],[657,1004],[677,2205],[724,1821],[744,1182],[776,115],[799,2350],[809,269],[881,746],[935,344],[1048,1547],[1072,1610],[1109,1561],[1172,823],[1200,2623],[1266,580],[1356,277],[1384,2156],[1583,271],[1624,315],[1654,772],[1700,634],[1737,1528],[1911,2039],[1967,1634],[2078,492],[2078,915],[2145,315],[2180,288],[2400,101],[2475,315],[2689,2273],[2749,112],[2773,115],[2828,4814],[2915,115],[3325,551],[3478,532],[3785,316],[4685,1902],[32,381],[77,339],[102,723],[105,1180],[108,306],[112,447],[115,470],[115,900],[115,932],[116,387],[118,470],[121,335],[122,270],[195,168],[256,1221],[261,111],[261,270],[272,344],[278,1089],[281,1629],[281,2013],[286,115],[292,2850],[297,98],[304,715],[310,457],[314,485],[325,503],[341,735],[344,945],[347,354],[380,2094],[382,5205],[398,5033],[412,378],[413,108],[413,552],[417,494],[418,1103],[422,1249],[422,3042],[423,3512],[424,378],[442,270],[489,112],[489,288],[513,4348],[548,2030],[550,101],[567,3968],[584,101],[598,2554],[622,2790],[633,592],[642,108],[645,3662],[654,3720],[659,4823],[688,1760],[690,257],[727,756],[741,1585],[758,561],[775,314],[798,3625],[806,1131],[890,794],[904,3186],[907,4965],[930,506],[959,277],[1056,4075],[1151,795],[1266,2181],[1378,378],[1431,315],[1462,277],[1506,283],[1677,436],[1912,592],[2006,1924],[2039,121],[2067,2883],[2191,371],[2211,691],[2396,277],[2642,4842],[2671,1502],[2748,270],[3138,327],[3175,270],[3278,344],[3341,270],[3499,115],[3688,2529],[3748,511],[3781,277],[3891,330],[3985,4891],[4147,634],[4573,122],[4611,2284],[4976,4857],[5085,315],[99,1051],[102,342],[108,2551],[109,337],[109,344],[109,1027],[112,408],[115,3165],[116,1095],[119,97],[119,290],[258,311],[258,3397],[267,304],[278,1262],[278,2880],[280,809],[281,2619],[283,277],[284,121],[293,342],[294,633],[294,641],[339,115],[353,288],[353,338],[366,5160],[385,277],[411,335],[417,815],[418,3275],[422,1614],[423,801],[450,4415],[451,692],[467,275],[476,121],[496,2444],[497,4173],[531,795],[591,1952],[599,1054],[633,4826],[646,107],[654,313],[682,115],[721,101],[769,270],[789,478],[792,1998],[825,115],[830,330],[988,316],[1040,1081],[1109,381],[1158,97],[1227,296],[1227,369],[1228,546],[1263,1389],[1354,678],[1424,277],[1454,115],[1456,973],[1458,369],[1659,277],[1732,114],[2038,283],[2046,288],[2141,2136],[2166,283],[2232,1891],[2265,626],[2287,3203],[2295,315],[2374,277],[2605,270],[2731,4084],[2822,540],[2892,1998],[3124,4091],[3204,121],[3281,313],[3583,121],[3638,415],[3993,315],[4397,746],[5000,315],[41,46],[73,83],[76,462],[80,2547],[84,2419],[95,368],[98,288],[99,3128],[107,485],[114,274],[115,930],[116,864],[117,323],[119,277],[256,445],[256,2913],[258,385],[258,3047],[260,4501],[262,961],[263,411],[263,605],[265,4426],[269,107],[273,1272],[278,551],[278,2452],[280,453],[281,925],[281,1520],[283,320],[284,277],[285,1574],[292,2279],[294,1026],[294,3813],[325,358],[325,952],[342,115],[342,523],[347,428],[359,319],[382,391],[387,725],[390,387],[403,877],[413,330],[417,685],[438,500],[443,101],[454,276],[478,275],[479,3802],[482,1874],[529,1654],[567,4387],[624,756],[631,855],[664,2548],[688,2933],[690,428],[724,745],[724,1368],[738,640],[785,1358],[829,315],[830,412],[830,1203],[878,618],[883,1417],[891,5353],[998,420],[1010,115],[1108,1351],[1109,4564],[1165,270],[1229,417],[1287,314],[1408,1493],[1481,715],[1534,330],[1543,1434],[1682,3071],[1689,304],[1783,277],[1815,269],[1822,1792],[1918,3319],[1921,1319],[2023,1823],[2126,561],[2420,56],[2447,115],[2642,759],[2961,634],[3035,277],[3135,2626],[3144,436],[3187,344],[3205,270],[3445,555],[3503,276],[3773,277],[4363,523],[4364,412],[4502,97],[4881,121],[5192,386],[5461,1148],[65,1545],[76,117],[84,2612],[98,445],[99,577],[100,114],[102,425],[102,519],[108,687],[110,335],[110,448],[112,516],[112,884],[112,2525],[115,1128],[116,511],[118,374],[119,764],[256,267],[257,266],[261,2036],[263,344],[272,417],[272,430],[278,304],[278,374],[287,271],[290,108],[290,315],[293,277],[294,2139],[304,371],[305,1608],[306,114],[312,104],[314,441],[314,2318],[316,286],[320,382],[341,4037],[347,1060],[358,269],[358,559],[361,4444],[366,871],[376,3308],[393,335],[413,3372],[417,2585],[418,468],[423,4833],[426,1915],[441,1285],[442,277],[451,856],[464,296],[465,682],[467,301],[475,443],[502,4517],[521,855],[531,1201],[549,277],[588,1073],[591,102],[591,1050],[654,259],[682,291],[690,114],[707,313],[738,579],[740,4317],[741,296],[775,4417],[792,276],[830,725],[880,489],[1011,3498],[1141,4041],[1200,109],[1266,555],[1278,634],[1307,270],[1361,288],[1414,1064],[1479,121],[1513,290],[1604,762],[1697,4948],[1739,1795],[1978,574],[2005,736],[2102,4013],[2105,555],[2120,315],[2152,701],[2221,973],[2251,1129],[2270,283],[2283,73],[2531,270],[2670,1267],[2867,717],[3059,338],[3217,270],[3226,973],[3333,307],[3335,107],[3339,494],[3373,1089],[3408,551],[3723,355],[3770,270],[3817,4785],[3827,1678],[3939,259],[4083,615],[4935,304],[5310,4475],[87,284],[87,350],[99,387],[99,1465],[100,519],[100,621],[101,411],[101,441],[104,276],[104,444],[105,605],[112,374],[117,1882],[118,3256],[119,485],[258,120],[261,311],[266,956],[272,1027],[273,2698],[274,355],[278,441],[280,302],[280,378],[280,5021],[285,1922],[294,511],[294,4136],[304,808],[305,2682],[309,2355],[314,358],[319,592],[320,97],[321,859],[325,1621],[341,5319],[352,102],[360,2279],[398,3314],[416,112],[423,644],[423,1037],[425,2284],[440,1818],[445,519],[450,666],[465,4750],[467,269],[487,259],[487,1004],[500,412],[509,98],[518,300],[547,108],[548,1418],[591,99],[598,1348],[618,977],[631,4914],[631,5670],[637,4926],[680,626],[689,1478],[707,284],[732,276],[733,557],[744,583],[802,1549],[891,452],[898,4069],[932,759],[942,957],[942,1752],[978,303],[985,369],[988,1487],[1021,373],[1047,102],[1048,330],[1048,813],[1068,523],[1117,115],[1134,1584],[1164,3678],[1188,1012],[1235,1351],[1258,710],[1322,344],[1331,2554],[1346,374],[1403,1385],[1420,4344],[1459,634],[1506,551],[1513,504],[1583,533],[1605,270],[2118,1223],[2155,269],[2155,492],[2167,494],[2213,86],[2287,311],[2336,1757],[2360,517],[2400,277],[2488,4315],[2618,330],[2625,1186],[2659,1322],[3052,3448],[3097,270],[3122,315],[3572,1227],[3639,641],[3645,973],[3672,121],[3806,511],[3974,867],[4412,533],[4910,974],[5130,291],[5730,823],[32,277],[65,84],[80,283],[97,120],[98,2152],[99,403],[100,387],[102,5007],[103,349],[105,580],[109,1005],[110,490],[111,99],[111,421],[111,1862],[112,275],[115,578],[121,5587],[256,1554],[258,313],[258,327],[259,605],[266,619],[267,337],[272,283],[272,337],[272,3593],[278,1022],[280,443],[284,564],[288,99],[289,296],[293,581],[294,601],[297,108],[298,1849],[315,1177],[317,443],[321,263],[321,1168],[336,651],[344,1736],[352,559],[376,290],[387,112],[387,717],[389,3893],[398,470],[398,2916],[422,339],[438,1050],[450,269],[487,288],[492,5087],[525,377],[567,4505],[572,2398],[582,620],[598,3042],[600,2343],[610,10],[637,627],[664,304],[695,1112],[740,320],[758,290],[802,1225],[878,369],[894,115],[894,315],[944,121],[1001,107],[1011,116],[1109,469],[1159,2373],[1251,1368],[1298,864],[1326,483],[1353,629],[1472,605],[1489,115],[1503,620],[1590,1612],[1621,1152],[1635,1922],[1727,773],[1787,1434],[1918,999],[1928,634],[2118,411],[2189,3996],[2221,957],[2231,275],[2329,274],[2379,3228],[2510,4827],[2618,316],[2671,3692],[2672,447],[2689,1356],[2749,885],[2756,115],[2782,816],[2891,2397],[3454,816],[3640,5176],[3760,511],[3885,303],[3964,315],[4126,1291],[4132,270],[4139,5287],[4288,442],[4396,1080],[4461,2458],[4641,751],[4658,808],[5268,424],[5710,1944],[5801,111],[46,41],[80,269],[84,546],[99,723],[101,102],[102,644],[103,2276],[107,651],[108,290],[112,1192],[117,528],[118,523],[195,173],[258,1419],[259,118],[260,560],[269,1720],[275,288],[280,546],[280,3048],[284,793],[284,823],[285,269],[285,301],[290,843],[294,378],[294,536],[294,2426],[298,4002],[309,636],[313,1004],[316,2106],[321,577],[321,2512],[328,104],[332,270],[336,2847],[339,2034],[359,5093],[362,115],[379,1390],[382,1736],[391,115],[401,617],[440,363],[460,5334],[464,723],[464,3188],[473,363],[475,530],[487,105],[502,108],[508,485],[535,3761],[550,2452],[553,415],[553,2385],[596,5487],[598,307],[620,99],[639,1139],[642,384],[648,327],[664,1018],[677,1392],[712,893],[721,270],[721,395],[758,1129],[775,116],[800,4382],[853,115],[1077,114],[1082,682],[1235,269],[1273,5331],[1326,429],[1365,421],[1400,1960],[1444,1872],[1468,269],[1481,629],[1537,447],[1579,115],[1604,634],[1677,452],[1684,378],[1744,121],[1770,270],[1839,296],[1970,277],[2016,984],[2046,766],[2074,528],[2112,4072],[2142,4231],[2171,1490],[2185,1063],[2188,445],[2234,523],[2501,706],[2536,314],[2598,5285],[2663,579],[2759,1199],[2802,604],[2844,319],[2888,291],[2975,762],[3006,387],[3187,2806],[3207,5362],[3237,269],[3251,3058],[3327,338],[3572,306],[3833,344],[4251,311],[4436,773],[4828,5881],[4977,1819],[5105,430],[5212,436],[5269,3013],[5555,915],[5850,579],[10,32],[73,86],[79,82],[79,342],[99,310],[99,551],[100,953],[103,445],[103,804],[104,395],[105,1795],[107,97],[107,259],[115,831],[115,1030],[116,918],[117,859],[118,311],[256,1057],[261,259],[261,546],[261,1023],[265,104],[267,108],[272,508],[272,646],[280,3966],[281,5916],[293,268],[293,590],[294,306],[294,751],[295,4021],[297,815],[305,1168],[309,709],[314,1002],[317,111],[352,5057],[354,112],[358,315],[359,275],[359,3878],[365,344],[366,452],[366,574],[369,452],[380,1655],[382,706],[396,1423],[413,870],[418,1253],[423,108],[423,1397],[423,3311],[433,735],[456,2572],[464,444],[467,344],[470,416],[475,1943],[487,110],[487,1225],[495,338],[497,1366],[502,3332],[508,1267],[521,1023],[554,101],[556,110],[581,1362],[589,291],[590,335],[601,275],[628,115],[628,332],[633,823],[637,5392],[654,332],[707,773],[769,315],[789,328],[792,555],[817,259],[836,277],[870,1129],[930,523],[1021,277],[1048,385],[1069,1958],[1108,2438],[1207,270],[1228,1023],[1247,5967],[1284,5008],[1310,315],[1364,3399],[1380,277],[1411,115],[1477,315],[1573,1573],[1675,1924],[1687,315],[1818,777],[1909,3904],[1966,115],[1967,1515],[1989,1487],[1992,528],[2033,412],[2035,4994],[2192,480],[2225,269],[2335,2062],[2475,626],[2479,1129],[2788,1094],[2858,5811],[2891,5592],[3079,5010],[3121,956],[3220,315],[3235,1268],[3335,3203],[3354,121],[3441,1830],[3471,363],[3553,98],[3553,1502],[3560,2106],[3637,1061],[3644,369],[3749,580],[3898,3709],[4440,3965],[4612,2091],[5117,276],[5276,1114],[5315,338],[5512,271],[6136,3396],[6160,97],[65,1696],[83,2011],[85,110],[100,557],[101,783],[104,1476],[108,444],[109,311],[109,504],[109,701],[114,377],[115,328],[115,429],[119,108],[119,445],[256,271],[258,310],[263,102],[269,626],[269,678],[271,2097],[272,1964],[272,5611],[274,99],[274,112],[283,363],[285,579],[285,2452],[294,871],[304,447],[305,615],[306,111],[311,528],[328,1199],[339,288],[341,330],[345,5092],[347,1358],[352,1559],[359,270],[366,601],[380,759],[390,5412],[423,290],[432,296],[454,274],[460,112],[465,5602],[474,277],[487,109],[491,1547],[496,288],[498,330],[525,5738],[542,520],[542,1478],[550,108],[553,98],[553,620],[553,3527],[553,4822],[567,117],[571,115],[586,1734],[591,5891],[599,3365],[620,557],[620,801],[627,2041],[631,5621],[632,270],[655,115],[657,342],[664,719],[707,310],[724,109],[724,2655],[740,3717],[741,440],[760,328],[830,263],[898,3529],[957,4085],[966,511],[1040,328],[1068,344],[1069,629],[1165,115],[1172,104],[1212,1660],[1228,5924],[1281,276],[1283,382],[1309,107],[1326,646],[1434,1563],[1444,621],[1485,6184],[1488,344],[1511,626],[1523,5347],[1537,576],[1605,115],[1676,504],[1688,517],[1754,876],[1769,277],[1809,115],[1864,485],[1868,107],[1878,3234],[1978,621],[2102,3630],[2113,2097],[2142,756],[2218,290],[2356,4657],[2497,110],[2566,843],[2661,3130],[2669,962],[2670,339],[2828,5070],[3010,342],[3052,2438],[3154,719],[3313,270],[3379,559],[3890,661],[3969,304],[4141,363],[4189,1267],[4240,110],[4519,457],[4701,640],[4783,374],[4816,691],[5210,663],[5257,532],[5486,5744],[5498,315],[5626,1760],[5821,560],[33,623],[65,4179],[67,1090],[82,69],[97,885],[98,539],[98,1255],[99,1054],[104,892],[104,1143],[108,313],[109,342],[109,734],[112,1086],[115,495],[115,1983],[115,3314],[117,663],[119,692],[121,620],[256,892],[257,1055],[261,892],[268,356],[271,984],[273,708],[278,442],[283,436],[285,519],[285,1997],[285,2396],[288,363],[292,1297],[293,633],[293,1215],[295,5833],[309,1113],[321,99],[321,477],[330,108],[337,276],[344,116],[344,452],[344,468],[347,1032],[361,1045],[384,734],[390,5295],[398,110],[398,1272],[409,392],[416,318],[445,115],[445,5065],[458,3365],[464,369],[464,682],[475,267],[475,6216],[480,736],[482,3576],[487,115],[502,2021],[521,3153],[524,2577],[529,468],[536,624],[577,559],[582,370],[588,564],[591,5198],[613,5590],[617,275],[622,3372],[625,110],[691,805],[707,369],[713,5819],[718,1253],[785,301],[806,490],[806,2354],[847,852],[942,2146],[957,2623],[966,5484],[1001,867],[1116,121],[1153,495],[1164,2882],[1183,277],[1235,1561],[1236,1143],[1239,103],[1286,4736],[1408,403],[1409,523],[1565,98],[1572,115],[1669,115],[1719,120],[1925,719],[2004,1616],[2016,457],[2046,457],[2093,315],[2196,5168],[2199,1080],[2240,1442],[2333,619],[2425,1793],[2501,315],[2559,6374],[2710,2646],[2731,1340],[3001,277],[3038,320],[3070,3698],[3186,533],[3200,109],[3257,6102],[3373,621],[3379,316],[3487,266],[3792,381],[4023,562],[4135,1397],[4151,315],[4421,746],[4427,3528],[4739,381],[5177,335],[5330,1502],[5489,98],[5684,290],[5696,271],[6225,3331],[6330,2914],[32,396],[65,83],[80,263],[83,611],[95,397],[98,962],[100,270],[100,468],[102,114],[102,290],[102,443],[103,4025],[104,911],[105,442],[112,999],[114,436],[116,358],[117,579],[121,114],[195,161],[256,501],[258,1385],[260,520],[271,494],[273,555],[273,2594],[275,745],[275,4909],[277,270],[278,269],[281,116],[283,592],[285,429],[285,650],[287,3860],[289,1804],[293,2450],[294,519],[309,1397],[310,1324],[317,1190],[319,579],[356,470],[366,342],[366,369],[376,286],[376,4778],[379,815],[390,98],[398,119],[400,2473],[406,286],[422,501],[422,743],[422,3104],[451,2011],[458,110],[464,387],[464,5954],[475,114],[475,2096],[497,4856],[513,4370],[525,6381],[556,118],[567,3047],[577,316],[582,1291],[598,501],[598,1701],[606,2395],[610,2085],[613,118],[613,120],[620,118],[623,4259],[632,2300],[636,115],[637,374],[645,5516],[648,111],[657,318],[674,368],[688,382],[689,468],[697,1249],[707,5721],[721,2284],[721,5399],[758,1545],[772,344],[781,269],[791,626],[800,612],[852,306],[888,115],[890,276],[987,3894],[1011,1487],[1110,1872],[1141,410],[1160,2988],[1164,110],[1197,101],[1201,276],[1223,337],[1229,3944],[1273,1442],[1292,1206],[1297,470],[1331,565],[1375,1296],[1379,6462],[1429,6340],[1441,1118],[1509,868],[1586,306],[1662,485],[1731,621],[1802,277],[1986,5589],[2053,403],[2158,277],[2252,3353],[2341,448],[2397,4471],[2414,1595],[2449,338],[2471,344],[2550,115],[2566,624],[2597,121],[2632,338],[2651,315],[2669,564],[2757,270],[2827,274],[2834,1761],[2861,115],[2869,2156],[2873,4835],[2998,1240],[3100,378],[3325,328],[3427,576],[3487,1794],[3492,277],[3676,906],[3723,4615],[3858,1799],[3990,115],[3992,385],[4217,580],[4273,378],[4463,344],[4479,706],[4550,306],[4588,270],[4621,1869],[4773,494],[4958,580],[5398,1650],[5787,3991],[5964,1862],[5990,4336],[6606,561],[59,303],[66,1032],[66,2532],[67,470],[69,500],[69,2778],[78,68],[84,274],[84,443],[89,335],[97,274],[97,417],[98,503],[101,808],[102,277],[102,577],[103,275],[103,1059],[104,306],[105,306],[108,354],[108,445],[109,296],[109,467],[109,1308],[109,3119],[110,310],[110,2300],[112,296],[112,373],[115,1262],[121,1018],[257,116],[259,523],[263,288],[270,121],[272,565],[278,1169],[280,354],[280,489],[280,1165],[280,1470],[281,382],[287,470],[288,1902],[290,1098],[293,296],[293,2942],[294,906],[294,3546],[304,1385],[321,104],[335,277],[337,899],[347,6042],[348,4809],[359,1169],[365,2033],[366,377],[376,120],[376,369],[387,2041],[390,5890],[401,615],[413,1496],[418,2197],[422,1637],[426,257],[433,478],[456,2122],[464,349],[464,6405],[464,6578],[465,275],[473,4918],[477,5457],[491,274],[502,704],[502,1743],[502,5814],[547,121],[550,3529],[550,5672],[584,717],[601,277],[628,270],[631,1964],[631,6253],[664,290],[683,1328],[688,957],[690,584],[690,4025],[721,1414],[721,6183],[775,1813],[794,957],[798,337],[798,666],[799,1792],[806,1086],[814,520],[833,2919],[852,579],[878,1181],[883,5508],[895,115],[895,511],[898,1528],[930,338],[996,115],[1040,867],[1069,327],[1077,270],[1121,5937],[1156,115],[1164,112],[1232,815],[1236,443],[1243,277],[1316,436],[1357,2711],[1372,480],[1373,1878],[1384,551],[1408,809],[1460,315],[1467,436],[1503,304],[1506,328],[1607,612],[1613,772],[1623,4088],[1655,523],[1687,6203],[1759,1063],[1802,338],[1828,656],[1854,717],[1857,1073],[1859,315],[1888,288],[1909,433],[1951,119],[1999,1571],[2027,719],[2304,5804],[2358,867],[2397,288],[2461,661],[2471,519],[2472,277],[2498,101],[2505,751],[2539,283],[2555,277],[2685,101],[2771,270],[2816,494],[2863,115],[3180,2339],[3235,511],[3363,71],[3405,331],[3454,2595],[3560,121],[3568,1906],[3577,494],[3584,1975],[3619,270],[3659,1634],[3672,2106],[3773,288],[3840,444],[3887,3999],[4007,2652],[4243,290],[4298,291],[4385,568],[4587,112],[4684,1905],[4758,291],[4810,950],[4854,275],[4859,3509],[4884,344],[5109,328],[5949,411],[5963,1093],[6602,5494],[32,90],[32,1610],[68,642],[82,2968],[98,624],[100,445],[103,296],[104,111],[104,2787],[107,2847],[108,950],[115,110],[115,1998],[116,646],[117,745],[121,320],[256,259],[256,328],[256,781],[257,290],[260,781],[261,615],[263,121],[263,385],[268,905],[271,2402],[272,704],[273,277],[273,5189],[278,562],[283,1098],[285,263],[285,619],[285,1182],[285,2354],[288,2776],[289,448],[293,1153],[294,270],[294,1177],[296,1430],[297,3580],[305,4677],[309,474],[319,121],[325,1107],[336,290],[336,3552],[344,363],[344,1407],[371,511],[376,284],[376,2014],[381,562],[389,1752],[413,98],[434,1804],[438,5413],[440,110],[450,1336],[456,1893],[465,1068],[497,2571],[497,4897],[497,5256],[502,495],[508,277],[552,119],[567,4571],[599,2381],[656,284],[690,328],[707,306],[747,115],[789,1648],[798,107],[870,2183],[891,5393],[958,2480],[982,2933],[993,315],[995,4204],[1003,1297],[1019,270],[1077,2840],[1180,270],[1213,501],[1213,6091],[1221,98],[1283,276],[1331,580],[1373,328],[1378,1610],[1409,1761],[1435,656],[1441,5718],[1477,116],[1492,1080],[1503,973],[1514,344],[1582,1299],[1603,3426],[1865,102],[1913,115],[2017,4235],[2153,4380],[2158,269],[2221,1923],[2244,335],[2368,338],[2427,259],[2510,1696],[2560,5927],[2663,1475],[2687,444],[2763,271],[2834,986],[3001,615],[3007,1139],[3124,1186],[3264,270],[3317,270],[3505,583],[3517,794],[3659,1515],[3724,719],[3741,1889],[3760,1085],[3769,756],[3886,2084],[4149,270],[4262,738],[4333,457],[4638,2845],[4697,3044],[4936,369],[5020,410],[5312,589],[5566,335],[5829,706],[5867,641],[5933,457],[6200,304],[6904,304],[32,1068],[73,67],[76,101],[84,2096],[98,665],[99,719],[101,557],[102,619],[102,2346],[103,276],[103,319],[103,1616],[105,876],[108,1280],[109,335],[109,770],[109,864],[115,2366],[116,659],[118,508],[119,271],[119,647],[195,175],[256,117],[258,1677],[260,301],[261,713],[272,276],[272,808],[274,823],[278,382],[280,349],[283,528],[285,453],[285,3950],[287,425],[293,369],[296,493],[298,259],[298,457],[306,288],[308,46],[309,110],[309,328],[314,743],[314,2055],[319,277],[327,320],[328,2529],[336,5724],[341,2571],[351,682],[351,2315],[358,335],[359,311],[361,116],[361,3173],[366,3223],[379,2331],[384,2478],[393,557],[398,107],[398,1308],[398,3165],[406,99],[417,865],[422,487],[423,374],[426,617],[450,6446],[454,98],[464,477],[475,6591],[477,745],[502,344],[502,992],[504,3234],[515,327],[524,271],[525,892],[547,495],[550,6036],[553,286],[591,5677],[598,617],[637,2355],[668,338],[688,2556],[690,795],[690,1566],[690,5934],[694,115],[707,5468],[743,2657],[762,626],[770,1319],[775,4554],[781,2525],[802,349],[802,5606],[806,1668],[807,865],[833,1089],[854,270],[881,121],[976,559],[985,266],[1003,4830],[1040,313],[1048,112],[1057,485],[1100,349],[1105,1990],[1119,506],[1153,315],[1188,2627],[1239,1203],[1470,1324],[1480,2478],[1503,3383],[1526,1478],[1609,2080],[1682,117],[1682,441],[1686,1622],[1694,277],[1828,407],[1856,6204],[1887,316],[1896,288],[1980,1112],[2006,1306],[2016,685],[2195,950],[2221,579],[2232,384],[2277,115],[2312,793],[2335,442],[2336,2952],[2395,421],[2529,121],[2557,559],[2597,763],[2791,6507],[2998,4353],[3020,442],[3020,963],[3022,838],[3023,277],[3085,315],[3097,373],[3135,311],[3226,1923],[3250,115],[3380,1533],[3402,6483],[3495,304],[3519,583],[3539,97],[3583,950],[3655,5923],[3694,1093],[3827,1490],[4207,381],[4298,275],[4474,109],[4567,356],[4626,523],[4683,1794],[4695,1708],[4755,270],[4885,3999],[4949,3482],[5013,1106],[5019,867],[5074,121],[5216,984],[5691,304],[5797,275],[5805,316],[6153,121],[6417,283],[7023,288],[46,44],[63,95],[65,114],[69,614],[69,3036],[73,2635],[77,386],[77,1269],[83,4078],[87,445],[97,710],[97,6988],[98,1249],[100,893],[102,754],[102,1336],[102,2528],[103,328],[103,713],[104,478],[106,369],[109,441],[112,306],[112,943],[114,115],[116,810],[117,304],[121,651],[256,276],[260,291],[262,296],[271,283],[271,1843],[272,284],[272,470],[272,1544],[272,2441],[275,99],[278,1727],[278,1958],[278,4749],[285,1247],[285,1831],[287,635],[289,4986],[290,449],[290,2040],[291,110],[293,430],[293,2702],[297,122],[298,445],[298,3080],[301,738],[304,1073],[304,1331],[305,2014],[316,116],[320,109],[328,956],[339,304],[347,3400],[356,562],[366,111],[413,270],[418,121],[418,2972],[423,6875],[433,470],[451,4671],[464,111],[464,6910],[465,633],[478,277],[491,442],[496,2750],[506,378],[508,117],[508,2860],[513,5717],[524,1872],[525,1314],[535,98],[535,1351],[563,115],[581,116],[582,6198],[598,311],[598,561],[598,5091],[601,736],[604,624],[620,339],[652,651],[667,335],[672,1854],[675,270],[681,4851],[688,4675],[690,386],[690,1515],[697,1092],[713,640],[724,4662],[728,269],[741,494],[757,307],[760,5278],[775,3498],[784,99],[802,1002],[829,2322],[830,715],[854,1081],[887,2682],[891,6280],[932,115],[935,804],[983,3894],[1004,3328],[1031,115],[1040,4248],[1056,5591],[1069,339],[1082,4071],[1096,111],[1096,963],[1122,384],[1137,109],[1142,344],[1206,277],[1229,319],[1266,725],[1266,986],[1281,770],[1284,2691],[1329,338],[1338,384],[1347,327],[1361,103],[1403,1991],[1410,315],[1413,315],[1418,2139],[1427,10],[1623,1808],[1670,746],[1807,4420],[1912,2073],[1967,2621],[1986,6193],[2020,6911],[2054,685],[2109,115],[2128,277],[2180,277],[2195,736],[2251,6106],[2296,562],[2576,385],[2590,874],[2613,1685],[2707,277],[2720,315],[2726,865],[2855,661],[2867,1385],[3327,793],[3348,634],[3385,4097],[3489,1863],[3503,3044],[3519,1958],[3522,533],[3539,7042],[3676,1690],[3684,115],[3908,1475],[3910,442],[3939,1093],[4081,338],[4190,307],[4234,1585],[4244,1442],[4309,4027],[4319,506],[4385,678],[4590,661],[4707,773],[4839,6805],[4874,5573],[4900,2985],[5016,344],[5138,270],[5145,1080],[5554,1197],[5688,101],[5707,115],[5746,3059],[5799,1715],[5896,271],[6365,314],[6624,328],[6708,511],[6789,301],[6828,267],[6978,108],[7034,1862],[67,2676],[68,101],[82,101],[83,332],[87,3602],[95,396],[98,528],[98,843],[98,1566],[99,307],[100,349],[104,621],[105,119],[105,388],[105,1255],[108,271],[110,344],[114,313],[114,770],[115,313],[116,4392],[117,620],[118,436],[256,342],[256,617],[259,328],[260,3809],[261,536],[265,480],[267,98],[271,619],[271,1168],[272,311],[272,755],[273,3878],[274,457],[275,356],[276,1677],[280,355],[280,1567],[280,3188],[281,470],[283,107],[287,301],[287,1283],[288,1559],[293,2098],[293,4129],[294,1240],[294,1614],[294,1622],[294,5488],[304,103],[306,277],[313,618],[314,111],[314,276],[319,257],[342,661],[342,1502],[347,277],[351,2962],[356,283],[359,1582],[359,6453],[365,2623],[377,270],[380,306],[387,745],[390,109],[412,108],[416,101],[423,283],[426,536],[432,4635],[434,448],[441,4227],[442,523],[451,1471],[459,269],[460,2931],[464,290],[475,546],[497,7024],[501,97],[502,892],[521,1414],[525,452],[527,1820],[535,701],[550,693],[550,6493],[553,2095],[556,2620],[566,1178],[567,506],[567,1397],[582,3607],[596,2080],[606,100],[622,269],[631,291],[631,590],[645,823],[645,5781],[654,442],[672,2165],[690,1634],[704,274],[727,1093],[730,2241],[741,1402],[741,1582],[769,277],[789,99],[802,2073],[852,621],[870,962],[910,930],[924,801],[942,1285],[948,5687],[953,815],[1050,270],[1096,6837],[1100,263],[1116,563],[1135,121],[1145,344],[1149,2858],[1212,112],[1227,339],[1229,5910],[1309,6735],[1329,1118],[1336,961],[1363,634],[1364,501],[1428,412],[1459,115],[1488,112],[1488,3330],[1503,783],[1571,363],[1598,1240],[1609,735],[1614,338],[1623,2317],[1720,1053],[1720,1536],[1832,115],[1850,115],[1965,2533],[1980,270],[2000,605],[2113,1053],[2164,2962],[2185,6272],[2193,1763],[2196,371],[2202,288],[2218,101],[2319,338],[2470,1486],[2561,115],[2605,277],[2642,327],[2654,277],[2804,374],[2818,115],[2860,1117],[2908,1268],[3014,580],[3100,1728],[3149,2127],[3184,315],[3189,275],[3263,315],[3520,624],[3547,97],[3548,661],[3609,270],[3611,316],[3724,108],[3837,492],[3890,746],[3945,5893],[4095,876],[4228,805],[4273,263],[4304,1487],[4321,2097],[4469,2683],[4633,121],[4667,344],[4831,624],[4834,416],[4844,1975],[4901,746],[4940,876],[5022,270],[5111,520],[5272,511],[5538,1215],[5610,444],[5745,532],[5803,616],[5822,384],[5995,4296],[6224,1165],[6385,1075],[6523,500],[7431,661],[7434,103],[32,51],[32,54],[32,122],[65,3606],[66,114],[69,104],[70,900],[72,275],[72,403],[73,76],[73,84],[75,1848],[76,687],[77,332],[78,468],[78,3006],[79,76],[97,433],[98,306],[98,876],[100,1742],[100,2665],[102,477],[102,665],[103,3792],[108,485],[109,440],[109,579],[109,1440],[114,1168],[115,773],[115,927],[118,1678],[120,523],[195,162],[259,793],[260,536],[261,519],[261,1114],[263,3527],[266,115],[267,1089],[271,471],[272,533],[272,1165],[273,350],[273,442],[273,447],[273,884],[275,335],[277,1563],[280,284],[283,1882],[284,618],[285,296],[285,382],[285,1864],[285,7076],[289,270],[292,107],[293,354],[294,403],[296,1843],[298,310],[298,487],[301,291],[304,2533],[309,373],[309,3068],[310,275],[310,2402],[313,109],[335,101],[347,1964],[347,5031],[352,732],[359,271],[359,1328],[359,6118],[366,283],[366,313],[366,5961],[366,6347],[366,7059],[380,263],[380,3705],[387,412],[390,3606],[390,7355],[392,32],[392,299],[398,332],[398,7356],[404,363],[406,301],[418,111],[422,307],[422,319],[429,793],[438,4372],[440,349],[453,276],[456,379],[464,574],[465,1079],[470,494],[470,710],[473,1324],[473,3172],[475,7528],[487,277],[489,316],[491,7228],[497,1118],[508,276],[509,6780],[513,291],[515,4249],[521,6115],[525,1835],[550,290],[589,1794],[591,3915],[598,478],[606,356],[606,899],[613,447],[620,290],[620,344],[622,2033],[633,992],[645,1366],[652,330],[664,1066],[688,2215],[694,651],[703,269],[741,1032],[745,288],[757,961],[790,6583],[806,307],[852,386],[883,1702],[894,678],[922,277],[930,766],[932,2657],[941,2024],[957,1774],[966,1268],[974,457],[1019,2179],[1021,999],[1061,277],[1077,386],[1175,474],[1239,2272],[1271,746],[1297,382],[1348,6664],[1364,328],[1408,3128],[1444,1089],[1479,592],[1507,277],[1655,457],[1722,6323],[1912,1487],[2020,474],[2130,1496],[2170,315],[2196,500],[2248,428],[2256,563],[2313,2284],[2327,951],[2479,1825],[2485,115],[2576,715],[2578,3729],[2670,6436],[2729,1894],[2731,97],[2757,640],[2772,103],[2782,445],[2782,3948],[2869,3845],[3198,801],[3205,511],[3295,315],[3354,661],[3393,1580],[3394,391],[3408,867],[3416,277],[3477,283],[3682,121],[3744,627],[3748,1085],[3765,506],[3974,328],[4060,88],[4130,415],[4167,335],[4413,103],[4451,691],[4482,270],[4492,108],[4574,304],[4616,1515],[4680,2106],[4690,485],[4843,338],[4899,84],[5506,277],[5743,7132],[5831,815],[5869,1701],[6317,634],[6354,4580],[6376,7557],[6425,4004],[6530,284],[6546,504],[6637,3516],[6655,7173],[6671,328],[6702,715],[6812,1749],[7022,892],[7465,1869],[7640,101],[65,76],[65,100],[68,1861],[71,335],[77,283],[77,2101],[78,283],[83,3165],[85,4905],[98,449],[100,6557],[102,259],[102,296],[102,927],[104,374],[106,633],[108,339],[108,478],[108,1032],[109,628],[112,1875],[114,296],[115,108],[115,411],[115,1062],[115,1081],[115,2508],[116,374],[116,2846],[118,1487],[256,536],[257,2315],[260,469],[261,2445],[263,415],[263,3330],[265,121],[269,436],[272,743],[273,1397],[278,5693],[280,121],[280,6932],[281,263],[285,1785],[285,4192],[285,5941],[287,4694],[291,120],[292,651],[293,1247],[294,592],[294,642],[304,118],[304,713],[306,793],[309,519],[314,453],[319,528],[319,4232],[325,1717],[332,277],[335,269],[336,327],[336,561],[336,568],[336,4886],[336,5690],[340,4553],[345,271],[349,103],[351,504],[355,110],[359,97],[359,884],[362,2215],[384,114],[384,121],[384,1666],[390,118],[390,415],[396,95],[398,7308],[400,951],[411,617],[417,270],[417,1168],[418,358],[422,428],[426,5370],[426,7014],[442,1894],[450,2279],[460,411],[467,7367],[475,387],[482,314],[482,5810],[483,115],[497,4513],[497,4973],[509,4934],[513,4267],[550,506],[553,795],[560,290],[560,2144],[562,117],[567,382],[567,3366],[581,1445],[589,378],[591,1560],[593,304],[598,1053],[599,121],[606,3481],[613,316],[613,1090],[619,315],[631,7545],[637,1032],[645,5158],[648,1101],[659,99],[666,2329],[669,1618],[695,634],[697,750],[721,773],[724,121],[744,436],[781,115],[794,275],[800,1196],[833,621],[838,539],[838,755],[872,342],[883,373],[927,4636],[931,3467],[941,118],[953,719],[993,2919],[1040,6129],[1077,277],[1082,7063],[1090,270],[1096,3256],[1100,277],[1108,1610],[1125,259],[1125,446],[1125,773],[1169,110],[1181,766],[1212,320],[1212,957],[1216,6912],[1226,115],[1228,6387],[1235,2912],[1236,313],[1271,269],[1284,666],[1300,269],[1338,3130],[1345,762],[1378,682],[1404,576],[1406,1112],[1444,259],[1481,327],[1491,756],[1492,506],[1559,1502],[1589,627],[1621,2015],[1697,2275],[1720,288],[1746,619],[1770,277],[1785,430],[1888,1210],[1899,706],[1928,275],[1935,1215],[1938,736],[1957,6191],[1978,2011],[1999,330],[2029,373],[2033,756],[2079,269],[2115,120],[2115,382],[2129,530],[2149,3400],[2154,311],[2193,315],[2197,115],[2208,115],[2218,2595],[2225,270],[2225,277],[2336,7083],[2353,110],[2395,725],[2422,7370],[2428,6985],[2498,736],[2534,813],[2550,277],[2571,315],[2607,1708],[2616,112],[2671,599],[2687,283],[2802,494],[2802,5680],[2886,315],[2928,650],[3009,808],[3121,269],[3140,921],[3176,6575],[3183,2806],[3207,2585],[3230,283],[3453,277],[3613,1616],[3756,706],[3774,770],[3774,6717],[3863,793],[3887,1445],[3928,275],[3945,7146],[3953,2988],[4033,1268],[4081,793],[4118,2819],[4180,344],[4205,115],[4309,7182],[4310,756],[4313,837],[4410,523],[4492,2382],[4590,313],[4645,4152],[4680,121],[4692,269],[4825,885],[4847,7161],[5053,580],[5112,276],[5185,263],[5208,1143],[5427,533],[5628,3709],[5638,559],[5739,270],[5847,511],[5848,3249],[6023,3103],[6026,2592],[6049,116],[6060,8061],[6071,1106],[6075,3965],[6416,442],[6786,2458],[6876,589],[7002,722],[7088,1385],[7272,436],[7275,555],[7348,766],[7480,315],[7579,492],[7606,532],[7955,1105],[8075,4636],[65,68],[65,121],[65,1715],[70,2321],[74,1314],[77,101],[77,453],[80,349],[83,69],[97,559],[100,1107],[101,1867],[102,555],[103,2735],[105,685],[106,444],[108,487],[108,2003],[109,429],[110,288],[112,1129],[112,1702],[112,1825],[112,4136],[115,511],[115,4233],[116,474],[116,492],[119,574],[119,856],[195,179],[257,109],[258,578],[258,7212],[259,494],[263,560],[269,494],[269,5595],[271,291],[271,743],[272,801],[272,1092],[274,1063],[275,1267],[278,111],[278,701],[278,1872],[280,1615],[285,584],[289,108],[291,2136],[293,259],[294,2627],[295,78],[295,109],[301,98],[301,275],[306,445],[312,815],[314,349],[314,494],[317,2702],[320,500],[327,706],[335,356],[335,1012],[336,541],[341,823],[345,3564],[347,574],[358,1944],[358,4352],[359,342],[359,563],[359,7900],[366,374],[366,6359],[367,95],[369,97],[371,277],[376,288],[382,634],[398,2146],[400,651],[401,1915],[422,3807],[423,448],[423,1320],[426,708],[426,6870],[429,344],[449,277],[453,319],[460,1331],[464,350],[469,103],[478,328],[478,1877],[482,1027],[482,7590]],"special":{"<|endoftext|>":8191}}123version https://git-lfs.github.com/spec/v1oid sha256:fba50796bb2d677a4d9805ff3d57748ea293fccef7e3ecb80e810465218f16bbsize 14063080123"""Vrel: a small language model built from scratch."""
__version__ = "0.3.1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Command line: python -m vrel <command>"""
import argparseimport jsonimport mathimport shutilimport sysimport timefrom pathlib import Path
from . import __version__
ROOT = Path(__file__).resolve().parent.parentDATA = ROOT / "data"
BOOKS = {"data": DATA, "ckpt": ROOT / "checkpoints", "steps": 6000, "batch": 32, "lr": 6e-4, "warmup": 200, "eval_every": 250, "prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels", "trained_on": "public-domain books from Project Gutenberg", "model_version": "0.1.0"}STORIES = {"data": DATA / "stories", "ckpt": ROOT / "checkpoints" / "stories", "steps": 20000, "batch": 16, "lr": 8e-4, "warmup": 500, "eval_every": 500, "prompt": "Once upon a time", "dataset": "2.7 million short stories", "trained_on": "TinyStories: short, simple stories written by GPT-4 (CDLA-Sharing-1.0)", "model_version": "0.2.0"}# What each preset trains on and how, and which Vrel it makes. The model shapes themselves live in model.PRESETS.RUNS = { "small": BOOKS, # Quick tests save to their own folder so they never overwrite a real model. "tiny": {**BOOKS, "ckpt": ROOT / "checkpoints" / "tiny", "steps": 200, "eval_every": 50, "model_version": "0.1.0-tiny"}, "stories": STORIES, "stories-tiny": {**STORIES, "ckpt": ROOT / "checkpoints" / "stories-tiny", "steps": 200, "eval_every": 50, "model_version": "0.2.0-tiny"}, # Vrel 0.3: half the size of "stories", learning from the trained "stories" model as well as from the text. "mini": {**STORIES, "ckpt": ROOT / "checkpoints" / "mini", "teacher": ROOT / "checkpoints" / "stories" / "vrel.pt", "distill": 0.5, "model_version": "0.3.0"},}DEFAULT = "stories"
def cmd_prepare(a): from .data import HOST, MIRRORS, clean_all, fetch, read_book_ids
ids = read_book_ids(a.books) hosts = MIRRORS if a.mirror_only else (HOST,) + MIRRORS print(f"fetching {len(ids)} books from {' then '.join(hosts)} into {DATA / 'raw'} " "(already-downloaded books are skipped)") if not fetch(ids, DATA / "raw", delay=a.delay, hosts=hosts, timeout=a.timeout): sys.exit("download stopped early; run the same command again later (finished books are kept)") print("cleaning") clean_all(DATA / "raw", DATA / "clean")
def cmd_tokenizer(a): from .data import build_bins, tokenizer_sample from .tokenizer import Tokenizer
text = tokenizer_sample(DATA / "clean", a.sample_chars) print(f"training tokenizer on {len(text) / 1e6:.1f}M characters, vocab {a.vocab}") t0 = time.time() tok = Tokenizer.train(text, a.vocab, verbose=True) tok.save(DATA / "tokenizer.json") print(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") t0 = time.time() n_train, n_val = build_bins(DATA / "clean", tok, DATA, log=lambda s: None) chars = sum(p.stat().st_size for p in (DATA / "clean").glob("*.txt")) print(f"encoded in {time.time() - t0:.0f}s: {n_train:,} train + {n_val:,} val tokens " f"({chars / (n_train + n_val):.2f} bytes per token)")
def cmd_stories(a): from . import stories
folder = STORIES["data"] missing = [n for n, size in stories.FILES.values() if not (folder / n).exists() or (folder / n).stat().st_size != size] if missing: if not a.download: sys.exit(f"missing {', '.join(missing)} in {folder}. Run again with --download to fetch them " "(about 2.25 GB from huggingface.co).") stories.download(folder) stories.build(folder, vocab=a.vocab, sample_chars=a.sample_chars, workers=a.workers)
def cmd_bigram(a): from .bigram import bigram_loss from .data import load_bin from .tokenizer import Tokenizer
d = RUNS[a.preset]["data"] tok = Tokenizer.load(d / "tokenizer.json") loss = bigram_loss(load_bin(d / "train.bin"), load_bin(d / "val.bin"), tok.vocab_size) (d / "bigram.json").write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)})) print(json.dumps({"bigram_val_loss": round(loss, 4), "perplexity": round(math.exp(loss), 1)}))
def cmd_train(a): from .train import train
r = RUNS[a.preset] name = a.name or a.preset out_dir = r["ckpt"] if not a.name else ROOT / "checkpoints" / a.name teacher = None if a.teacher == "none" else (a.teacher or r.get("teacher")) if teacher and not Path(teacher).exists(): sys.exit(f"teacher checkpoint {teacher} not found. Train it first, or pass --teacher none.") summary = train(data_dir=r["data"], out_dir=out_dir, run_dir=ROOT / "runs" / name, preset=a.preset, steps=a.steps or r["steps"], batch_size=a.batch_size or r["batch"], lr=a.lr or r["lr"], min_lr=(a.lr or r["lr"]) / 10, warmup=r["warmup"], eval_every=a.eval_every or r["eval_every"], resume=a.resume, prompt=r["prompt"], about={"dataset": r["dataset"], "trained_on": r["trained_on"]}, teacher=teacher, distill=r.get("distill", 0.5) if a.distill is None else a.distill) print(json.dumps(summary, indent=2))
def _paths(a): r = RUNS[a.preset] return Path(a.checkpoint or r["ckpt"] / "vrel.pt"), Path(a.tokenizer or r["data"] / "tokenizer.json")
def cmd_generate(a): from .generate import Runner
ckpt, tok = _paths(a) r = Runner(ckpt, tok) sys.stdout.write(a.prompt) sys.stdout.flush()
def show(piece): sys.stdout.write(piece) sys.stdout.flush()
r.generate(a.prompt, a.max_tokens, a.temperature, a.top_k, a.seed, on_token=show) print()
def cmd_stats(a): import torch
ckpt, _ = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) params = sum(t.numel() for t in ck["model"].values() if t.dtype.is_floating_point) print(json.dumps({"config": ck["config"], "step": ck["step"], "params": params, "tokenizer": ck["tokenizer"], "summary": ck.get("extra", {})}, indent=2))
def export_dir(preset): """models/vrel-<the model's own version>, so exports of different models never overwrite each other.""" return ROOT / "models" / f"vrel-{RUNS[preset]['model_version']}"
def cmd_export(a): import torch
ckpt, tok = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) out = Path(a.out or export_dir(a.preset)) if out.exists(): shutil.rmtree(out) (out / "vrel").mkdir(parents=True) for src in (ROOT / "vrel").glob("*.py"): # self-contained: the code travels with the weights shutil.copy2(src, out / "vrel" / src.name) keep = {k: ck[k] for k in ("config", "step", "val_loss", "tokenizer", "extra")} if a.format == "int8": from .quant import quantize
keep["model_int8"] = quantize(ck["model"]) else: keep["model"] = ck["model"] torch.save(keep, out / "vrel.pt") shutil.copy2(tok, out / "tokenizer.json") extra = ck.get("extra", {}) manifest = { "name": "Vrel", "version": RUNS[a.preset]["model_version"], # the model's version, not this code's "kind": "text-generator", "entry": "vrel.generate:load", "weights": "vrel.pt", "tokenizer": "tokenizer.json", "params": extra.get("params"), "context": ck["config"]["context"], "val_loss": round(extra.get("val_loss", ck["val_loss"]), 4), "trained_on": extra.get("trained_on", RUNS[a.preset]["trained_on"]), } (out / "model.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") size = sum(p.stat().st_size for p in out.rglob("*") if p.is_file()) print(f"exported to {out} ({size / 1e6:.1f} MB)")
def cmd_watch(a): from .watch import serve
r = RUNS[a.preset] serve(ROOT / "runs" / a.preset, r["ckpt"], r["data"], port=a.port, steps=a.steps or r["steps"])
def main(argv=None): p = argparse.ArgumentParser(prog="vrel", description="Vrel: a small language model built from scratch.") p.add_argument("--version", action="version", version=f"vrel {__version__}") sub = p.add_subparsers(dest="cmd", required=True) presets = list(RUNS)
s = sub.add_parser("stories", help="build the TinyStories training data (tokenizer and token files)") s.add_argument("--download", action="store_true", help="download missing files (about 2.25 GB)") s.add_argument("--vocab", type=int, default=4096, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=20_000_000, help="characters to learn the tokenizer from") s.add_argument("--workers", type=int, default=None, help="encoding processes (default: half your CPU, max 6)") s.set_defaults(fn=cmd_stories)
s = sub.add_parser("prepare", help="download and clean the 0.1 training books") s.add_argument("--books", default=DATA / "books.txt", help="file with one Gutenberg book ID per line") s.add_argument("--delay", type=float, default=2.0, help="seconds to wait between downloads") s.add_argument("--timeout", type=float, default=60.0, help="seconds to wait on a stalled download") s.add_argument("--mirror-only", action="store_true", help="skip gutenberg.org and use only its official mirrors " "(by default the mirrors are fallbacks)") s.set_defaults(fn=cmd_prepare)
s = sub.add_parser("tokenizer", help="train the tokenizer and encode the 0.1 books into token files") s.add_argument("--vocab", type=int, default=8192, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=5_000_000, help="characters of text to learn merges from") s.set_defaults(fn=cmd_tokenizer)
s = sub.add_parser("bigram", help="score the bigram baseline on the validation set") s.add_argument("--preset", choices=presets, default=DEFAULT, help="which dataset") s.set_defaults(fn=cmd_bigram)
s = sub.add_parser("train", help="train Vrel") s.add_argument("--preset", choices=presets, default=DEFAULT, help="stories (Vrel 0.2, default), mini (Vrel 0.3: half the size, learns from 0.2), small (Vrel 0.1 books), " "or a -tiny version for a quick test") s.add_argument("--steps", type=int, default=None, help="training rounds (default depends on the preset)") s.add_argument("--batch-size", type=int, default=None) s.add_argument("--lr", type=float, default=None, help="peak learning rate") s.add_argument("--eval-every", type=int, default=None) s.add_argument("--resume", action="store_true", help="continue from the preset's last.pt") s.add_argument("--teacher", default=None, help="checkpoint to learn from as well as the text (mini learns from Vrel 0.2); 'none' to skip") s.add_argument("--distill", type=float, default=None, help="share of the loss from the teacher, 0 to 1 (default 0.5)") s.add_argument("--name", default=None, help="save under runs/NAME and checkpoints/NAME instead of the preset's folders") s.set_defaults(fn=cmd_train)
s = sub.add_parser("watch", help="live training dashboard in your browser") s.add_argument("--port", type=int, default=8777) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which run to watch") s.add_argument("--steps", type=int, default=None, help="total rounds, if the run did not record it") s.set_defaults(fn=cmd_watch)
for name, fn, hlp in (("generate", cmd_generate, "write text from a prompt"), ("stats", cmd_stats, "show what is inside a checkpoint"), ("export", cmd_export, "package the model so other apps can load it")): s = sub.add_parser(name, help=hlp) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which trained model") s.add_argument("--checkpoint", default=None, help="checkpoint file (default: the preset's vrel.pt)") s.add_argument("--tokenizer", default=None, help="tokenizer file (default: the preset's)") if name == "generate": s.add_argument("--prompt", default="", help="text for Vrel to continue") s.add_argument("--max-tokens", type=int, default=200) s.add_argument("--temperature", type=float, default=0.8, help="0 = always pick the likeliest token") s.add_argument("--top-k", type=int, default=50, help="only sample from the k likeliest tokens") s.add_argument("--seed", type=int, default=None, help="same seed + prompt = same text") if name == "export": s.add_argument("--out", default=None, help="output folder (default models/vrel-<model version>, such as models/vrel-0.3.0)") s.add_argument("--format", choices=("int8", "float32"), default="int8", help="int8 (default) is a quarter of the size with the same quality") s.set_defaults(fn=fn)
a = p.parse_args(argv) a.fn(a)
if __name__ == "__main__": main()12345678910111213141516171819202122232425"""Bigram baseline: predicts each token only from the one before it, by counting.
This is the simplest possible language model. Vrel has to beat it by a wide
margin for its attention layers to be worth anything.
"""
import numpy as np
def bigram_loss(train, val, vocab_size, k=0.1, chunk=50_000_000):
"""Mean negative log-probability on `val`, using add-k smoothed bigram counts from `train`."""
V = vocab_size
counts = np.zeros(V * V, dtype=np.int64)
# Count in slices so even hundreds of millions of tokens fit in memory. Each slice
# overlaps the next by one token so the pair across the boundary is counted once.
for start in range(0, max(1, len(train) - 1), chunk):
a = np.asarray(train[start:start + chunk + 1], dtype=np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V)
counts = counts.astype(np.float32).reshape(V, V)
val = np.asarray(val, dtype=np.int64)
counts += k
row_sums = counts.sum(axis=1)
a, b = val[:-1], val[1:]
logp = np.log(counts[a, b]) - np.log(row_sums[a])
return float(-logp.mean())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Training data: fetch public-domain books, clean them, and turn them into token files."""
import http.client
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
import numpy as np
from .tokenizer import EOT
CACHE_PATH = "/cache/epub/{id}/pg{id}.txt"
# Where each server keeps a book's plain text. Paths are tried in order.
SOURCES = {
"www.gutenberg.org": [CACHE_PATH],
# Official Project Gutenberg mirror, classic layout: book 1342 lives at /1/3/4/1342/1342-0.txt
"mirrors.xmission.com": ["/gutenberg/{dirs}/{id}/{id}-0.txt", "/gutenberg/{dirs}/{id}/{id}.txt"],
# Project Gutenberg Literary Archive Foundation, same layout as the main site
"aleph.pglaf.org": [CACHE_PATH],
}
HOST = "www.gutenberg.org"
MIRRORS = ("mirrors.xmission.com", "aleph.pglaf.org")
USER_AGENT = "vrel-data-fetch/0.1"
def book_urls(host, book_id):
s = str(book_id)
dirs = "0" if len(s) == 1 else "/".join(s[:-1])
return [f"https://{host}" + p.format(id=book_id, dirs=dirs) for p in SOURCES.get(host, [CACHE_PATH])]
# The marker can wrap onto a second line ("...SHERLOCK" / "HOLMES ***"), so match up to its closing ***.
START_RE = re.compile(r"^\*\*\* ?START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^*]{0,300}\*\*\*", re.M | re.I)
END_RE = re.compile(r"^\*\*\* ?END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK.*$", re.M | re.I)
TITLE_RE = re.compile(r"^Title:\s*(.+)$", re.M)
def read_book_ids(path):
"""Parse a list file: one book ID per line, '#' starts a comment."""
ids = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
line = line.split("#", 1)[0].strip()
if line:
ids.append(int(line))
return ids
def _download(url, timeout=60, attempts=5, pause=5.0, opener=urllib.request.urlopen, sleep=time.sleep):
"""Fetch `url`. If the connection drops or stalls partway, resume from the last
byte received (HTTP Range) instead of starting over, up to `attempts` tries.
Errors the server answers with (like 503 or 404) are not retried."""
data = b""
total = None
for attempt in range(1, attempts + 1):
headers = {"User-Agent": USER_AGENT}
if data:
headers["Range"] = f"bytes={len(data)}-"
try:
with opener(urllib.request.Request(url, headers=headers), timeout=timeout) as resp:
if data and resp.status != 206: # server ignored the range: start over
data = b""
if total is None and resp.headers.get("Content-Length"):
total = len(data) + int(resp.headers["Content-Length"])
while True:
chunk = resp.read(1 << 16)
if not chunk:
break
data += chunk
if total is None or len(data) >= total:
break
raise http.client.IncompleteRead(data, total - len(data))
except urllib.error.HTTPError:
raise
except (http.client.HTTPException, OSError) as e: # dropped, reset or timed out
if attempt == attempts:
raise
sleep(pause)
if not START_RE.search(data[:20000].decode("utf-8", errors="replace")):
raise ValueError("response is not a Project Gutenberg text")
return data
def fetch(ids, raw_dir, delay=2.0, hosts=(HOST,) + MIRRORS, max_failures_in_a_row=3, log=print,
download=_download, timeout=60):
"""Download each book once; files already on disk are never fetched again.
Each book is tried on `hosts` in order, so the main site is preferred and the
mirrors are fallbacks. Waits `delay` seconds after every request, success or
not. A host that fails `max_failures_in_a_row` times is dropped for the rest
of the run so no server is hammered (a plain "not found" does not count).
Returns False if every host was dropped.
"""
raw_dir = Path(raw_dir)
raw_dir.mkdir(parents=True, exist_ok=True)
live = list(hosts)
failures = {h: 0 for h in hosts}
for n, book_id in enumerate(ids, 1):
dest = raw_dir / f"{book_id}.txt"
if dest.exists():
continue
body = None
for host in list(live):
for url in book_urls(host, book_id):
try:
body = download(url, timeout=timeout)
break
except urllib.error.HTTPError as e:
if e.code == 404:
continue # this server keeps it under another name; try the next path
err = e
except Exception as e:
err = e
finally:
time.sleep(delay)
failures[host] += 1
log(f" [{n}/{len(ids)}] book {book_id} from {host}: FAILED ({err})")
if failures[host] >= max_failures_in_a_row:
live.remove(host)
log(f" {host}: {failures[host]} failures in a row, not asking it again this run")
break
if body is not None:
failures[host] = 0
dest.write_bytes(body)
log(f" [{n}/{len(ids)}] book {book_id} from {host}: {len(body) / 1e6:.2f} MB")
break
if body is None and live:
log(f" [{n}/{len(ids)}] book {book_id}: not downloaded this run")
if not live:
return False
return True
def strip_gutenberg(text):
"""Keep only the book itself: drop the Project Gutenberg header, footer and license."""
text = text.replace("\r\n", "\n").replace("\r", "\n").lstrip("")
start = START_RE.search(text)
end = END_RE.search(text)
body = text[start.end() if start else 0 : end.start() if end else len(text)]
return body.strip() + "\n"
def book_title(text):
m = TITLE_RE.search(text)
return m.group(1).strip() if m else "(unknown title)"
def clean_all(raw_dir, clean_dir, log=print):
raw_dir, clean_dir = Path(raw_dir), Path(clean_dir)
clean_dir.mkdir(parents=True, exist_ok=True)
titles = {}
for src in sorted(raw_dir.glob("*.txt"), key=lambda p: int(p.stem)):
raw = src.read_bytes().decode("utf-8", errors="replace")
body = strip_gutenberg(raw).replace(EOT, "")
(clean_dir / src.name).write_text(body, encoding="utf-8")
titles[int(src.stem)] = book_title(raw)
log(f" {src.stem}: {book_title(raw)} ({len(body) / 1e6:.2f} MB)")
return titles
def clean_books(clean_dir):
return sorted(Path(clean_dir).glob("*.txt"), key=lambda p: int(p.stem))
def tokenizer_sample(clean_dir, max_chars=5_000_000):
"""An even slice from every book, so the tokenizer learns from all authors."""
books = clean_books(clean_dir)
per_book = max_chars // max(1, len(books))
parts = []
for p in books:
text = p.read_text(encoding="utf-8")
mid = max(0, len(text) // 2 - per_book // 2)
parts.append(text[mid : mid + per_book])
return "\n".join(parts)
def build_bins(clean_dir, tok, out_dir, val_frac=0.05, log=print):
"""Encode every book. The last `val_frac` of each book becomes validation data."""
out_dir = Path(out_dir)
train_ids, val_ids = [], []
for p in clean_books(clean_dir):
text = p.read_text(encoding="utf-8")
cut = text.rfind("\n", 0, int(len(text) * (1 - val_frac)))
cut = cut if cut > 0 else int(len(text) * (1 - val_frac))
train_ids += tok.encode_ordinary(text[:cut]) + [tok.eot_id]
val_ids += tok.encode_ordinary(text[cut:]) + [tok.eot_id]
log(f" encoded {p.stem}: {len(train_ids):,} train / {len(val_ids):,} val tokens so far")
np.array(train_ids, dtype=np.uint16).tofile(out_dir / "train.bin")
np.array(val_ids, dtype=np.uint16).tofile(out_dir / "val.bin")
return len(train_ids), len(val_ids)
def load_bin(path):
return np.memmap(path, dtype=np.uint16, mode="r")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Make Vrel write: load a checkpoint and sample text one token at a time."""
import codecs
import json
import os
from pathlib import Path
import torch
from .model import Config, Vrel, softmax
from .quant import dequantize
from .tokenizer import Tokenizer
def pick_device(device=None):
if device:
return device
return "cuda" if torch.cuda.is_available() else "cpu"
def load_model(ckpt_path, device=None):
device = pick_device(device)
ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
model = Vrel(Config(**ckpt["config"])).to(device)
# Exports store 8-bit weights ("model_int8"); training checkpoints store float32 ("model").
model.load_state_dict(dequantize(ckpt["model_int8"]) if "model_int8" in ckpt else ckpt["model"])
model.eval()
return model, ckpt
@torch.no_grad()
def sample(model, tok, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
"""Continue `prompt`. Calls on_token(text) as each piece is ready; returns the new text."""
device = next(model.parameters()).device
was_training = model.training
model.eval()
ids = [tok.eot_id] + tok.encode(prompt) # start a new story, as in training
idx = torch.tensor([ids], dtype=torch.long, device=device)
gen = torch.Generator(device=device)
gen.manual_seed(seed if seed is not None else int.from_bytes(os.urandom(8), "little") >> 1)
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
out = []
def emit(piece):
if piece:
out.append(piece)
if on_token is not None:
on_token(piece)
ctx = model.cfg.context
cache, pos = None, 0
def prefill(window):
"""Fill a fresh KV cache with `window` and return the logits for the next token."""
nonlocal cache, pos
cache = model.new_cache()
pos = window.size(1)
return model(window, cache=cache, offset=0)[0][:, -1, :]
if model.v2:
next_logits = prefill(idx[:, -ctx:])
for _ in range(max_tokens):
if should_stop is not None and should_stop():
break
if model.v2:
logits = next_logits.float()
else: # 0.1 architecture: no cache, re-read the whole window every step
logits = model(idx[:, -ctx:])[0][:, -1, :].float()
if temperature <= 0:
nxt = logits.argmax(dim=-1, keepdim=True)
else:
logits = logits / temperature
if top_k and top_k < logits.size(-1):
kth = torch.topk(logits, top_k, dim=-1).values[:, -1:]
logits = logits.masked_fill(logits < kth, float("-inf"))
nxt = torch.multinomial(softmax(logits, dim=-1), 1, generator=gen)
t = int(nxt)
if t == tok.eot_id:
break
idx = torch.cat([idx, nxt], dim=1)
emit(decoder.decode(tok.token_bytes(t)))
if model.v2:
if pos + 1 > ctx: # window full: restart the cache from the most recent half
next_logits = prefill(idx[:, -(ctx // 2):])
else: # only the new token goes through the model; earlier ones come from the cache
next_logits = model(nxt, cache=cache, offset=pos)[0][:, -1, :]
pos += 1
emit(decoder.decode(b"", final=True))
model.train(was_training)
return "".join(out)
class Runner:
"""A loaded model plus its tokenizer, ready to generate."""
def __init__(self, ckpt_path, tokenizer_path, device=None):
self.device = pick_device(device)
self.model, self.ckpt = load_model(ckpt_path, self.device)
self.tok = Tokenizer.load(tokenizer_path)
if self.ckpt.get("tokenizer") and self.ckpt["tokenizer"] != self.tok.fingerprint():
raise ValueError("this tokenizer does not match the one the model was trained with")
def generate(self, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
return sample(self.model, self.tok, prompt, max_tokens, temperature, top_k, seed, on_token, should_stop)
def load(path, device=None):
"""Entry point for the shared model contract: `path` is an exported model folder."""
path = Path(path)
manifest = json.loads((path / "model.json").read_text(encoding="utf-8"))
return Runner(path / manifest["weights"], path / manifest["tokenizer"], device=device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366"""The Vrel transformer, written from scratch.
PyTorch supplies tensors, automatic gradients and the GPU. Every layer here
(linear, embedding, norms, attention, rotary positions, activations, dropout,
loss) is our own code built from basic tensor math.
Two architectures:
- "gpt2" (Vrel 0.1): LayerNorm, learned positions, GELU MLP, biases.
- "v2" (Vrel 0.2+): RMSNorm, rotary positions (RoPE), SwiGLU MLP, no biases,
memory-efficient attention for training and a KV cache for fast generation.
"""
import math
from dataclasses import asdict, dataclass, replace
import torch
from torch import nn
@dataclass
class Config:
vocab_size: int = 8192
context: int = 256 # how many tokens the model can see at once
n_layer: int = 6
n_head: int = 6
d_model: int = 384
dropout: float = 0.1
arch: str = "gpt2" # checkpoints saved before 0.2 have no arch field and load as gpt2
PRESETS = {
"small": Config(),
"tiny": Config(context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0),
"stories": Config(vocab_size=4096, context=512, n_layer=8, n_head=8, d_model=512, dropout=0.0, arch="v2"),
"stories-tiny": Config(vocab_size=4096, context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0, arch="v2"),
# Half the size of "stories" (14.0M parameters), meant to learn from it as a teacher.
"mini": Config(vocab_size=4096, context=512, n_layer=7, n_head=6, d_model=384, dropout=0.0, arch="v2"),
}
def make_config(preset="small", **overrides):
return replace(PRESETS[preset], **overrides)
# ------------------------------------------------------------------ basic math
def softmax(x, dim=-1):
x = x - x.amax(dim=dim, keepdim=True)
e = x.exp()
return e / e.sum(dim=dim, keepdim=True)
def log_softmax(x, dim=-1):
shifted = x - x.amax(dim=dim, keepdim=True)
return shifted - shifted.exp().sum(dim=dim, keepdim=True).log()
def cross_entropy(logits, targets):
"""Average negative log-probability of the correct next token."""
logp = log_softmax(logits.float(), dim=-1)
return -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
def distill_loss(logits, teacher_logits, targets, weight):
"""Learn from the real next token and from a teacher model's guesses at the same time.
The teacher gives a full spread of likely next tokens, not just the one that happened, which is
much richer to learn from. `weight` is the share of the loss that comes from the teacher (0 to 1).
The teacher part is the KL divergence: how far our spread is from the teacher's.
"""
logp = log_softmax(logits.float(), dim=-1)
hard = -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
if weight <= 0:
return hard
t_logp = log_softmax(teacher_logits.float(), dim=-1)
kl = (t_logp.exp() * (t_logp - logp)).sum(dim=-1).mean()
return (1 - weight) * hard + weight * kl
def gelu(x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x)))
def silu(x):
return x / (1.0 + torch.exp(-x))
def dropout(x, p, training):
if not training or p == 0.0:
return x
keep = (torch.rand_like(x, dtype=torch.float32) >= p).to(x.dtype)
return x * keep / (1.0 - p)
def causal_mask(t_q, t_k, device, offset=0):
"""True where a query may NOT look: keys later than the query's own position."""
q_pos = torch.arange(t_q, device=device)[:, None] + offset
k_pos = torch.arange(t_k, device=device)[None, :]
return k_pos > q_pos
# ------------------------------------------------------------------- attention
def _acc_dtype(t):
"""Accumulate in at least 32-bit floats (64-bit stays 64-bit)."""
return torch.promote_types(t.dtype, torch.float32)
class _CausalAttention(torch.autograd.Function):
"""softmax(q k^T * scale, causal) v, without keeping the T x T grid for backward.
Forward saves only q, k, v, the output and one log-sum-exp per row. Backward
recomputes the attention weights from those, one layer at a time, so memory
for the score grid is needed for a single layer instead of every layer at once.
The gradient formulas are the standard ones for softmax attention.
"""
@staticmethod
@torch.amp.custom_fwd(device_type="cuda")
def forward(ctx, q, k, v, scale):
T = q.size(-2)
acc = _acc_dtype(q)
mask = causal_mask(T, T, q.device)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(mask, float("-inf"))
m = s.amax(dim=-1, keepdim=True)
p = (s - m).exp_()
denom = p.sum(dim=-1, keepdim=True)
lse = m + denom.log()
p = (p / denom).to(v.dtype)
y = p @ v
ctx.save_for_backward(q, k, v, y, lse)
ctx.scale = scale
return y
@staticmethod
@torch.amp.custom_bwd(device_type="cuda")
def backward(ctx, dy):
q, k, v, y, lse = ctx.saved_tensors
scale = ctx.scale
T = q.size(-2)
acc = _acc_dtype(q)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(causal_mask(T, T, q.device), float("-inf"))
p = (s - lse).exp_() # the forward's attention weights, recomputed
del s
dy = dy.to(v.dtype)
dv = p.to(v.dtype).transpose(-2, -1) @ dy
dp = (dy @ v.transpose(-2, -1)).to(acc)
row = (dy.to(acc) * y.to(acc)).sum(dim=-1, keepdim=True)
ds = (p * (dp - row) * scale).to(q.dtype)
del p, dp
dq = ds @ k
dk = ds.transpose(-2, -1) @ q
return dq, dk, dv, None
def attention(q, k, v):
return _CausalAttention.apply(q, k, v, 1.0 / math.sqrt(q.size(-1)))
def rope_tables(context, head_dim, device=None, base=10000.0):
"""cos and sin tables for rotary position encoding, shape (context, head_dim / 2)."""
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
angles = torch.outer(torch.arange(context, device=device, dtype=torch.float32), inv)
return angles.cos(), angles.sin()
def apply_rope(x, cos, sin):
"""Rotate each (first-half, second-half) pair of features by an angle that grows with position.
x: (B, H, T, hd); cos, sin: (T, hd/2). Dot products between rotated queries and keys
then depend only on how far apart two tokens are, not on where they are.
"""
half = x.size(-1) // 2
x32 = x.float()
x1, x2 = x32[..., :half], x32[..., half:]
out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
return out.to(x.dtype)
# ---------------------------------------------------------------------- layers
class Linear(nn.Module):
def __init__(self, n_in, n_out, bias=True, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n_out, n_in) * std)
self.bias = nn.Parameter(torch.zeros(n_out)) if bias else None
def forward(self, x):
y = x @ self.weight.t()
return y if self.bias is None else y + self.bias
class Embedding(nn.Module):
def __init__(self, n, d, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n, d) * std)
def forward(self, idx):
return self.weight[idx]
class LayerNorm(nn.Module):
def __init__(self, d, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.bias = nn.Parameter(torch.zeros(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
mean = x32.mean(dim=-1, keepdim=True)
var = ((x32 - mean) ** 2).mean(dim=-1, keepdim=True)
y = (x32 - mean) / torch.sqrt(var + self.eps)
return y * self.weight + self.bias
class RMSNorm(nn.Module):
"""Scale each vector to unit root-mean-square, then by a learned gain. No mean, no bias."""
def __init__(self, d, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
y = x32 * torch.rsqrt((x32 * x32).mean(dim=-1, keepdim=True) + self.eps)
return (y * self.weight).to(x.dtype) if x.dtype != torch.float32 else y * self.weight
class CausalSelfAttention(nn.Module):
"""Each position looks back at itself and earlier positions, never ahead."""
def __init__(self, cfg):
super().__init__()
assert cfg.d_model % cfg.n_head == 0
self.v2 = cfg.arch == "v2"
self.n_head = cfg.n_head
bias = not self.v2
self.qkv = Linear(cfg.d_model, 3 * cfg.d_model, bias=bias)
self.proj = Linear(cfg.d_model, cfg.d_model, bias=bias, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
if not self.v2:
mask = torch.tril(torch.ones(cfg.context, cfg.context, dtype=torch.bool))
self.register_buffer("mask", mask, persistent=False)
def forward(self, x, rope=None, cache=None, offset=0):
B, T, C = x.shape
H = self.n_head
hd = C // H
q, k, v = self.qkv(x).split(C, dim=2)
q = q.view(B, T, H, hd).transpose(1, 2) # (B, H, T, hd)
k = k.view(B, T, H, hd).transpose(1, 2)
v = v.view(B, T, H, hd).transpose(1, 2)
if not self.v2:
scores = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(hd))
scores = scores.float().masked_fill(~self.mask[:T, :T], float("-inf"))
att = dropout(softmax(scores, dim=-1), self.p, self.training)
y = att.to(v.dtype) @ v
else:
cos, sin = rope
q = apply_rope(q, cos[offset:offset + T], sin[offset:offset + T])
k = apply_rope(k, cos[offset:offset + T], sin[offset:offset + T])
if cache is None:
y = attention(q, k, v)
else: # generation: attend over everything cached so far plus the new positions
if cache.get("k") is not None:
k = torch.cat([cache["k"], k], dim=2)
v = torch.cat([cache["v"], v], dim=2)
cache["k"], cache["v"] = k, v
s = (q @ k.transpose(-2, -1)).float() * (1.0 / math.sqrt(hd))
s = s.masked_fill(causal_mask(T, k.size(2), x.device, offset), float("-inf"))
y = softmax(s, dim=-1).to(v.dtype) @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return dropout(self.proj(y), self.p, self.training)
class MLP(nn.Module):
def __init__(self, cfg):
super().__init__()
self.fc = Linear(cfg.d_model, 4 * cfg.d_model)
self.proj = Linear(4 * cfg.d_model, cfg.d_model, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.proj(gelu(self.fc(x))), self.p, self.training)
class SwiGLU(nn.Module):
"""A gated MLP: one projection decides how much of another to let through."""
def __init__(self, cfg):
super().__init__()
hidden = 64 * math.ceil(8 * cfg.d_model / 3 / 64) # same parameter count as a 4x GELU MLP
self.gate = Linear(cfg.d_model, hidden, bias=False)
self.up = Linear(cfg.d_model, hidden, bias=False)
self.down = Linear(hidden, cfg.d_model, bias=False, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.down(silu(self.gate(x)) * self.up(x)), self.p, self.training)
class Block(nn.Module):
def __init__(self, cfg):
super().__init__()
v2 = cfg.arch == "v2"
self.ln1 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.attn = CausalSelfAttention(cfg)
self.ln2 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.mlp = SwiGLU(cfg) if v2 else MLP(cfg)
def forward(self, x, rope=None, cache=None, offset=0):
x = x + self.attn(self.ln1(x), rope, cache, offset)
x = x + self.mlp(self.ln2(x))
return x
class Vrel(nn.Module):
def __init__(self, cfg):
super().__init__()
if cfg.arch not in ("gpt2", "v2"):
raise ValueError(f"unknown architecture {cfg.arch!r}")
self.cfg = cfg
self.v2 = cfg.arch == "v2"
self.tok = Embedding(cfg.vocab_size, cfg.d_model)
if self.v2:
cos, sin = rope_tables(cfg.context, cfg.d_model // cfg.n_head)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
else:
self.pos = Embedding(cfg.context, cfg.d_model)
self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
self.ln_f = RMSNorm(cfg.d_model) if self.v2 else LayerNorm(cfg.d_model)
def forward(self, idx, targets=None, cache=None, offset=0):
"""cache: None for training, or a list (one dict per layer) for step-by-step generation.
offset: how many positions are already in the cache."""
B, T = idx.shape
if offset + T > self.cfg.context:
raise ValueError(f"sequence of {offset + T} tokens is longer than the context of {self.cfg.context}")
if cache is not None and not self.v2:
raise ValueError("the KV cache needs the v2 architecture")
x = self.tok(idx)
rope = None
if self.v2:
rope = (self.rope_cos, self.rope_sin)
else:
x = x + self.pos(torch.arange(T, device=idx.device))
x = dropout(x, self.cfg.dropout, self.training)
for i, block in enumerate(self.blocks):
x = block(x, rope, None if cache is None else cache[i], offset)
x = self.ln_f(x)
logits = x @ self.tok.weight.t() # output layer shares weights with the token embedding
loss = None
if targets is not None:
loss = cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
return logits, loss
def new_cache(self):
return [{} for _ in range(self.cfg.n_layer)]
def num_params(self):
return sum(p.numel() for p in self.parameters())
def config_dict(self):
return asdict(self.cfg)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Training helpers written from scratch: AdamW, gradient clipping, LR schedule."""
import math
import torch
class AdamW: """Adam with decoupled weight decay.
groups: list of {"params": [...], "weight_decay": float} """
def __init__(self, groups, lr=6e-4, betas=(0.9, 0.95), eps=1e-8): self.groups = [{"params": list(g["params"]), "weight_decay": g.get("weight_decay", 0.0)} for g in groups] self.lr = lr self.betas = betas self.eps = eps self.t = 0 self.m = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups] self.v = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups]
def zero_grad(self): for g in self.groups: for p in g["params"]: p.grad = None
@torch.no_grad() def step(self): self.t += 1 b1, b2 = self.betas bc1 = 1.0 - b1 ** self.t bc2 = 1.0 - b2 ** self.t step_size = self.lr / bc1 for gi, g in enumerate(self.groups): wd = g["weight_decay"] for pi, p in enumerate(g["params"]): if p.grad is None: continue grad = p.grad m = self.m[gi][pi] v = self.v[gi][pi] if wd: p.mul_(1.0 - self.lr * wd) m.mul_(b1).add_(grad, alpha=1.0 - b1) v.mul_(b2).addcmul_(grad, grad, value=1.0 - b2) denom = (v.sqrt() / math.sqrt(bc2)).add_(self.eps) p.addcdiv_(m, denom, value=-step_size)
def state_dict(self): return {"t": self.t, "lr": self.lr, "m": self.m, "v": self.v}
def load_state_dict(self, state): self.t = state["t"] self.lr = state["lr"] for gi in range(len(self.groups)): for pi in range(len(self.groups[gi]["params"])): self.m[gi][pi].copy_(state["m"][gi][pi]) self.v[gi][pi].copy_(state["v"][gi][pi])
def param_groups(model, weight_decay): """Matrices get weight decay; biases and layer-norm gains do not.""" decay = [p for p in model.parameters() if p.dim() >= 2] no_decay = [p for p in model.parameters() if p.dim() < 2] return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]
@torch.no_grad()def clip_grad_norm(params, max_norm): """Scale all gradients down together if their combined length exceeds max_norm.""" grads = [p.grad for p in params if p.grad is not None] total = torch.sqrt(sum((g.float() ** 2).sum() for g in grads)) coef = torch.clamp(max_norm / (total + 1e-6), max=1.0) for g in grads: g.mul_(coef.to(g.dtype)) return total
def lr_at(step, max_lr, warmup, total, min_lr): """Linear warmup, then cosine decay from max_lr down to min_lr.""" if step < warmup: return max_lr * (step + 1) / warmup progress = min(1.0, (step - warmup) / max(1, total - warmup)) return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * progress))12345678910111213141516171819202122232425"""Store weights as 8-bit integers: a quarter of the file size, measured to change nothing you can notice.
Every row of a weight matrix gets its own scale: the row's largest absolute value maps to 127, and eachweight is rounded to the nearest of the 255 steps in between. Vectors (norm weights) are tiny, so theystay in 16-bit. When the model loads, everything is turned back into ordinary float32 numbers."""
import torch
def quantize(state): out = {} for name, t in state.items(): t = t.detach().float().cpu() if t.dim() < 2: out[name] = {"w": t.half()} continue # One 32-bit scale per row: exact enough, and so few that they cost almost nothing. scale = t.abs().amax(dim=1, keepdim=True).clamp(min=1e-12) / 127 out[name] = {"q": torch.round(t / scale).clamp(-127, 127).to(torch.int8), "s": scale} return out
def dequantize(state): return {name: d["w"].float() if "w" in d else d["q"].float() * d["s"].float() for name, d in state.items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""The TinyStories dataset: download, clean, train the tokenizer, encode to token files.
TinyStories (roneneldan/TinyStories on Hugging Face, license CDLA-Sharing-1.0) is about2.7 million short, simple English stories written by GPT-4. Vrel only reads them: themodel and every weight in it are still trained from scratch here."""
import osimport timeimport urllib.requestfrom multiprocessing import Poolfrom pathlib import Path
import numpy as np
from .tokenizer import EOT, Tokenizer
BASE_URL = "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/"FILES = { "train": ("TinyStoriesV2-GPT4-train.txt", 2_227_753_162), "valid": ("TinyStoriesV2-GPT4-valid.txt", 22_502_601),}USER_AGENT = "vrel-data-fetch/0.2"
# Curly quotes become straight ones, so the model does not learn two spellings of every quote._TRANSLATE = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})_TRANSLATE.update({c: None for c in range(0x80, 0xA0)}) # stray control characters
def clean(text): return text.translate(_TRANSLATE).strip()
def download(folder, log=print): """Fetch the train and validation files, resuming partial downloads. Skips complete files.""" folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) for name, size in FILES.values(): dest = folder / name have = dest.stat().st_size if dest.exists() else 0 if have == size: continue req = urllib.request.Request(BASE_URL + name, headers={"User-Agent": USER_AGENT, "Range": f"bytes={have}-"}) log(f" downloading {name} ({size / 1e9:.2f} GB) ...") with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "ab" if have else "wb") as f: if have and resp.status != 206: f.truncate(0) # server ignored the resume request; start over while chunk := resp.read(1 << 20): f.write(chunk) if dest.stat().st_size != size: raise OSError(f"{name}: got {dest.stat().st_size:,} bytes, expected {size:,}; run again to resume")
def iter_stories(path, block=1 << 23): """Yield cleaned stories one at a time without reading the whole file into memory.""" buf = "" with open(path, encoding="utf-8", errors="replace") as f: while True: data = f.read(block) if not data: break buf += data parts = buf.split(EOT) buf = parts.pop() # the last piece may be cut off mid-story for p in parts: s = clean(p) if s: yield s s = clean(buf) if s: yield s
def tokenizer_sample(path, max_chars): out, n = [], 0 for s in iter_stories(path): out.append(s) n += len(s) + 1 if n >= max_chars: break return "\n".join(out)
_worker_tok = None
def _init_worker(tok_path): global _worker_tok _worker_tok = Tokenizer.load(tok_path)
def _encode_batch(stories): ids = [] for s in stories: ids.extend(_worker_tok.encode_ordinary(s)) ids.append(_worker_tok.eot_id) return np.array(ids, dtype=np.uint16)
def _batches(path, size=2000): batch = [] for s in iter_stories(path): batch.append(s) if len(batch) == size: yield batch batch = [] if batch: yield batch
def encode_file(src, dest, tok_path, workers, log=print): """Encode every story to `dest` as uint16 tokens, each story followed by the EOT token.""" t0 = time.time() n_tokens = n_stories = 0 tmp = Path(str(dest) + ".tmp") with Pool(workers, initializer=_init_worker, initargs=(str(tok_path),)) as pool, open(tmp, "wb") as f: for i, arr in enumerate(pool.imap(_encode_batch, _batches(src), chunksize=4)): arr.tofile(f) n_tokens += arr.size n_stories += 2000 if i % 100 == 0 and i: log(f" {Path(src).name}: ~{n_stories:,} stories, {n_tokens / 1e6:.0f}M tokens, {time.time() - t0:.0f}s") tmp.replace(dest) return n_tokens, time.time() - t0
def build(folder, vocab=4096, sample_chars=20_000_000, workers=None, log=print): folder = Path(folder) train_txt, valid_txt = (folder / FILES[k][0] for k in ("train", "valid")) workers = workers or max(1, min(6, (os.cpu_count() or 2) // 2)) text = tokenizer_sample(train_txt, sample_chars) log(f"training tokenizer on {len(text) / 1e6:.0f}M characters, vocab {vocab}") t0 = time.time() tok = Tokenizer.train(text, vocab) tok.save(folder / "tokenizer.json") log(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") results = {} for split, src in (("val", valid_txt), ("train", train_txt)): n, secs = encode_file(src, folder / f"{split}.bin", folder / "tokenizer.json", workers, log) chars = src.stat().st_size results[split] = n log(f"{split}: {n:,} tokens in {secs:.0f}s with {workers} workers ({chars / n:.2f} bytes per token)") return tok, results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Vrel's tokenizer: byte-level byte pair encoding (BPE), written from scratch.
Text is first split into rough word-like chunks, then each chunk is turned intoUTF-8 bytes (256 base tokens). Training repeatedly finds the most frequentadjacent pair of tokens and merges it into a new token, until the vocabularyreaches the requested size. Because everything starts from raw bytes, anystring can be encoded and decoded back exactly."""
import hashlibimport heapqimport jsonimport refrom collections import Counter, defaultdict
# Splits text into chunks that merges are not allowed to cross: contractions,# words (with one optional leading space), numbers, punctuation runs, whitespace.# Every character of the input lands in exactly one chunk.SPLIT = re.compile(r"'(?:[sdmt]|ll|ve|re)| ?[^\W\d_]+| ?\d+| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")
EOT = "<|endoftext|>" # marks the boundary between two separate documentsFORMAT = "vrel-bpe-1"
def _merge(ids, pair, new_id): """Replace every non-overlapping occurrence of `pair` in `ids` with `new_id`.""" out = [] i = 0 n = len(ids) a, b = pair while i < n: if i < n - 1 and ids[i] == a and ids[i + 1] == b: out.append(new_id) i += 2 else: out.append(ids[i]) i += 1 return out
class Tokenizer: def __init__(self, merges): self.merges = [tuple(m) for m in merges] self.ranks = {pair: i for i, pair in enumerate(self.merges)} self.vocab = [bytes([i]) for i in range(256)] for a, b in self.merges: self.vocab.append(self.vocab[a] + self.vocab[b]) self.eot_id = len(self.vocab) self.vocab_size = len(self.vocab) + 1 self._cache = {}
# ---------------------------------------------------------------- training @classmethod def train(cls, text, vocab_size=8192, verbose=False): """Learn merges from `text` until the vocabulary has `vocab_size` entries.""" n_merges = vocab_size - 256 - 1 # 256 bytes + merges + 1 special token if n_merges < 0: raise ValueError("vocab_size must be at least 257") counts = Counter(SPLIT.findall(text.replace(EOT, ""))) words = [list(w.encode("utf-8")) for w in counts] freqs = list(counts.values())
pair_counts = defaultdict(int) where = defaultdict(set) # pair -> indices of words that contain it for wi, w in enumerate(words): f = freqs[wi] for p in zip(w, w[1:]): pair_counts[p] += f where[p].add(wi)
# Max-heap of (count, pair). Entries go stale as counts change; a stale # entry is skipped when popped because a fresh one was pushed on change. heap = [(-c, p) for p, c in pair_counts.items()] heapq.heapify(heap)
merges = [] while len(merges) < n_merges and heap: negc, p = heapq.heappop(heap) c = pair_counts.get(p, 0) if c <= 0 or c != -negc: continue new_id = 256 + len(merges) merges.append(p) touched = set() for wi in where.pop(p, ()): w = words[wi] f = freqs[wi] for q in zip(w, w[1:]): pair_counts[q] -= f touched.add(q) nw = _merge(w, p, new_id) for q in zip(nw, nw[1:]): pair_counts[q] += f where[q].add(wi) touched.add(q) words[wi] = nw for q in touched: cq = pair_counts[q] if cq > 0: heapq.heappush(heap, (-cq, q)) else: pair_counts.pop(q, None) if verbose and len(merges) % 500 == 0: print(f" {len(merges)}/{n_merges} merges") return cls(merges)
# ---------------------------------------------------------------- encoding def _encode_chunk(self, chunk): ids = self._cache.get(chunk) if ids is not None: return ids ids = list(chunk.encode("utf-8")) ranks = self.ranks while len(ids) >= 2: best = None best_rank = None for p in zip(ids, ids[1:]): r = ranks.get(p) if r is not None and (best_rank is None or r < best_rank): best, best_rank = p, r if best is None: break ids = _merge(ids, best, 256 + best_rank) if len(self._cache) < 1_000_000: self._cache[chunk] = ids return ids
def encode_ordinary(self, text): """Encode text, treating any special-token text as ordinary characters.""" out = [] for chunk in SPLIT.findall(text): out.extend(self._encode_chunk(chunk)) return out
def encode(self, text): """Encode text; the literal string <|endoftext|> becomes the EOT token.""" out = [] for i, part in enumerate(text.split(EOT)): if i: out.append(self.eot_id) out.extend(self.encode_ordinary(part)) return out
# ---------------------------------------------------------------- decoding def token_bytes(self, i): return EOT.encode("utf-8") if i == self.eot_id else self.vocab[i]
def decode(self, ids): return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors="replace")
# ---------------------------------------------------------------- storage def to_json(self): return json.dumps( {"format": FORMAT, "merges": [list(m) for m in self.merges], "special": {EOT: self.eot_id}}, separators=(",", ":"), )
def save(self, path): with open(path, "w", encoding="utf-8") as f: f.write(self.to_json())
@classmethod def load(cls, path): with open(path, encoding="utf-8") as f: data = json.load(f) if data.get("format") != FORMAT: raise ValueError(f"{path} is not a {FORMAT} tokenizer file") return cls(data["merges"])
def fingerprint(self): """Short hash that identifies this exact set of merges.""" return hashlib.sha256(self.to_json().encode("utf-8")).hexdigest()[:16]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""The training loop: show Vrel real text, measure how wrong it was, nudge every weight."""
import csv
import json
import math
import time
from contextlib import nullcontext
from pathlib import Path
import numpy as np
import torch
from .data import load_bin
from .generate import load_model, sample
from .model import Vrel, distill_loss, make_config
from .optim import AdamW, clip_grad_norm, lr_at, param_groups
from .tokenizer import Tokenizer
def get_batch(data, batch_size, context, rng, device):
ix = rng.integers(0, len(data) - context - 1, size=batch_size)
x = np.stack([data[i : i + context] for i in ix]).astype(np.int64)
y = np.stack([data[i + 1 : i + 1 + context] for i in ix]).astype(np.int64)
x, y = torch.from_numpy(x), torch.from_numpy(y)
if device == "cuda":
return x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
return x.to(device), y.to(device)
def autocast(device):
return torch.autocast("cuda", dtype=torch.bfloat16) if device == "cuda" else nullcontext()
@torch.no_grad()
def full_loss(model, data, device, batch_size=64):
"""Loss over the whole of `data`, in back-to-back windows. Same answer every time."""
model.eval()
T = model.cfg.context
n = (len(data) - 1) // T
total, count = 0.0, 0
for start in range(0, n, batch_size):
rows = range(start, min(n, start + batch_size))
x = torch.from_numpy(np.stack([data[r * T : r * T + T] for r in rows]).astype(np.int64)).to(device)
y = torch.from_numpy(np.stack([data[r * T + 1 : r * T + T + 1] for r in rows]).astype(np.int64)).to(device)
with autocast(device):
_, loss = model(x, y)
total += loss.item() * len(rows)
count += len(rows)
model.train()
return total / max(1, count)
@torch.no_grad()
def quick_loss(model, data, device, batch_size, iters=20, seed=1234):
"""Loss on a fixed set of random windows, for progress logging during training."""
model.eval()
rng = np.random.default_rng(seed)
losses = []
for _ in range(iters):
x, y = get_batch(data, batch_size, model.cfg.context, rng, device)
with autocast(device):
_, loss = model(x, y)
losses.append(loss.item())
model.train()
return sum(losses) / len(losses)
def sample_text(model, tok, prompt, n=120, seed=0):
return sample(model, tok, prompt, max_tokens=n, temperature=0.8, top_k=50, seed=seed)
def save_checkpoint(path, model, opt, step, val_loss, tok, extra=None, with_optimizer=True):
state = {
"model": model.state_dict(),
"config": model.config_dict(),
"step": step,
"val_loss": val_loss,
"tokenizer": tok.fingerprint(),
"extra": extra or {},
}
if with_optimizer:
state["optimizer"] = opt.state_dict()
tmp = Path(str(path) + ".tmp")
torch.save(state, tmp)
tmp.replace(path)
def train(data_dir="data", out_dir="checkpoints", run_dir="runs", preset="small", steps=6000,
batch_size=32, lr=6e-4, min_lr=6e-5, warmup=200, weight_decay=0.1, grad_clip=1.0,
eval_every=250, seed=1337, resume=False, prompt="It was a dark and stormy night", about=None,
teacher=None, distill=0.5, log=print):
"""teacher: path to a trained checkpoint (same tokenizer) for this model to learn from as well as the
text. distill: the share of the loss that comes from the teacher's guesses."""
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_num_threads(4) # keep CPU use modest; the GPU does the heavy work
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
data_dir, out_dir, run_dir = Path(data_dir), Path(out_dir), Path(run_dir)
out_dir.mkdir(parents=True, exist_ok=True)
run_dir.mkdir(parents=True, exist_ok=True)
tok = Tokenizer.load(data_dir / "tokenizer.json")
train_data = load_bin(data_dir / "train.bin")
val_data = load_bin(data_dir / "val.bin")
cfg = make_config(preset, vocab_size=tok.vocab_size)
model = Vrel(cfg).to(device)
teach = None
if teacher:
teach, t_ck = load_model(teacher, device)
if t_ck.get("tokenizer") != tok.fingerprint():
raise ValueError("the teacher was trained with a different tokenizer")
if teach.cfg.context < cfg.context:
raise ValueError("the teacher's context is shorter than this model's")
for p in teach.parameters():
p.requires_grad_(False)
opt = AdamW(param_groups(model, weight_decay), lr=lr)
start_step, best_val = 0, math.inf
last_path, best_path = out_dir / "last.pt", out_dir / "vrel.pt"
if resume and last_path.exists():
ck = torch.load(last_path, map_location=device, weights_only=True)
model.load_state_dict(ck["model"])
opt.load_state_dict(ck["optimizer"])
start_step = ck["step"]
best_val = ck["extra"].get("best_val", math.inf)
rng = np.random.default_rng(seed + start_step)
log(f"resumed from step {start_step}")
about = dict(about or {})
if teach is not None:
about.update(teacher=str(Path(teacher).name), teacher_params=teach.num_params(), distill=distill)
run_info = {"preset": preset, "params": model.num_params(), "batch": batch_size, "context": cfg.context,
"steps": steps, "tokens_per_step": batch_size * cfg.context, "prompt": prompt, **about}
(run_dir / "run.json").write_text(json.dumps(run_info, indent=2), encoding="utf-8")
log(f"device {device}, {model.num_params():,} parameters, "
f"{len(train_data):,} train tokens, {len(val_data):,} val tokens")
log_path = run_dir / "log.csv"
new_log = not (resume and log_path.exists())
log_file = open(log_path, "w" if new_log else "a", newline="")
writer = csv.writer(log_file)
if new_log:
writer.writerow(["step", "lr", "train_loss", "val_loss", "tokens_per_s", "elapsed_s"])
if start_step == 0:
init_val = full_loss(model, val_data, device)
init_sample = sample_text(model, tok, prompt)
(run_dir / "sample_step0.txt").write_text(prompt + init_sample, encoding="utf-8")
log(f"random init: val loss {init_val:.4f} (perplexity {math.exp(init_val):,.0f})")
if device == "cuda":
torch.cuda.reset_peak_memory_stats()
t_start = time.time()
train_time = 0.0
tokens_done = 0
tokens_per_step = batch_size * cfg.context
model.train()
for step in range(start_step, steps + 1):
if step % eval_every == 0 or step == steps:
tr = quick_loss(model, train_data, device, batch_size)
va = quick_loss(model, val_data, device, batch_size)
tps = tokens_done / train_time if train_time else 0.0
writer.writerow([step, f"{opt.lr:.2e}", f"{tr:.4f}", f"{va:.4f}", f"{tps:.0f}", f"{time.time() - t_start:.1f}"])
log_file.flush()
log(f"step {step:5d} | train {tr:.4f} | val {va:.4f} | lr {opt.lr:.2e} | {tps:,.0f} tok/s")
if va < best_val:
best_val = va
save_checkpoint(best_path, model, opt, step, va, tok, with_optimizer=False)
save_checkpoint(last_path, model, opt, step, va, tok, extra={"best_val": best_val})
if step == steps:
break
opt.lr = lr_at(step, lr, warmup, steps, min_lr)
x, y = get_batch(train_data, batch_size, cfg.context, rng, device)
t0 = time.time()
with autocast(device):
if teach is None:
_, loss = model(x, y)
else:
with torch.no_grad():
t_logits, _ = teach(x)
logits, _ = model(x)
loss = distill_loss(logits, t_logits, y, distill)
loss.backward()
clip_grad_norm(model.parameters(), grad_clip)
opt.step()
opt.zero_grad()
if device == "cuda":
torch.cuda.synchronize()
train_time += time.time() - t0
tokens_done += tokens_per_step
log_file.close()
# Final, exact numbers on the best checkpoint.
best = torch.load(best_path, map_location=device, weights_only=True)
model.load_state_dict(best["model"])
final_val = full_loss(model, val_data, device)
final_sample = sample_text(model, tok, prompt)
(run_dir / "sample_final.txt").write_text(prompt + final_sample, encoding="utf-8")
summary = {
"params": model.num_params(),
"best_step": best["step"],
"val_loss": final_val,
"perplexity": math.exp(final_val),
"tokens_seen": tokens_done,
"train_seconds": train_time,
"wall_seconds": time.time() - t_start,
"tokens_per_s": tokens_done / train_time if train_time else 0.0,
"peak_gpu_mb": torch.cuda.max_memory_allocated() / 2**20 if device == "cuda" else 0.0,
}
for key in ("trained_on", "teacher", "teacher_params", "distill"):
if key in about:
summary[key] = about[key]
best["extra"] = summary
torch.save(best, best_path)
log(f"done: best step {best['step']}, val loss {final_val:.4f} (perplexity {math.exp(final_val):.1f})")
return summary123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Live training dashboard: python -m vrel watch, then open http://127.0.0.1:8777
Reads what training already writes (runs/<preset>/log.csv and run.json, and the preset's last.pt).
The "what Vrel writes right now" sample runs on the CPU so it never slows the GPU.
"""
import csv
import json
import math
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
PAGE = Path(__file__).with_name("watch.html")
DEFAULT_ABOUT = {"prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels",
"params": 13891584, "batch": 32, "tokens_per_step": 32 * 256}
class Dashboard:
def __init__(self, run_dir, ckpt_dir, data_dir, steps=6000):
self.run_dir = Path(run_dir)
self.data_dir = Path(data_dir)
self.last_ckpt = Path(ckpt_dir) / "last.pt"
self.steps = steps
self.bigram = None
self._sample = {"key": None, "body": None}
self._lock = threading.Lock()
threading.Thread(target=self._load_bigram, daemon=True).start()
def _load_bigram(self):
cache = self.data_dir / "bigram.json"
try:
if cache.exists():
self.bigram = json.loads(cache.read_text())["bigram_val_loss"]
return
from .bigram import bigram_loss
from .data import load_bin
from .tokenizer import Tokenizer
tok = Tokenizer.load(self.data_dir / "tokenizer.json")
loss = bigram_loss(load_bin(self.data_dir / "train.bin"), load_bin(self.data_dir / "val.bin"),
tok.vocab_size)
cache.write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)}))
self.bigram = loss
except Exception:
self.bigram = None # the chart simply leaves the baseline line out
def status(self):
rows = []
log = self.run_dir / "log.csv"
if log.exists():
with open(log, newline="") as f:
for r in csv.DictReader(f):
try:
rows.append({k: float(v) for k, v in r.items()})
except (TypeError, ValueError):
pass # a row being written right now
final = self.run_dir / "sample_final.txt"
finished = final.exists() and log.exists() and final.stat().st_mtime >= log.stat().st_mtime - 5
age = time.time() - log.stat().st_mtime if log.exists() else None
state = "finished" if finished else ("training" if age is not None and age < 600 else "waiting")
about = self.about()
return {"rows": rows, "steps": about.get("steps", self.steps), "bigram": self.bigram, "state": state,
"log_age_s": age, "prompt": about["prompt"], "about": about}
def about(self):
"""What this run is: written by training to run.json (runs before 0.2 did not write one)."""
info = dict(DEFAULT_ABOUT)
try:
info.update(json.loads((self.run_dir / "run.json").read_text(encoding="utf-8")))
except (OSError, ValueError):
pass
return info
def sample(self):
"""Text from the newest checkpoint, regenerated only when the checkpoint changes."""
step0_path = self.run_dir / "sample_step0.txt"
step0 = step0_path.read_text(encoding="utf-8") if step0_path.exists() else None
prompt = self.about()["prompt"]
if not self.last_ckpt.exists():
return {"step": None, "text": None, "step0": step0, "prompt": prompt}
key = self.last_ckpt.stat().st_mtime
with self._lock:
if self._sample["key"] != key:
import torch
from .generate import Runner
torch.set_num_threads(2)
t0 = time.time()
r = Runner(self.last_ckpt, self.data_dir / "tokenizer.json", device="cpu")
text = r.generate(prompt, max_tokens=90, temperature=0.8, top_k=50, seed=0)
self._sample = {"key": key, "body": {"step": r.ckpt["step"], "text": text,
"seconds": round(time.time() - t0, 1)}}
body = dict(self._sample["body"])
body.update(step0=step0, prompt=prompt)
return body
def serve(run_dir, ckpt_dir, data_dir, port=8777, steps=6000):
dash = Dashboard(run_dir, ckpt_dir, data_dir, steps)
class Handler(BaseHTTPRequestHandler):
def _send(self, code, body, ctype):
data = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
try:
if self.path in ("/", "/index.html"):
self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8")
elif self.path == "/api/status":
self._send(200, json.dumps(dash.status()), "application/json")
elif self.path == "/api/sample":
self._send(200, json.dumps(dash.sample()), "application/json")
else:
self._send(404, "not found", "text/plain")
except Exception as e:
self._send(500, json.dumps({"error": str(e)}), "application/json")
def log_message(self, *args):
pass # keep the terminal quiet
class Server(ThreadingHTTPServer):
allow_reuse_address = False # on Windows, True lets two servers share a port silently
try:
server = Server(("127.0.0.1", port), Handler)
except OSError:
raise SystemExit(f"port {port} is already in use; try: python -m vrel watch --port {port + 1}")
print(f"Vrel dashboard: http://127.0.0.1:{port} (Ctrl+C to stop)")
try:
server.serve_forever()
except KeyboardInterrupt:
pass123456789101112{
"name": "Vrel",
"version": "0.2.0",
"kind": "text-generator",
"entry": "vrel.generate:load",
"weights": "vrel.pt",
"tokenizer": "tokenizer.json",
"params": 27795968,
"context": 512,
"val_loss": 1.2779,
"trained_on": "TinyStories: short, simple stories written by GPT-4 (CDLA-Sharing-1.0)"
}1{"format":"vrel-bpe-1","merges":[[32,116],[104,101],[32,97],[32,115],[32,119],[256,257],[110,100],[101,100],[32,98],[256,111],[258,262],[32,104],[32,102],[105,110],[32,84],[260,97],[114,101],[105,116],[111,117],[32,108],[32,100],[32,99],[32,112],[97,121],[32,109],[101,114],[271,115],[111,109],[270,257],[32,257],[105,115],[97,114],[32,110],[105,109],[111,110],[259,97],[108,108],[105,100],[267,97],[32,103],[97,116],[269,103],[32,83],[111,116],[101,110],[97,110],[108,101],[111,114],[105,114],[101,116],[97,109],[32,72],[256,104],[32,273],[284,121],[105,103],[32,34],[105,108],[278,108],[32,269],[307,101],[111,119],[118,281],[114,105],[117,116],[32,117],[314,279],[264,101],[291,293],[273,104],[260,325],[276,279],[32,121],[32,111],[79,110],[112,112],[111,111],[32,114],[107,263],[285,114],[99,101],[32,73],[108,100],[298,257],[270,289],[267,286],[259,116],[107,101],[32,101],[99,107],[110,116],[328,274],[115,116],[318,121],[264,311],[118,101],[101,262],[117,110],[294,331],[32,290],[97,292],[319,352],[268,357],[313,121],[261,121],[32,76],[294,100],[260,101],[321,112],[271,346],[288,299],[257,114],[275,105],[329,102],[97,100],[276,111],[273,116],[115,101],[32,66],[32,77],[354,121],[300,116],[39,115],[101,115],[32,349],[308,296],[330,101],[274,338],[291,119],[268,303],[280,283],[259,104],[259,111],[372,302],[275,389],[259,257],[46,34],[99,104],[289,101],[256,394],[288,101],[288,306],[32,107],[261,272],[274,262],[397,263],[259,109],[361,359],[363,272],[264,111],[33,34],[365,263],[264,320],[84,257],[358,115],[118,263],[274,116],[270,283],[104,116],[304,100],[101,108],[264,415],[97,108],[97,343],[258,110],[283,101],[337,116],[265,111],[260,377],[293,101],[117,103],[260,104],[330,336],[32,286],[285,108],[117,101],[258,292],[430,112],[275,332],[275,111],[114,121],[32,65],[364,290],[116,281],[111,272],[105,262],[268,353],[105,292],[103,305],[306,101],[265,121],[258,115],[32,106],[258,116],[114,97],[276,293],[32,272],[444,367],[117,114],[97,345],[259,101],[265,453],[256,272],[277,296],[108,121],[332,100],[105,99],[277,383],[116,263],[371,103],[277,301],[287,107],[264,356],[261,304],[287,100],[63,34],[101,99],[322,263],[39,116],[119,279],[267,289],[304,108],[109,121],[295,111],[295,477],[333,111],[258,272],[257,100],[97,120],[97,269],[261,109],[275,101],[32,412],[398,110],[268,114],[257,110],[117,109],[291,100],[458,101],[405,121],[117,108],[277,108],[294,351],[299,367],[274,103],[280,301],[435,411],[434,334],[259,112],[342,287],[268,400],[104,297],[375,484],[290,101],[298,431],[264,455],[259,99],[317,110],[368,343],[97,272],[280,101],[277,287],[102,496],[323,99],[278,467],[115,425],[290,103],[416,116],[311,414],[32,382],[268,97],[368,334],[260,383],[268,523],[280,419],[111,112],[283,305],[456,101],[275,97],[114,400],[89,274],[32,87],[101,292],[374,320],[288,111],[274,373],[505,464],[287,263],[447,334],[396,119],[258,108],[105,336],[374,300],[277,445],[500,414],[97,103],[259,532],[313,263],[32,499],[258,103],[298,306],[259,279],[295,461],[264,114],[115,115],[402,356],[370,101],[297,115],[402,553],[319,263],[111,98],[105,97],[112,299],[258,475],[260,303],[552,507],[344,120],[268,441],[308,550],[300,263],[280,562],[427,296],[267,421],[332,107],[116,121],[280,117],[278,320],[490,283],[322,297],[344,349],[271,108],[277,111],[333,301],[287,110],[97,393],[32,74],[100,100],[105,101],[298,568],[105,302],[32,70],[276,513],[259,421],[97,351],[555,485],[268,108],[117,99],[110,121],[107,297],[267,541],[512,543],[534,426],[264,108],[97,98],[117,345],[117,272],[105,345],[101,112],[487,589],[44,34],[32,536],[280,121],[278,114],[105,102],[260,443],[423,107],[308,563],[272,116],[405,120],[258,535],[446,115],[274,100],[259,353],[259,119],[347,114],[97,115],[268,101],[261,110],[368,411],[375,567],[260,491],[286,104],[117,115],[331,263],[277,104],[557,115],[258,98],[301,107],[299,104],[84,289],[275,299],[84,104],[295,305],[295,299],[427,111],[256,565],[97,112],[117,348],[286,116],[489,317],[101,119],[492,112],[273,263],[602,121],[501,121],[315,116],[76,359],[262,281],[105,351],[286,101],[276,472],[333,263],[642,412],[278,623],[32,68],[280,440],[356,121],[113,117],[420,121],[489,656],[97,336],[32,118],[278,111],[614,263],[267,426],[277,515],[278,462],[329,112],[323,348],[519,445],[274,115],[117,373],[454,112],[102,439],[271,439],[475,115],[267,111],[321,110],[295,272],[572,99],[546,691],[97,687],[434,107],[293,263],[488,521],[344,296],[281,115],[607,483],[666,699],[298,111],[481,283],[375,283],[117,592],[361,659],[661,111],[387,317],[264,644],[519,697],[374,566],[278,101],[409,121],[110,110],[301,116],[276,370],[437,262],[308,286],[32,69],[448,657],[288,547],[333,353],[32,343],[273,101],[526,348],[102,101],[355,101],[695,658],[275,522],[89,379],[688,114],[632,416],[84,283],[258,109],[259,108],[117,292],[259,734],[274,114],[256,114],[259,303],[265,338],[256,419],[269,107],[717,97],[269,121],[315,521],[87,104],[259,107],[111,103],[669,580],[295,450],[280,111],[481,345],[344,590],[289,418],[295,599],[420,758],[581,393],[396,263],[302,119],[308,301],[66,320],[265,119],[103,263],[743,436],[114,111],[267,317],[342,114],[32,67],[305,439],[118,300],[32,303],[287,97],[321,663],[329,338],[103,101],[379,115],[497,111],[286,263],[454,116],[323,287],[97,348],[277,302],[102,102],[601,317],[294,262],[454,110],[398,441],[269,101],[451,110],[760,115],[97,262],[97,373],[354,575],[586,334],[307,286],[267,311],[271,116],[448,653],[102,116],[268,637],[268,105],[537,101],[256,436],[257,272],[112,108],[99,483],[32,425],[114,283],[268,461],[321,115],[264,773],[309,115],[275,654],[609,302],[118,297],[811,97],[103,436],[275,305],[396,287],[751,121],[256,119],[256,101],[32,300],[112,472],[285,470],[270,104],[264,426],[296,101],[387,515],[647,643],[681,518],[77,283],[32,619],[105,418],[342,303],[101,120],[264,121],[504,472],[435,351],[842,838],[646,115],[268,763],[276,290],[437,478],[264,579],[268,460],[268,111],[276,301],[396,318],[259,110],[109,440],[674,855],[277,283],[108,102],[105,290],[344,262],[97,107],[387,748],[272,306],[268,440],[256,418],[295,114],[289,98],[260,441],[344,774],[531,302],[497,867],[98,281],[437,747],[277,419],[708,300],[114,109],[786,301],[722,349],[303,116],[256,790],[264,117],[267,470],[280,551],[800,104],[264,370],[371,303],[39,109],[828,464],[277,117],[271,121],[76,305],[875,460],[267,783],[277,421],[284,110],[258,689],[715,870],[329,318],[740,782],[693,840],[900,888],[295,664],[277,257],[683,575],[268,306],[587,108],[618,627],[98,98],[65,115],[268,287],[32,289],[78,111],[682,334],[596,812],[275,627],[295,535],[764,334],[332,108],[680,767],[342,443],[295,108],[32,75],[344,318],[370,121],[117,787],[291,729],[277,356],[492,478],[97,313],[537,491],[883,462],[470,300],[295,932],[298,776],[313,100],[608,431],[32,673],[307,281],[107,279],[99,116],[906,303],[302,115],[278,287],[586,107],[500,104],[369,102],[337,110],[387,383],[402,595],[398,293],[105,112],[105,122],[905,359],[342,279],[864,348],[288,317],[97,320],[101,109],[723,263],[259,673],[111,290],[372,121],[551,101],[116,611],[342,612],[257,115],[323,957],[694,296],[100,121],[256,450],[314,676],[490,752],[272,108],[105,518],[302,796],[967,974],[264,450],[321,346],[111,121],[97,604],[120,116],[396,981],[585,509],[771,522],[781,115],[353,603],[354,359],[333,485],[766,110],[98,101],[32,80],[342,111],[978,313],[110,297],[950,115],[559,111],[839,121],[433,263],[280,305],[105,379],[258,331],[925,121],[911,112],[711,263],[427,595],[73,116],[817,300],[112,116],[682,964],[301,101],[742,610],[927,263],[78,317],[280,541],[280,303],[272,560],[111,345],[272,101],[323,297],[295,445],[277,436],[98,121],[371,292],[452,109],[294,116],[683,300],[298,672],[801,393],[116,104],[258,100],[67,301],[361,305],[87,491],[738,425],[420,821],[72,101],[388,803],[328,928],[992,639],[115,111],[788,702],[537,104],[276,101],[592,263],[276,450],[546,1040],[463,110],[260,111],[922,962],[435,348],[405,296],[108,1002],[694,300],[102,440],[726,613],[449,101],[286,115],[286,483],[264,263],[118,377],[97,122],[268,538],[287,121],[977,351],[304,348],[304,973],[103,301],[540,665],[103,281],[487,599],[526,336],[960,1066],[692,302],[278,638],[750,296],[32,82],[98,273],[260,808],[304,263],[271,876],[302,613],[609,1077],[388,290],[825,111],[323,1054],[72,105],[409,110],[373,858],[98,302],[317,108],[264,272],[789,115],[540,1044],[443,121],[596,1052],[386,478],[285,287],[333,1082],[268,269],[76,579],[647,296],[572,809],[291,116],[66,300],[279,990],[344,121],[459,393],[726,1008],[294,115],[100,279],[278,97],[101,287],[256,1079],[308,746],[516,301],[294,819],[342,440],[277,579],[628,603],[278,739],[278,485],[109,97],[32,1013],[321,373],[442,603],[264,986],[301,779],[272,119],[417,115],[323,104],[328,538],[448,111],[601,111],[117,393],[308,114],[814,263],[570,107],[678,262],[259,297],[117,273],[116,507],[106,979],[32,741],[479,297],[1106,379],[271,273],[260,114],[865,107],[278,593],[434,604],[276,114],[285,370],[276,610],[772,301],[268,1065],[554,115],[591,111],[259,400],[259,1081],[447,107],[958,872],[97,426],[1162,414],[277,450],[333,676],[32,71],[116,297],[122,121],[264,638],[608,1017],[97,304],[788,281],[87,101],[526,118],[805,120],[827,1142],[291,262],[398,273],[333,524],[110,103],[889,319],[452,418],[943,580],[292,317],[267,443],[72,538],[1186,111],[99,491],[1178,1188],[267,531],[277,290],[296,104],[559,524],[1181,686],[303,110],[677,111],[670,111],[276,619],[285,272],[1024,1161],[329,939],[272,263],[591,455],[256,319],[517,115],[387,543],[108,263],[1003,879],[289,379],[1015,418],[570,334],[323,1067],[497,97],[1030,1060],[97,99],[851,1184],[280,980],[308,297],[740,665],[32,319],[105,686],[328,470],[629,101],[280,290],[1174,303],[1225,727],[805,272],[280,780],[596,269],[452,348],[1208,718],[555,1202],[276,286],[104,110],[264,551],[292,121],[587,338],[754,560],[267,293],[276,304],[68,290],[265,112],[278,612],[32,513],[113,431],[65,116],[1130,441],[652,281],[274,346],[276,1016],[256,818],[586,604],[87,317],[385,103],[267,353],[1133,303],[99,111],[830,286],[472,116],[288,524],[801,810],[910,109],[256,356],[259,522],[277,320],[570,436],[333,117],[1196,547],[387,111],[105,263],[267,299],[287,297],[452,370],[458,379],[755,351],[256,538],[342,531],[105,343],[65,689],[348,281],[77,484],[871,263],[1070,115],[750,121],[286,121],[880,263],[256,929],[278,975],[985,281],[762,263],[371,379],[1170,115],[276,467],[32,122],[323,108],[670,370],[98,111],[32,547],[368,290],[65,747],[358,460],[1045,119],[629,297],[1255,821],[277,565],[1214,611],[258,346],[281,263],[314,301],[609,121],[387,412],[729,272],[375,114],[1131,317],[1198,1312],[1223,305],[83,431],[97,810],[1149,336],[437,115],[1022,101],[278,1248],[607,104],[830,296],[340,478],[735,297],[970,269],[298,892],[941,115],[260,305],[311,110],[256,785],[852,336],[313,97],[260,461],[276,416],[83,306],[452,924],[115,104],[1315,346],[852,99],[490,1140],[268,739],[265,1134],[629,289],[83,257],[119,808],[264,1310],[481,292],[105,377],[107,300],[781,373],[692,338],[817,575],[277,918],[420,499],[669,352],[921,370],[456,379],[618,283],[558,1321],[996,1351],[452,1318],[111,283],[99,334],[618,269],[83,892],[271,292],[278,281],[277,114],[342,610],[355,460],[737,1061],[1048,663],[526,304],[296,281],[738,317],[83,111],[32,79],[295,509],[908,263],[275,780],[331,121],[437,292],[275,924],[878,509],[77,567],[725,994],[296,367],[278,117],[294,304],[433,297],[714,111],[258,99],[708,121],[342,101],[452,809],[258,114],[276,319],[591,1010],[408,439],[468,961],[1074,483],[97,118],[83,776],[277,863],[280,524],[937,612],[402,538],[101,101],[386,377],[497,627],[262,1122],[509,121],[323,300],[271,103],[264,273],[259,273],[462,121],[698,115],[371,297],[268,356],[275,524],[269,115],[97,102],[276,769],[452,590],[397,101],[264,287],[868,317],[260,1058],[306,379],[462,263],[857,297],[276,269],[285,338],[581,348],[276,509],[97,1285],[280,296],[889,112],[1102,440],[881,121],[260,665],[268,524],[1120,263],[640,935],[276,863],[1135,945],[260,269],[849,115],[100,281],[39,272],[277,785],[267,425],[79,939],[795,121],[866,317],[374,1395],[99,302],[807,297],[1369,102],[427,121],[631,104],[256,748],[296,859],[308,643],[777,348],[769,283],[881,935],[1132,269],[105,120],[73,110],[1213,639],[504,108],[278,300],[629,306],[1311,263],[1382,290],[631,611],[1001,302],[32,351],[343,121],[487,803],[552,1209],[1397,1270],[114,263],[278,746],[952,263],[299,116],[1240,580],[559,499],[271,411],[317,281],[512,1063],[1408,460],[416,121],[610,121],[1176,263],[274,112],[940,303],[259,611],[258,876],[277,272],[295,1432],[396,348],[456,300],[350,1069],[707,478],[109,301],[546,509],[640,1171],[1200,263],[593,338],[264,763],[854,317],[259,305],[437,689],[1191,116],[1404,121],[100,115],[32,1090],[278,299],[308,1018],[280,287],[308,1128],[1335,115],[319,379],[647,286],[295,619],[271,658],[514,115],[674,1141],[954,263],[1401,102],[284,272],[754,1381],[112,101],[412,104],[448,566],[504,299],[534,262],[581,115],[79,104],[100,101],[652,101],[74,111],[277,1249],[559,301],[608,455],[280,1539],[258,304],[280,1057],[941,518],[1091,861],[1454,302],[256,524],[766,281],[287,116],[458,296],[530,115],[264,1278],[996,343],[1009,115],[268,443],[295,377],[1216,263],[631,107],[880,115],[1121,116],[114,317],[366,1433],[280,1472],[278,296],[692,639],[111,1236],[285,1520],[328,1112],[108,99],[260,290],[122,122],[570,338],[314,718],[112,104],[456,97],[116,290],[670,1439],[68,111],[1543,462],[34,46],[678,108],[1042,296],[448,117],[726,121],[1254,299],[497,299],[333,400],[585,1347],[1596,966],[72,281],[559,550],[264,1490],[83,568],[274,110],[1147,522],[342,117],[323,101],[476,1088],[280,492],[303,109],[1535,460],[452,108],[117,263],[365,115],[1336,462],[99,121],[110,281],[264,303],[336,560],[739,121],[1341,263],[302,560],[114,299],[857,112],[66,566],[363,287],[677,286],[333,425],[769,560],[1043,613],[76,659],[756,115],[267,273],[1157,1234],[111,115],[851,120],[728,281],[102,1620],[351,115],[272,110],[105,305],[286,439],[288,652],[427,727],[608,643],[259,1094],[387,1272],[276,436],[865,334],[937,1641],[1645,305],[301,336],[947,521],[259,425],[264,1090],[470,115],[1029,121],[1224,1280],[487,103],[263,969],[398,297],[515,346],[598,509],[259,1331],[570,565],[361,1334],[1519,269],[1157,101],[375,1105],[1530,116],[705,290],[1468,795],[344,109],[1220,318],[295,105],[32,1245],[77,1105],[456,99],[72,286],[1627,273],[344,108],[259,1642],[934,104],[452,672],[295,117],[452,115],[487,1425],[278,1662],[372,300],[408,1586],[448,287],[1099,1058],[371,1501],[1118,1000],[278,708],[300,336],[591,300],[70,812],[850,297],[265,1110],[1681,373],[270,111],[301,103],[306,112],[1435,1617],[1678,623],[363,1579],[437,116],[1375,121],[505,116],[1360,782],[296,263],[402,1559],[750,595],[1021,297],[268,454],[354,300],[323,590],[105,272],[949,115],[103,103],[260,637],[1667,1613],[678,269],[278,311],[681,1638],[1447,1640],[1462,1259],[363,292],[559,513],[269,263],[277,317],[70,269],[581,100],[277,1457],[585,1141],[344,302],[393,918],[701,297],[268,1514],[1547,1234],[1160,115],[122,101],[1319,115],[638,263],[1373,297],[449,116],[458,1480],[725,115],[264,1604],[722,109],[264,1192],[291,1180],[101,370],[1135,317],[1182,1489],[348,1754],[1565,263],[101,98],[259,1738],[607,507],[278,785],[1151,746],[1224,1483],[260,563],[372,297],[771,1127],[985,263],[32,45],[74,653],[1297,470],[373,115],[772,104],[344,1721],[351,108],[1001,942],[32,90],[101,121],[105,331],[278,688],[345,305],[1349,263],[289,105],[775,1127],[303,100],[267,303],[268,1018],[1416,767],[103,121],[1549,393],[259,1500],[39,292],[328,379],[570,1521],[1015,994],[836,478],[754,1413],[277,101],[755,411],[287,109],[326,412],[1114,115],[1707,421],[1780,302],[269,297],[291,313],[311,104],[1269,379],[1695,302],[1504,296],[115,305],[275,290],[105,1089],[1074,104],[65,478],[256,1660],[344,287],[368,819],[1429,334],[1812,1497],[259,1766],[286,379],[587,296],[854,455],[1164,98],[1688,115],[102,879],[280,370],[852,1069],[903,101],[631,263],[264,727],[1099,672],[292,593],[391,292],[1166,450],[97,560],[278,305],[374,1094],[1023,115],[1045,103],[280,269],[677,443],[456,263],[109,101],[260,257],[268,301],[273,393],[504,114],[512,863],[264,1568],[280,1414],[638,104],[1851,305],[102,637],[1111,560],[105,393],[292,97],[402,111],[800,367],[278,272],[648,1167],[275,419],[280,499],[353,393],[1426,639],[629,563],[1097,116],[387,531],[99,966],[115,121],[290,115],[291,1845],[827,945],[1111,119],[1295,593],[98,317],[286,107],[345,115],[504,269],[825,1424],[1398,319],[259,117],[80,975],[538,97],[854,419],[418,1657],[587,292],[277,97],[342,795],[427,654],[559,297],[903,1308],[1615,1221],[97,331],[105,318],[115,119],[277,1195],[481,370],[988,1877],[291,345],[1878,702],[264,296],[277,1163],[420,1897],[1843,963],[280,929],[335,1088],[342,272],[1262,281],[327,115],[387,1805],[1265,101],[375,1783],[481,98],[1139,297],[264,610],[333,97],[448,101],[101,478],[278,104],[268,273],[79,75],[260,440],[265,109],[1190,263],[456,287],[640,111],[278,1494],[865,604],[1578,115],[115,99],[413,478],[1332,121],[1566,302],[280,792],[342,509],[1602,302],[275,773],[1830,373],[361,101],[1244,281],[286,97],[1048,343],[517,1623],[1295,522],[111,108],[1829,686],[264,300],[278,702],[504,111],[102,1745],[278,595],[374,117],[1169,104],[98,114],[387,579],[448,979],[1841,290],[105,301],[265,602],[311,103],[315,99],[74,455],[277,741],[374,108],[694,119],[1091,370],[1882,411],[1915,299],[540,373],[280,654],[1733,672],[304,112],[642,302],[101,543],[111,348],[387,419],[1593,547],[105,281],[268,1696],[387,114],[1257,108],[1961,483],[344,631],[450,940],[1042,1902],[1786,373],[618,566],[826,1215],[278,443],[864,318],[76,1334],[306,97],[481,1538],[517,436],[302,109],[353,97],[830,643],[1965,373],[264,317],[296,303],[755,348],[943,116],[1163,121],[293,779],[1390,1383],[1989,1997],[505,115],[1584,718],[374,1885],[275,1498],[288,2005],[632,119],[387,121],[398,1057],[1737,2010],[1751,1122],[1153,115],[264,795],[275,1865],[398,727],[452,99],[1949,393],[288,320],[277,599],[280,467],[328,752],[329,98],[97,454],[260,450],[492,98],[504,467],[1076,1920],[533,109],[741,110],[1249,485],[1370,279],[1675,718],[304,1029],[364,1811],[1377,460],[448,2036],[613,352],[678,1781],[1374,518],[71,461],[735,115],[783,302],[1239,297],[105,639],[1353,297],[387,287],[742,274],[1574,1350],[2040,1110],[368,351],[1876,351],[398,1689],[657,121],[831,115],[1909,305],[2053,112],[271,114],[504,961],[766,1656],[1240,116],[1475,631],[1941,111],[256,980],[826,590],[1990,367],[296,111],[375,467],[387,652],[839,1000],[1169,121],[276,379],[540,1822],[931,418],[1390,1581],[259,602],[313,297],[1917,305],[396,345],[680,115],[103,460],[277,470],[303,115],[492,872],[264,2056],[272,370],[719,969],[1426,351],[1360,665],[281,436],[321,2087],[738,293],[267,1414],[275,832],[516,305],[370,317],[1399,318],[275,370],[304,116],[497,644],[314,1010],[538,121],[2075,379],[256,2049],[278,531],[305,281],[277,304],[496,287],[1827,818],[32,330],[259,612],[280,313],[1118,593],[2118,107],[117,346],[1267,1545],[332,112],[347,1180],[839,109],[1891,302],[2104,1452],[111,351],[282,110],[405,560],[587,318],[677,418],[952,101],[1373,263],[280,299],[361,1943],[433,518],[533,107],[587,269],[754,98],[1036,121],[1158,115],[1366,1619],[1399,351],[323,292],[315,1757],[108,297],[288,305],[1229,672],[264,301],[281,116],[591,289],[851,338],[1099,637],[1966,431],[280,590],[418,109],[1560,115],[98,356],[570,109],[772,421],[1233,1895],[259,416],[260,425],[300,115],[302,116],[504,1419],[97,302],[110,299],[331,297],[468,115],[670,752],[1204,112],[101,272],[259,426],[308,269],[466,2169],[83,611],[315,118],[866,279],[1974,121],[504,293],[775,1067],[278,1192],[437,717],[534,348],[866,2060],[1132,343],[1177,119],[903,119],[2150,301],[66,101],[857,379],[965,115],[1553,263],[2163,1855],[771,297],[1396,639],[79,102],[117,98],[786,318],[32,377],[259,892],[278,301],[271,351],[534,119],[1028,297],[1307,115],[504,101],[1859,644],[2174,348],[259,281],[280,263],[640,1127],[366,507],[591,653],[1191,1952],[866,832],[116,111],[117,112],[448,2108],[1151,492],[264,467],[276,654],[306,263],[661,2211],[1159,121],[100,779],[256,593],[448,656],[707,111],[2218,518],[101,318],[1445,297],[1921,509],[109,281],[264,509],[331,281],[385,444],[680,101],[715,676],[2230,416],[83,116],[108,1494],[640,1831],[2135,303],[100,300],[291,108],[447,104],[745,115],[826,97],[281,121],[308,945],[1306,115],[119,470],[1175,263],[1296,969],[908,942],[952,1168],[1239,2247],[1991,317],[2156,792],[374,986],[1773,2181],[269,97],[353,103],[485,263],[596,1487],[911,551],[1394,1629],[1503,115],[332,102],[332,373],[517,116],[591,443],[76,1376],[111,1365],[260,935],[531,104],[546,522],[1332,101],[1440,393],[323,861],[772,296],[1972,419],[276,105],[391,858],[1264,115],[268,302],[275,1376],[277,1629],[333,297],[391,613],[640,612],[1147,727],[1254,664],[329,774],[348,859],[456,296],[487,109],[1297,120],[83,961],[374,101],[448,752],[1043,281],[1102,303],[1542,263],[1846,416],[2226,297],[276,1128],[572,112],[2081,302],[121,470],[465,115],[1659,115],[273,121],[496,116],[1379,1834],[258,118],[511,2313],[1929,518],[1985,121],[292,111],[396,1807],[1836,1413],[1164,119],[1294,1364],[1676,2298],[2130,121],[32,78],[97,119],[109,297],[275,279],[426,103],[921,317],[2182,281],[278,455],[282,104],[755,290],[452,116],[570,604],[287,779],[311,281],[2340,790],[256,293],[262,112],[291,351],[1228,121],[2324,98],[108,664],[333,370],[355,2219],[368,729],[617,1280],[111,99],[259,741],[319,292],[84,111],[109,98],[277,2157],[742,431],[98,287],[264,550],[285,1887],[260,283],[368,803],[902,115],[1001,1976],[2365,301],[101,348],[361,1998],[375,1576],[1618,297],[2068,483],[342,613],[843,115],[1190,101],[117,672],[479,338],[537,325],[650,302],[742,653],[851,299],[270,86],[278,918],[1342,115],[303,1571],[353,107],[732,281],[75,962],[259,1134],[275,2342],[1146,297],[2345,121],[273,297],[1566,460],[1676,300],[264,97],[304,114],[305,104],[366,101],[1374,263],[1409,121],[109,377],[110,263],[291,411],[342,623],[1071,115],[1475,1464],[112,580],[303,107],[843,460],[1345,2332],[1516,1510],[1673,2410],[1883,331],[1928,1983],[278,1986],[398,612],[619,101],[828,116],[1750,336],[115,112],[287,115],[295,1389],[387,2105],[517,565],[951,101],[1166,111],[1412,115],[1635,2030],[1925,2387],[77,121],[83,672],[280,652],[337,102],[531,101],[674,509],[756,305],[256,1546],[277,274],[278,269],[632,1389],[65,262],[258,940],[267,492],[268,297],[280,1105],[290,116],[298,116],[903,281],[509,348],[582,115],[314,832],[363,861],[512,287],[101,107],[405,299],[450,560],[1673,2362],[2346,97],[2460,2459],[111,373],[298,112],[1850,263],[1898,281],[1950,290],[267,2452],[1215,263],[2249,2225],[278,741],[1409,263],[1849,279],[32,1331],[67,421],[268,419],[270,114],[280,441],[781,345],[1341,297],[1357,263],[1435,2431],[1905,281],[2417,832],[363,1272],[479,379],[677,301],[971,115],[264,589],[490,2449],[723,297],[1267,98],[118,686],[258,102],[275,792],[333,515],[387,467],[452,103],[2035,263],[276,311],[448,305],[1042,121],[281,460],[416,112],[618,299],[1294,332],[1366,336],[991,975],[1402,115],[1470,297],[2043,1778],[2172,1789],[290,379],[587,1168],[2082,1619],[110,780],[450,293],[823,1022],[1213,560],[1847,1616],[2300,290],[260,297],[284,304],[388,108],[632,305],[1810,664],[259,1245],[288,281],[1003,1016],[2494,2517],[271,787],[285,2323],[294,1180],[388,338],[534,1168],[1932,1546],[2456,102],[2528,2493],[119,101],[295,353],[489,2277],[826,2400],[1525,393],[298,532],[2038,1872],[280,286],[540,1285],[670,290],[2054,1089],[259,454],[826,302],[908,302],[1366,116],[342,296],[714,1022],[877,263],[72,2504],[335,111],[342,461],[1048,858],[462,334],[1591,547],[110,462],[268,313],[277,367],[454,373],[591,2096],[682,2563],[866,1500],[570,100],[1204,379],[280,2399],[418,107],[632,263],[985,305],[2554,431],[344,551],[450,103],[666,303],[1057,2089],[1440,439],[2243,531],[320,101],[372,281],[559,2006],[1163,281],[1364,121],[1702,453],[2189,1857],[2572,303],[328,589],[952,122],[1612,593],[289,112],[295,832],[489,1410],[640,796],[280,2037],[288,2090],[302,1956],[402,2083],[260,286],[265,785],[298,421],[386,115],[512,2580],[516,1480],[722,1858],[1798,2600],[1919,613],[1927,393],[117,336],[264,418],[504,676],[559,1853],[1220,393],[1724,464],[2241,518],[32,1419],[370,111],[632,287],[1121,464],[1407,121],[276,2586],[497,652],[629,1785],[921,1837],[1774,115],[68,370],[115,281],[258,112],[268,286],[276,637],[333,296],[1844,115],[342,304],[1060,2378],[117,418],[261,373],[287,108],[779,348],[1716,436],[299,101],[2462,263],[277,319],[301,121],[448,306],[786,287],[805,281],[375,121],[1963,1487],[342,450],[437,108],[670,1498],[1583,115],[2398,338],[2649,336],[2175,287],[2191,97],[2306,297],[32,39],[122,1168],[271,262],[281,97],[1549,1870],[1616,1460],[2113,1460],[2651,1813],[108,1639],[278,319],[581,787],[2165,664],[256,281],[271,343],[333,945],[375,1063],[1861,115],[2593,411],[114,1712],[264,419],[307,317],[908,121],[2311,2672],[99,263],[267,454],[291,102],[387,2102],[1573,263],[481,373],[1030,109],[1370,513],[264,281],[265,644],[286,112],[497,513],[693,108],[827,103],[1332,263],[2692,1528],[321,2359],[2246,2666],[2700,272],[256,377],[277,963],[398,2561],[619,102],[2477,431],[2673,319],[303,121],[329,336],[1606,908],[2710,301],[103,117],[268,2578],[276,739],[276,2259],[280,443],[427,2694],[490,653],[1394,1195],[1591,727],[121,109],[277,769],[1151,643],[276,2044],[277,652],[278,279],[282,483],[333,426],[504,2092],[628,102],[861,300],[1752,1469],[2544,1209],[2711,1195],[2714,595],[112,293],[114,566],[256,1163],[260,1848],[308,612],[423,108],[519,421],[631,112],[825,654],[1686,2421],[107,269],[267,2123],[388,652],[581,1339],[601,551],[608,1364],[1685,780],[2719,2679],[256,2732],[295,1962],[573,297],[1606,2737],[2354,1221],[2505,1259],[333,104],[492,1871],[497,2762],[678,303],[943,1623],[1171,115],[1233,1257],[1951,553],[2725,818],[108,97],[418,686],[512,515],[857,2115],[1468,461],[1919,2771],[2132,431],[2738,101],[258,2121],[264,790],[435,103],[487,370],[750,111],[1339,792],[295,300],[374,415],[497,279],[528,110],[1025,115],[1091,1192],[1612,484],[2750,1469],[256,2343],[444,818],[630,1088],[905,686],[1482,2793],[1523,2073],[2028,97],[99,313],[99,1350],[100,595],[116,115],[278,718],[342,319],[342,925],[677,792],[1257,2801],[1476,2799],[1927,810],[2527,101],[267,279],[387,951],[628,2783],[736,478],[1131,263],[2697,792],[2702,1858],[32,912],[447,604],[638,2638],[693,2820],[2213,462],[268,792],[268,918],[303,436],[420,2800],[608,317],[741,115],[854,1410],[1097,115],[1151,531],[1416,290],[1810,611],[1888,1259],[2723,2807],[2784,281],[2822,792],[32,51],[111,1383],[256,612],[258,592],[766,416],[826,348],[860,297],[1043,370],[1198,102],[2441,393],[2592,97],[2677,377],[2708,1089],[107,110],[265,426],[268,296],[269,418],[280,416],[311,2854],[374,1112],[435,345],[1164,1168],[1875,115],[2846,462],[2852,104],[264,2584],[272,300],[280,462],[281,818],[294,109],[373,2669],[435,373],[2546,2866],[342,2513],[572,306],[693,2851],[1102,2267],[2349,303],[103,653],[112,879],[120,1813],[338,2503],[481,287],[677,796],[775,2856],[999,418],[1036,272],[1043,348],[1302,297],[2248,370],[2803,115],[2824,637],[2861,2317],[2873,513],[104,1977],[109,305],[256,652],[267,287],[276,426],[311,483],[329,296],[342,455],[447,1081],[540,1521],[540,1871],[567,1089],[881,2258],[937,287],[1233,2876],[1602,283],[1615,832],[2031,112],[74,289],[105,1245],[301,767],[427,1857],[456,292],[2905,973],[277,1528],[295,2892],[645,478],[693,2911],[1132,1236],[2183,1489],[2836,686],[105,118],[344,2536],[430,2893],[548,603],[903,348],[275,317],[755,118],[755,819],[826,306],[1269,101],[1762,97],[2131,263],[69,349],[278,2848],[295,1140],[629,301],[1147,2643],[2027,305],[2613,1652],[2731,2244],[77,1576],[105,718],[111,262],[692,373],[960,515],[1042,595],[1471,263],[97,639],[100,302],[108,676],[121,418],[277,795],[388,345],[492,101],[534,98],[616,114],[618,279],[1467,518],[2906,297],[105,107],[301,320],[375,1994],[715,2963],[1954,1581],[2085,2952],[32,441],[103,535],[268,741],[293,377],[311,2002],[317,263],[648,115],[921,431],[1697,603],[2289,2878],[2937,287],[344,2879],[353,110],[640,1800],[738,2051],[2028,783],[267,1195],[432,2972],[479,296],[872,436],[1368,305],[1391,121],[1541,464],[2632,367],[121,297],[271,663],[277,609],[308,1065],[640,2912],[940,638],[1024,441],[2474,303],[99,283],[271,1639],[375,2646],[435,2953],[459,115],[490,524],[538,311],[775,100],[1618,263],[1618,1571],[2357,2944],[2447,281],[2981,297],[108,524],[111,338],[264,3010],[268,311],[296,379],[333,2469],[661,3006],[1215,257],[2031,639],[295,958],[333,2272],[387,792],[556,478],[566,121],[1051,115],[1204,1703],[2867,2236],[2994,269],[2995,121],[300,603],[374,114],[405,969],[921,2587],[991,101],[1269,299],[1476,603],[1476,2713],[2577,281],[99,942],[288,1610],[342,863],[427,2168],[551,379],[618,353],[695,2395],[2152,478],[3019,377],[32,281],[73,102],[278,304],[366,1759],[368,122],[504,377],[882,281],[1880,994],[2212,1221],[2358,453],[2529,664],[3042,418],[3053,579],[72,317],[256,1270],[281,112],[313,116],[490,513],[715,2238],[991,1576],[1612,2903],[2991,1510],[109,1977],[387,562],[640,2573],[827,1610],[1429,872],[1473,521],[1482,313],[2524,351],[2531,302],[2962,105],[3075,686],[269,780],[270,748],[275,1704],[304,273],[323,301],[546,3072],[893,115],[1061,101],[1061,122],[1398,1571],[1889,2997],[2044,377],[3005,575],[77,101],[288,929],[336,2166],[452,102],[574,518],[947,1757],[977,3098],[1267,1731],[1441,1771],[2294,300],[2767,318],[117,262],[295,2273],[504,3086],[512,114],[630,115],[742,657],[1309,305],[1846,296],[2111,2114],[2652,119],[3054,470],[83,2825],[97,1383],[640,117],[1824,115],[3112,305],[102,464],[117,100],[256,551],[277,532],[2451,518],[3033,513],[3120,2682],[65,272],[256,1209],[296,439],[387,440],[722,774],[1124,518],[1396,418],[1835,115],[2885,769],[87,808],[98,1207],[120,1221],[278,1016],[329,2350],[420,3141],[605,115],[692,2170],[755,1452],[1011,115],[2498,2114],[3028,302],[260,951],[260,1719],[263,1350],[363,1887],[418,115],[762,115],[1925,2073],[2344,263],[263,121],[280,531],[285,418],[313,580],[363,415],[1685,3162],[1903,439],[2025,115],[2029,3153],[2274,961],[3147,110],[97,787],[278,353],[393,1171],[827,99],[944,115],[1230,1622],[1759,450],[2023,1785],[2515,518],[2929,593],[2968,3094],[108,795],[280,293],[481,100],[601,2583],[681,1622],[960,1464],[1294,3176],[1856,263],[99,2971],[278,1960],[296,393],[299,111],[459,3065],[490,2006],[1888,287],[1890,297],[2319,2355],[3193,443],[105,111],[487,301],[746,121],[751,739],[1021,348],[1503,3172],[3190,111],[77,492],[112,379],[256,1719],[259,2897],[655,297],[825,311],[881,3066],[1204,1879],[3198,287],[111,299],[276,945],[306,2945],[433,115],[516,718],[754,336],[1243,115],[1276,115],[1462,1610],[1946,263],[3016,611],[103,297],[104,951],[259,1140],[267,1800],[322,518],[420,103],[429,3181],[561,281],[1059,1469],[1394,3189],[2286,3217],[3182,2951],[258,1044],[276,2112],[294,858],[328,2331],[379,1110],[601,1464],[618,111],[2016,263],[2209,263],[270,2265],[371,351],[410,3227],[462,116],[970,112],[1204,345],[1725,101],[1905,1308],[1950,654],[3138,121],[3203,418],[114,279],[283,379],[296,1350],[333,665],[368,1956],[375,1057],[587,348],[711,115],[1954,2662],[1982,2594],[2407,393],[3239,109],[3255,377],[256,643],[264,1419],[368,3123],[537,443],[1003,3260],[1747,462],[2671,269],[2718,1308],[32,85],[269,464],[454,686],[517,112],[859,115],[889,990],[903,652],[1043,1425],[1214,3281],[1336,524],[2855,290],[3050,631],[333,551],[342,1466],[385,2255],[405,470],[481,1545],[601,445],[814,297],[857,98],[1368,115],[3282,305],[66,1094],[256,2980],[268,2037],[275,273],[295,287],[301,1069],[308,2092],[693,3000],[1111,302],[1164,345],[1504,832],[2564,1657],[2696,1017],[3173,274],[3302,416],[3308,2115],[122,263],[259,313],[269,1063],[409,304],[435,1365],[531,470],[780,593],[840,116],[1220,336],[1750,2684],[2057,460],[2078,107],[2621,518],[2670,1743],[112,455],[117,990],[119,1759],[272,418],[277,566],[278,317],[342,1704],[354,3083],[512,2864],[540,1775],[601,1002],[1227,1510],[1624,305],[1798,3334],[1907,2301],[2078,1331],[2351,3199],[3039,269],[3231,416],[280,426],[291,2612],[434,112],[890,115],[1018,107],[1121,1167],[1405,104],[1849,297],[2162,111],[2796,115],[3335,3333],[77,1994],[277,3354],[278,657],[512,3132],[1606,969],[2328,115],[2443,115],[267,3259],[268,1389],[430,462],[504,353],[531,439],[540,100],[678,958],[809,279],[1355,281],[3370,3372],[71,664],[264,657],[273,367],[363,613],[373,492],[581,3382],[1133,296],[1702,1110],[2446,1089],[99,796],[259,302],[285,2228],[315,373],[454,297],[1530,464],[2032,1207],[106,1259],[278,2428],[368,1365],[489,2420],[546,2151],[557,297],[693,1460],[922,3081],[1159,297],[1233,3375],[2179,658],[2209,861],[2609,832],[3220,518],[3272,1460],[3358,3280],[120,121],[277,509],[320,104],[323,379],[344,2637],[387,1514],[775,1452],[861,121],[1548,263],[2579,832],[3290,281],[3305,963],[71,111],[277,796],[278,303],[387,1546],[409,272],[448,2266],[450,779],[487,3322],[581,302],[826,2424],[946,547],[1076,566],[1837,859],[2202,104],[3229,1622],[3269,1731],[3343,273],[3390,940],[99,1483],[112,281],[114,110],[260,918],[268,117],[355,379],[456,418],[504,1112],[692,3440],[693,1896],[1177,2301],[1267,1381],[1327,115],[1394,336],[1396,861],[1859,343],[2471,263],[3427,302],[99,320],[119,631],[258,281],[278,792],[291,553],[387,1896],[479,858],[531,108],[631,1772],[638,567],[872,1528],[937,273],[1379,75],[1591,637],[1624,320],[1624,3434],[2602,966],[2633,3459],[3007,3319],[3435,3467],[3460,3465],[3475,367],[74,1010],[277,306],[280,523],[286,859],[295,1112],[666,425],[755,302],[1130,599],[1422,115],[2038,290],[3197,2620],[3388,1008],[256,3332],[265,3442],[267,2828],[295,492],[333,293],[342,963],[452,112],[516,418],[530,2220],[587,1424],[614,297],[677,105],[1448,115],[1842,281],[1918,774],[2020,963],[2032,702],[2098,379],[264,739],[278,2566],[286,464],[335,98],[435,370],[695,727],[857,809],[1294,951],[1686,99],[1717,297],[1817,115],[3253,290],[275,2992],[385,1029],[486,2868],[501,551],[624,379],[827,118],[1336,1896],[1593,2228],[1945,115],[2326,1207],[2534,1980],[3151,263],[3243,3013],[70,1052],[112,287],[259,352],[259,746],[270,3026],[280,3090],[290,121],[489,299],[1501,121],[2539,305],[2551,1584],[256,928],[276,653],[288,3508],[455,305],[495,115],[593,102],[640,2273],[715,590],[720,121],[724,460],[742,3412],[771,3306],[943,562],[991,1779],[1128,2411],[1624,2166],[1762,436],[3424,393],[3481,2664],[3545,509],[32,263],[98,496],[99,1195],[118,2002],[273,418],[287,1960],[452,2255],[504,538],[526,3543],[593,119],[629,1848],[692,2423],[737,3567],[771,2334],[1271,416],[1737,3569],[3262,1063],[3472,281],[3577,3570],[3578,1652],[108,1584],[322,2969],[363,2457],[371,3586],[433,1622],[448,3549],[496,117],[677,3575],[751,269],[762,302],[849,3387],[984,281],[1625,111],[1777,1364],[2111,3568],[3473,832],[32,299],[77,928],[300,373],[496,98],[504,352],[791,2516],[906,741],[1003,769],[1573,281],[2337,963],[3602,439],[292,951],[342,3170],[505,263],[512,2168],[546,1800],[826,287],[992,351],[1475,273],[1548,297],[1747,1986],[3478,1010],[3613,531],[3622,664],[102,729],[116,105],[257,116],[308,3551],[329,861],[374,305],[496,619],[632,348],[678,334],[970,345],[1675,819],[2565,1528],[3626,101],[278,302],[298,110],[391,305],[435,3624],[448,2388],[504,443],[551,3628],[715,287],[805,3560],[1030,303],[1323,115],[1547,101],[1889,3632],[2043,418],[2054,3140],[2335,297],[3527,1221],[3645,3627],[99,421],[277,531],[277,818],[348,462],[355,336],[366,547],[456,3536],[504,3656],[670,301],[678,343],[715,2552],[970,1775],[1574,393],[2425,263],[3336,1452],[3648,818],[99,1983],[269,379],[272,924],[398,279],[466,101],[1223,1376],[1370,1010],[1492,115],[1550,1771],[1685,470],[2242,436],[2898,115],[2910,478],[3477,3660],[3503,1947],[3633,2923],[3651,2244],[3673,105],[74,443],[121,101],[277,1704],[277,1853],[328,590],[546,3675],[587,3638],[631,297],[692,942],[921,2128],[1169,966],[1398,103],[1553,595],[1579,301],[1751,359],[2162,1976],[2645,1781],[97,819],[104,462],[257,370],[267,579],[280,1568],[298,104],[320,379],[342,2766],[342,3393],[471,46],[677,425],[742,2388],[854,2706],[972,115],[1115,115],[1196,3704],[1423,115],[1482,3709],[1562,115],[1752,2777],[1842,116],[1861,112],[3687,269],[3688,418],[3695,116],[32,317],[65,108],[103,300],[110,1778],[277,1656],[289,3736],[375,492],[827,1775],[996,3690],[1482,262],[2224,718],[2418,547],[2418,1433],[3525,263],[3566,779],[100,283],[119,2411],[256,300],[264,3605],[323,305],[328,305],[678,302],[743,116],[826,109],[878,1347],[1477,112],[2132,117],[2685,436],[3723,111],[39,100],[108,1000],[259,2133],[385,107],[655,115],[1429,973],[1842,3714],[2533,297],[226,128],[259,524],[350,2641],[877,297],[1391,3458],[1458,297],[1545,348],[2221,1855],[2269,792],[2895,1339],[3589,269],[116,394],[260,2420],[264,443],[295,304],[922,289],[970,1339],[1273,297],[1451,257],[2213,418],[2840,305],[3116,2987],[3676,861],[3742,303],[71,450],[117,663],[329,107],[333,299],[387,320],[426,767],[439,110],[512,1128],[600,348],[866,1090],[1220,908],[1440,116],[1690,115],[2999,718],[3363,2747],[267,1779],[278,273],[280,935],[387,879],[638,483],[640,3738],[754,2461],[929,818],[1026,115],[2375,115],[2442,393],[3438,664],[3788,858],[269,2355],[280,1689],[336,263],[363,1807],[516,296],[711,297],[742,562],[1118,297],[1121,439],[1230,2030],[1798,2083],[1856,2877],[2206,121],[3783,1771],[3809,111],[3831,718],[73,115],[87,538],[275,2090],[361,3592],[452,318],[516,109],[545,2423],[915,281],[1302,563],[1724,1167],[1836,2461],[2033,460],[2082,3824],[2113,3041],[3052,832],[3561,101],[115,673],[264,796],[275,263],[308,3795],[309,393],[309,1088],[333,1061],[443,97],[591,419],[678,348],[755,3776],[789,302],[927,297],[940,531],[991,2839],[1297,969],[1883,3441],[2326,108],[2458,115],[3752,302],[118,3483],[273,111],[277,332],[329,3867],[361,579],[416,2252],[462,281],[512,3215],[534,2630],[608,269],[755,3854],[766,702],[883,1061],[1076,840],[1102,485],[1277,115],[1295,116],[1593,1419],[1918,665],[1982,746],[2176,604],[2761,3822],[3805,1016],[3834,281],[3884,3875],[3895,281],[68,1439],[99,297],[108,317],[110,306],[259,290],[277,3879],[295,2744],[406,46],[448,426],[481,299],[487,1464],[728,2370],[1176,297],[1441,115],[1482,348],[1574,3800],[2319,3816],[2551,3874],[3444,416],[3759,818],[3877,638],[3899,1635],[256,1568],[265,595],[278,418],[283,263],[308,2463],[454,263],[489,1017],[772,111],[883,110],[1448,263],[1903,257],[2464,1278],[2829,1743],[3030,305],[3515,2404],[3924,676],[32,311],[83,1410],[101,281],[108,332],[256,484],[268,595],[593,348],[596,111],[915,460],[937,952],[1732,115],[2029,3394],[2957,416],[3516,485],[3663,832],[3756,112],[3844,1248],[3923,116],[3938,3941],[3942,105],[116,300],[269,1466],[280,300],[291,638],[298,986],[302,262],[374,3323],[497,2200],[1353,115],[1951,343],[2206,110],[2223,297],[2550,102],[3036,870],[3046,101],[3860,303],[97,273],[294,292],[295,2722],[296,1497],[305,101],[322,281],[388,287],[452,441],[489,524],[628,1811],[775,3903],[780,2151],[854,101],[903,560],[1349,297],[1357,297],[1817,460],[1996,297],[2153,281],[2191,631],[2407,810],[3609,351],[3694,859],[3886,792],[3984,377],[77,114],[114,290],[270,3544],[276,3985],[295,303],[387,980],[437,272],[596,114],[628,103],[640,1652],[751,2051],[795,97],[866,513],[1106,101],[1379,2350],[1747,590],[1963,108],[2212,351],[2289,97],[2686,1497],[3981,3940],[82,101],[99,3604],[275,352],[295,769],[368,4021],[416,3657],[587,1257],[608,541],[715,2457],[825,477],[1525,436],[2175,2641],[2183,2133],[4026,97],[66,3692],[268,664],[277,2316],[321,114],[344,3380],[363,652],[414,2200],[452,1538],[516,2102],[588,393],[751,951],[1166,664],[1269,1775],[1903,4040],[2029,2630],[2416,879],[2742,115],[2810,1743],[3906,263],[108,3466],[118,305],[298,638],[452,336],[715,101],[1204,639],[1263,281],[1379,119],[1538,3159],[2279,593],[2756,1207],[3718,111],[3740,2437],[4007,4053],[46,46],[79,119],[276,664],[277,783],[313,299],[348,319],[636,2233],[871,297],[881,2552],[1182,782],[1269,1365],[1557,460],[1854,2159],[1946,115],[4003,3861],[260,2428],[280,1192],[377,859],[526,602],[601,741],[674,1347],[693,619],[769,1932],[772,2640],[1228,963],[1369,109],[1525,810],[1686,654]],"special":{"<|endoftext|>":4095}}123version https://git-lfs.github.com/spec/v1oid sha256:6a47fc9aa9cf8a5fb18a86b033cede82f907d7799eb48734df8627ea212710a4size 28016248123"""Vrel: a small language model built from scratch."""
__version__ = "0.3.1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Command line: python -m vrel <command>"""
import argparseimport jsonimport mathimport shutilimport sysimport timefrom pathlib import Path
from . import __version__
ROOT = Path(__file__).resolve().parent.parentDATA = ROOT / "data"
BOOKS = {"data": DATA, "ckpt": ROOT / "checkpoints", "steps": 6000, "batch": 32, "lr": 6e-4, "warmup": 200, "eval_every": 250, "prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels", "trained_on": "public-domain books from Project Gutenberg", "model_version": "0.1.0"}STORIES = {"data": DATA / "stories", "ckpt": ROOT / "checkpoints" / "stories", "steps": 20000, "batch": 16, "lr": 8e-4, "warmup": 500, "eval_every": 500, "prompt": "Once upon a time", "dataset": "2.7 million short stories", "trained_on": "TinyStories: short, simple stories written by GPT-4 (CDLA-Sharing-1.0)", "model_version": "0.2.0"}# What each preset trains on and how, and which Vrel it makes. The model shapes themselves live in model.PRESETS.RUNS = { "small": BOOKS, # Quick tests save to their own folder so they never overwrite a real model. "tiny": {**BOOKS, "ckpt": ROOT / "checkpoints" / "tiny", "steps": 200, "eval_every": 50, "model_version": "0.1.0-tiny"}, "stories": STORIES, "stories-tiny": {**STORIES, "ckpt": ROOT / "checkpoints" / "stories-tiny", "steps": 200, "eval_every": 50, "model_version": "0.2.0-tiny"}, # Vrel 0.3: half the size of "stories", learning from the trained "stories" model as well as from the text. "mini": {**STORIES, "ckpt": ROOT / "checkpoints" / "mini", "teacher": ROOT / "checkpoints" / "stories" / "vrel.pt", "distill": 0.5, "model_version": "0.3.0"},}DEFAULT = "stories"
def cmd_prepare(a): from .data import HOST, MIRRORS, clean_all, fetch, read_book_ids
ids = read_book_ids(a.books) hosts = MIRRORS if a.mirror_only else (HOST,) + MIRRORS print(f"fetching {len(ids)} books from {' then '.join(hosts)} into {DATA / 'raw'} " "(already-downloaded books are skipped)") if not fetch(ids, DATA / "raw", delay=a.delay, hosts=hosts, timeout=a.timeout): sys.exit("download stopped early; run the same command again later (finished books are kept)") print("cleaning") clean_all(DATA / "raw", DATA / "clean")
def cmd_tokenizer(a): from .data import build_bins, tokenizer_sample from .tokenizer import Tokenizer
text = tokenizer_sample(DATA / "clean", a.sample_chars) print(f"training tokenizer on {len(text) / 1e6:.1f}M characters, vocab {a.vocab}") t0 = time.time() tok = Tokenizer.train(text, a.vocab, verbose=True) tok.save(DATA / "tokenizer.json") print(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") t0 = time.time() n_train, n_val = build_bins(DATA / "clean", tok, DATA, log=lambda s: None) chars = sum(p.stat().st_size for p in (DATA / "clean").glob("*.txt")) print(f"encoded in {time.time() - t0:.0f}s: {n_train:,} train + {n_val:,} val tokens " f"({chars / (n_train + n_val):.2f} bytes per token)")
def cmd_stories(a): from . import stories
folder = STORIES["data"] missing = [n for n, size in stories.FILES.values() if not (folder / n).exists() or (folder / n).stat().st_size != size] if missing: if not a.download: sys.exit(f"missing {', '.join(missing)} in {folder}. Run again with --download to fetch them " "(about 2.25 GB from huggingface.co).") stories.download(folder) stories.build(folder, vocab=a.vocab, sample_chars=a.sample_chars, workers=a.workers)
def cmd_bigram(a): from .bigram import bigram_loss from .data import load_bin from .tokenizer import Tokenizer
d = RUNS[a.preset]["data"] tok = Tokenizer.load(d / "tokenizer.json") loss = bigram_loss(load_bin(d / "train.bin"), load_bin(d / "val.bin"), tok.vocab_size) (d / "bigram.json").write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)})) print(json.dumps({"bigram_val_loss": round(loss, 4), "perplexity": round(math.exp(loss), 1)}))
def cmd_train(a): from .train import train
r = RUNS[a.preset] name = a.name or a.preset out_dir = r["ckpt"] if not a.name else ROOT / "checkpoints" / a.name teacher = None if a.teacher == "none" else (a.teacher or r.get("teacher")) if teacher and not Path(teacher).exists(): sys.exit(f"teacher checkpoint {teacher} not found. Train it first, or pass --teacher none.") summary = train(data_dir=r["data"], out_dir=out_dir, run_dir=ROOT / "runs" / name, preset=a.preset, steps=a.steps or r["steps"], batch_size=a.batch_size or r["batch"], lr=a.lr or r["lr"], min_lr=(a.lr or r["lr"]) / 10, warmup=r["warmup"], eval_every=a.eval_every or r["eval_every"], resume=a.resume, prompt=r["prompt"], about={"dataset": r["dataset"], "trained_on": r["trained_on"]}, teacher=teacher, distill=r.get("distill", 0.5) if a.distill is None else a.distill) print(json.dumps(summary, indent=2))
def _paths(a): r = RUNS[a.preset] return Path(a.checkpoint or r["ckpt"] / "vrel.pt"), Path(a.tokenizer or r["data"] / "tokenizer.json")
def cmd_generate(a): from .generate import Runner
ckpt, tok = _paths(a) r = Runner(ckpt, tok) sys.stdout.write(a.prompt) sys.stdout.flush()
def show(piece): sys.stdout.write(piece) sys.stdout.flush()
r.generate(a.prompt, a.max_tokens, a.temperature, a.top_k, a.seed, on_token=show) print()
def cmd_stats(a): import torch
ckpt, _ = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) params = sum(t.numel() for t in ck["model"].values() if t.dtype.is_floating_point) print(json.dumps({"config": ck["config"], "step": ck["step"], "params": params, "tokenizer": ck["tokenizer"], "summary": ck.get("extra", {})}, indent=2))
def export_dir(preset): """models/vrel-<the model's own version>, so exports of different models never overwrite each other.""" return ROOT / "models" / f"vrel-{RUNS[preset]['model_version']}"
def cmd_export(a): import torch
ckpt, tok = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) out = Path(a.out or export_dir(a.preset)) if out.exists(): shutil.rmtree(out) (out / "vrel").mkdir(parents=True) for src in (ROOT / "vrel").glob("*.py"): # self-contained: the code travels with the weights shutil.copy2(src, out / "vrel" / src.name) keep = {k: ck[k] for k in ("config", "step", "val_loss", "tokenizer", "extra")} if a.format == "int8": from .quant import quantize
keep["model_int8"] = quantize(ck["model"]) else: keep["model"] = ck["model"] torch.save(keep, out / "vrel.pt") shutil.copy2(tok, out / "tokenizer.json") extra = ck.get("extra", {}) manifest = { "name": "Vrel", "version": RUNS[a.preset]["model_version"], # the model's version, not this code's "kind": "text-generator", "entry": "vrel.generate:load", "weights": "vrel.pt", "tokenizer": "tokenizer.json", "params": extra.get("params"), "context": ck["config"]["context"], "val_loss": round(extra.get("val_loss", ck["val_loss"]), 4), "trained_on": extra.get("trained_on", RUNS[a.preset]["trained_on"]), } (out / "model.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") size = sum(p.stat().st_size for p in out.rglob("*") if p.is_file()) print(f"exported to {out} ({size / 1e6:.1f} MB)")
def cmd_watch(a): from .watch import serve
r = RUNS[a.preset] serve(ROOT / "runs" / a.preset, r["ckpt"], r["data"], port=a.port, steps=a.steps or r["steps"])
def main(argv=None): p = argparse.ArgumentParser(prog="vrel", description="Vrel: a small language model built from scratch.") p.add_argument("--version", action="version", version=f"vrel {__version__}") sub = p.add_subparsers(dest="cmd", required=True) presets = list(RUNS)
s = sub.add_parser("stories", help="build the TinyStories training data (tokenizer and token files)") s.add_argument("--download", action="store_true", help="download missing files (about 2.25 GB)") s.add_argument("--vocab", type=int, default=4096, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=20_000_000, help="characters to learn the tokenizer from") s.add_argument("--workers", type=int, default=None, help="encoding processes (default: half your CPU, max 6)") s.set_defaults(fn=cmd_stories)
s = sub.add_parser("prepare", help="download and clean the 0.1 training books") s.add_argument("--books", default=DATA / "books.txt", help="file with one Gutenberg book ID per line") s.add_argument("--delay", type=float, default=2.0, help="seconds to wait between downloads") s.add_argument("--timeout", type=float, default=60.0, help="seconds to wait on a stalled download") s.add_argument("--mirror-only", action="store_true", help="skip gutenberg.org and use only its official mirrors " "(by default the mirrors are fallbacks)") s.set_defaults(fn=cmd_prepare)
s = sub.add_parser("tokenizer", help="train the tokenizer and encode the 0.1 books into token files") s.add_argument("--vocab", type=int, default=8192, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=5_000_000, help="characters of text to learn merges from") s.set_defaults(fn=cmd_tokenizer)
s = sub.add_parser("bigram", help="score the bigram baseline on the validation set") s.add_argument("--preset", choices=presets, default=DEFAULT, help="which dataset") s.set_defaults(fn=cmd_bigram)
s = sub.add_parser("train", help="train Vrel") s.add_argument("--preset", choices=presets, default=DEFAULT, help="stories (Vrel 0.2, default), mini (Vrel 0.3: half the size, learns from 0.2), small (Vrel 0.1 books), " "or a -tiny version for a quick test") s.add_argument("--steps", type=int, default=None, help="training rounds (default depends on the preset)") s.add_argument("--batch-size", type=int, default=None) s.add_argument("--lr", type=float, default=None, help="peak learning rate") s.add_argument("--eval-every", type=int, default=None) s.add_argument("--resume", action="store_true", help="continue from the preset's last.pt") s.add_argument("--teacher", default=None, help="checkpoint to learn from as well as the text (mini learns from Vrel 0.2); 'none' to skip") s.add_argument("--distill", type=float, default=None, help="share of the loss from the teacher, 0 to 1 (default 0.5)") s.add_argument("--name", default=None, help="save under runs/NAME and checkpoints/NAME instead of the preset's folders") s.set_defaults(fn=cmd_train)
s = sub.add_parser("watch", help="live training dashboard in your browser") s.add_argument("--port", type=int, default=8777) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which run to watch") s.add_argument("--steps", type=int, default=None, help="total rounds, if the run did not record it") s.set_defaults(fn=cmd_watch)
for name, fn, hlp in (("generate", cmd_generate, "write text from a prompt"), ("stats", cmd_stats, "show what is inside a checkpoint"), ("export", cmd_export, "package the model so other apps can load it")): s = sub.add_parser(name, help=hlp) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which trained model") s.add_argument("--checkpoint", default=None, help="checkpoint file (default: the preset's vrel.pt)") s.add_argument("--tokenizer", default=None, help="tokenizer file (default: the preset's)") if name == "generate": s.add_argument("--prompt", default="", help="text for Vrel to continue") s.add_argument("--max-tokens", type=int, default=200) s.add_argument("--temperature", type=float, default=0.8, help="0 = always pick the likeliest token") s.add_argument("--top-k", type=int, default=50, help="only sample from the k likeliest tokens") s.add_argument("--seed", type=int, default=None, help="same seed + prompt = same text") if name == "export": s.add_argument("--out", default=None, help="output folder (default models/vrel-<model version>, such as models/vrel-0.3.0)") s.add_argument("--format", choices=("int8", "float32"), default="int8", help="int8 (default) is a quarter of the size with the same quality") s.set_defaults(fn=fn)
a = p.parse_args(argv) a.fn(a)
if __name__ == "__main__": main()12345678910111213141516171819202122232425"""Bigram baseline: predicts each token only from the one before it, by counting.
This is the simplest possible language model. Vrel has to beat it by a wide
margin for its attention layers to be worth anything.
"""
import numpy as np
def bigram_loss(train, val, vocab_size, k=0.1, chunk=50_000_000):
"""Mean negative log-probability on `val`, using add-k smoothed bigram counts from `train`."""
V = vocab_size
counts = np.zeros(V * V, dtype=np.int64)
# Count in slices so even hundreds of millions of tokens fit in memory. Each slice
# overlaps the next by one token so the pair across the boundary is counted once.
for start in range(0, max(1, len(train) - 1), chunk):
a = np.asarray(train[start:start + chunk + 1], dtype=np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V)
counts = counts.astype(np.float32).reshape(V, V)
val = np.asarray(val, dtype=np.int64)
counts += k
row_sums = counts.sum(axis=1)
a, b = val[:-1], val[1:]
logp = np.log(counts[a, b]) - np.log(row_sums[a])
return float(-logp.mean())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Training data: fetch public-domain books, clean them, and turn them into token files."""
import http.client
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
import numpy as np
from .tokenizer import EOT
CACHE_PATH = "/cache/epub/{id}/pg{id}.txt"
# Where each server keeps a book's plain text. Paths are tried in order.
SOURCES = {
"www.gutenberg.org": [CACHE_PATH],
# Official Project Gutenberg mirror, classic layout: book 1342 lives at /1/3/4/1342/1342-0.txt
"mirrors.xmission.com": ["/gutenberg/{dirs}/{id}/{id}-0.txt", "/gutenberg/{dirs}/{id}/{id}.txt"],
# Project Gutenberg Literary Archive Foundation, same layout as the main site
"aleph.pglaf.org": [CACHE_PATH],
}
HOST = "www.gutenberg.org"
MIRRORS = ("mirrors.xmission.com", "aleph.pglaf.org")
USER_AGENT = "vrel-data-fetch/0.1"
def book_urls(host, book_id):
s = str(book_id)
dirs = "0" if len(s) == 1 else "/".join(s[:-1])
return [f"https://{host}" + p.format(id=book_id, dirs=dirs) for p in SOURCES.get(host, [CACHE_PATH])]
# The marker can wrap onto a second line ("...SHERLOCK" / "HOLMES ***"), so match up to its closing ***.
START_RE = re.compile(r"^\*\*\* ?START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^*]{0,300}\*\*\*", re.M | re.I)
END_RE = re.compile(r"^\*\*\* ?END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK.*$", re.M | re.I)
TITLE_RE = re.compile(r"^Title:\s*(.+)$", re.M)
def read_book_ids(path):
"""Parse a list file: one book ID per line, '#' starts a comment."""
ids = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
line = line.split("#", 1)[0].strip()
if line:
ids.append(int(line))
return ids
def _download(url, timeout=60, attempts=5, pause=5.0, opener=urllib.request.urlopen, sleep=time.sleep):
"""Fetch `url`. If the connection drops or stalls partway, resume from the last
byte received (HTTP Range) instead of starting over, up to `attempts` tries.
Errors the server answers with (like 503 or 404) are not retried."""
data = b""
total = None
for attempt in range(1, attempts + 1):
headers = {"User-Agent": USER_AGENT}
if data:
headers["Range"] = f"bytes={len(data)}-"
try:
with opener(urllib.request.Request(url, headers=headers), timeout=timeout) as resp:
if data and resp.status != 206: # server ignored the range: start over
data = b""
if total is None and resp.headers.get("Content-Length"):
total = len(data) + int(resp.headers["Content-Length"])
while True:
chunk = resp.read(1 << 16)
if not chunk:
break
data += chunk
if total is None or len(data) >= total:
break
raise http.client.IncompleteRead(data, total - len(data))
except urllib.error.HTTPError:
raise
except (http.client.HTTPException, OSError) as e: # dropped, reset or timed out
if attempt == attempts:
raise
sleep(pause)
if not START_RE.search(data[:20000].decode("utf-8", errors="replace")):
raise ValueError("response is not a Project Gutenberg text")
return data
def fetch(ids, raw_dir, delay=2.0, hosts=(HOST,) + MIRRORS, max_failures_in_a_row=3, log=print,
download=_download, timeout=60):
"""Download each book once; files already on disk are never fetched again.
Each book is tried on `hosts` in order, so the main site is preferred and the
mirrors are fallbacks. Waits `delay` seconds after every request, success or
not. A host that fails `max_failures_in_a_row` times is dropped for the rest
of the run so no server is hammered (a plain "not found" does not count).
Returns False if every host was dropped.
"""
raw_dir = Path(raw_dir)
raw_dir.mkdir(parents=True, exist_ok=True)
live = list(hosts)
failures = {h: 0 for h in hosts}
for n, book_id in enumerate(ids, 1):
dest = raw_dir / f"{book_id}.txt"
if dest.exists():
continue
body = None
for host in list(live):
for url in book_urls(host, book_id):
try:
body = download(url, timeout=timeout)
break
except urllib.error.HTTPError as e:
if e.code == 404:
continue # this server keeps it under another name; try the next path
err = e
except Exception as e:
err = e
finally:
time.sleep(delay)
failures[host] += 1
log(f" [{n}/{len(ids)}] book {book_id} from {host}: FAILED ({err})")
if failures[host] >= max_failures_in_a_row:
live.remove(host)
log(f" {host}: {failures[host]} failures in a row, not asking it again this run")
break
if body is not None:
failures[host] = 0
dest.write_bytes(body)
log(f" [{n}/{len(ids)}] book {book_id} from {host}: {len(body) / 1e6:.2f} MB")
break
if body is None and live:
log(f" [{n}/{len(ids)}] book {book_id}: not downloaded this run")
if not live:
return False
return True
def strip_gutenberg(text):
"""Keep only the book itself: drop the Project Gutenberg header, footer and license."""
text = text.replace("\r\n", "\n").replace("\r", "\n").lstrip("")
start = START_RE.search(text)
end = END_RE.search(text)
body = text[start.end() if start else 0 : end.start() if end else len(text)]
return body.strip() + "\n"
def book_title(text):
m = TITLE_RE.search(text)
return m.group(1).strip() if m else "(unknown title)"
def clean_all(raw_dir, clean_dir, log=print):
raw_dir, clean_dir = Path(raw_dir), Path(clean_dir)
clean_dir.mkdir(parents=True, exist_ok=True)
titles = {}
for src in sorted(raw_dir.glob("*.txt"), key=lambda p: int(p.stem)):
raw = src.read_bytes().decode("utf-8", errors="replace")
body = strip_gutenberg(raw).replace(EOT, "")
(clean_dir / src.name).write_text(body, encoding="utf-8")
titles[int(src.stem)] = book_title(raw)
log(f" {src.stem}: {book_title(raw)} ({len(body) / 1e6:.2f} MB)")
return titles
def clean_books(clean_dir):
return sorted(Path(clean_dir).glob("*.txt"), key=lambda p: int(p.stem))
def tokenizer_sample(clean_dir, max_chars=5_000_000):
"""An even slice from every book, so the tokenizer learns from all authors."""
books = clean_books(clean_dir)
per_book = max_chars // max(1, len(books))
parts = []
for p in books:
text = p.read_text(encoding="utf-8")
mid = max(0, len(text) // 2 - per_book // 2)
parts.append(text[mid : mid + per_book])
return "\n".join(parts)
def build_bins(clean_dir, tok, out_dir, val_frac=0.05, log=print):
"""Encode every book. The last `val_frac` of each book becomes validation data."""
out_dir = Path(out_dir)
train_ids, val_ids = [], []
for p in clean_books(clean_dir):
text = p.read_text(encoding="utf-8")
cut = text.rfind("\n", 0, int(len(text) * (1 - val_frac)))
cut = cut if cut > 0 else int(len(text) * (1 - val_frac))
train_ids += tok.encode_ordinary(text[:cut]) + [tok.eot_id]
val_ids += tok.encode_ordinary(text[cut:]) + [tok.eot_id]
log(f" encoded {p.stem}: {len(train_ids):,} train / {len(val_ids):,} val tokens so far")
np.array(train_ids, dtype=np.uint16).tofile(out_dir / "train.bin")
np.array(val_ids, dtype=np.uint16).tofile(out_dir / "val.bin")
return len(train_ids), len(val_ids)
def load_bin(path):
return np.memmap(path, dtype=np.uint16, mode="r")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Make Vrel write: load a checkpoint and sample text one token at a time."""
import codecs
import json
import os
from pathlib import Path
import torch
from .model import Config, Vrel, softmax
from .quant import dequantize
from .tokenizer import Tokenizer
def pick_device(device=None):
if device:
return device
return "cuda" if torch.cuda.is_available() else "cpu"
def load_model(ckpt_path, device=None):
device = pick_device(device)
ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
model = Vrel(Config(**ckpt["config"])).to(device)
# Exports store 8-bit weights ("model_int8"); training checkpoints store float32 ("model").
model.load_state_dict(dequantize(ckpt["model_int8"]) if "model_int8" in ckpt else ckpt["model"])
model.eval()
return model, ckpt
@torch.no_grad()
def sample(model, tok, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
"""Continue `prompt`. Calls on_token(text) as each piece is ready; returns the new text."""
device = next(model.parameters()).device
was_training = model.training
model.eval()
ids = [tok.eot_id] + tok.encode(prompt) # start a new story, as in training
idx = torch.tensor([ids], dtype=torch.long, device=device)
gen = torch.Generator(device=device)
gen.manual_seed(seed if seed is not None else int.from_bytes(os.urandom(8), "little") >> 1)
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
out = []
def emit(piece):
if piece:
out.append(piece)
if on_token is not None:
on_token(piece)
ctx = model.cfg.context
cache, pos = None, 0
def prefill(window):
"""Fill a fresh KV cache with `window` and return the logits for the next token."""
nonlocal cache, pos
cache = model.new_cache()
pos = window.size(1)
return model(window, cache=cache, offset=0)[0][:, -1, :]
if model.v2:
next_logits = prefill(idx[:, -ctx:])
for _ in range(max_tokens):
if should_stop is not None and should_stop():
break
if model.v2:
logits = next_logits.float()
else: # 0.1 architecture: no cache, re-read the whole window every step
logits = model(idx[:, -ctx:])[0][:, -1, :].float()
if temperature <= 0:
nxt = logits.argmax(dim=-1, keepdim=True)
else:
logits = logits / temperature
if top_k and top_k < logits.size(-1):
kth = torch.topk(logits, top_k, dim=-1).values[:, -1:]
logits = logits.masked_fill(logits < kth, float("-inf"))
nxt = torch.multinomial(softmax(logits, dim=-1), 1, generator=gen)
t = int(nxt)
if t == tok.eot_id:
break
idx = torch.cat([idx, nxt], dim=1)
emit(decoder.decode(tok.token_bytes(t)))
if model.v2:
if pos + 1 > ctx: # window full: restart the cache from the most recent half
next_logits = prefill(idx[:, -(ctx // 2):])
else: # only the new token goes through the model; earlier ones come from the cache
next_logits = model(nxt, cache=cache, offset=pos)[0][:, -1, :]
pos += 1
emit(decoder.decode(b"", final=True))
model.train(was_training)
return "".join(out)
class Runner:
"""A loaded model plus its tokenizer, ready to generate."""
def __init__(self, ckpt_path, tokenizer_path, device=None):
self.device = pick_device(device)
self.model, self.ckpt = load_model(ckpt_path, self.device)
self.tok = Tokenizer.load(tokenizer_path)
if self.ckpt.get("tokenizer") and self.ckpt["tokenizer"] != self.tok.fingerprint():
raise ValueError("this tokenizer does not match the one the model was trained with")
def generate(self, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
return sample(self.model, self.tok, prompt, max_tokens, temperature, top_k, seed, on_token, should_stop)
def load(path, device=None):
"""Entry point for the shared model contract: `path` is an exported model folder."""
path = Path(path)
manifest = json.loads((path / "model.json").read_text(encoding="utf-8"))
return Runner(path / manifest["weights"], path / manifest["tokenizer"], device=device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366"""The Vrel transformer, written from scratch.
PyTorch supplies tensors, automatic gradients and the GPU. Every layer here
(linear, embedding, norms, attention, rotary positions, activations, dropout,
loss) is our own code built from basic tensor math.
Two architectures:
- "gpt2" (Vrel 0.1): LayerNorm, learned positions, GELU MLP, biases.
- "v2" (Vrel 0.2+): RMSNorm, rotary positions (RoPE), SwiGLU MLP, no biases,
memory-efficient attention for training and a KV cache for fast generation.
"""
import math
from dataclasses import asdict, dataclass, replace
import torch
from torch import nn
@dataclass
class Config:
vocab_size: int = 8192
context: int = 256 # how many tokens the model can see at once
n_layer: int = 6
n_head: int = 6
d_model: int = 384
dropout: float = 0.1
arch: str = "gpt2" # checkpoints saved before 0.2 have no arch field and load as gpt2
PRESETS = {
"small": Config(),
"tiny": Config(context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0),
"stories": Config(vocab_size=4096, context=512, n_layer=8, n_head=8, d_model=512, dropout=0.0, arch="v2"),
"stories-tiny": Config(vocab_size=4096, context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0, arch="v2"),
# Half the size of "stories" (14.0M parameters), meant to learn from it as a teacher.
"mini": Config(vocab_size=4096, context=512, n_layer=7, n_head=6, d_model=384, dropout=0.0, arch="v2"),
}
def make_config(preset="small", **overrides):
return replace(PRESETS[preset], **overrides)
# ------------------------------------------------------------------ basic math
def softmax(x, dim=-1):
x = x - x.amax(dim=dim, keepdim=True)
e = x.exp()
return e / e.sum(dim=dim, keepdim=True)
def log_softmax(x, dim=-1):
shifted = x - x.amax(dim=dim, keepdim=True)
return shifted - shifted.exp().sum(dim=dim, keepdim=True).log()
def cross_entropy(logits, targets):
"""Average negative log-probability of the correct next token."""
logp = log_softmax(logits.float(), dim=-1)
return -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
def distill_loss(logits, teacher_logits, targets, weight):
"""Learn from the real next token and from a teacher model's guesses at the same time.
The teacher gives a full spread of likely next tokens, not just the one that happened, which is
much richer to learn from. `weight` is the share of the loss that comes from the teacher (0 to 1).
The teacher part is the KL divergence: how far our spread is from the teacher's.
"""
logp = log_softmax(logits.float(), dim=-1)
hard = -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
if weight <= 0:
return hard
t_logp = log_softmax(teacher_logits.float(), dim=-1)
kl = (t_logp.exp() * (t_logp - logp)).sum(dim=-1).mean()
return (1 - weight) * hard + weight * kl
def gelu(x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x)))
def silu(x):
return x / (1.0 + torch.exp(-x))
def dropout(x, p, training):
if not training or p == 0.0:
return x
keep = (torch.rand_like(x, dtype=torch.float32) >= p).to(x.dtype)
return x * keep / (1.0 - p)
def causal_mask(t_q, t_k, device, offset=0):
"""True where a query may NOT look: keys later than the query's own position."""
q_pos = torch.arange(t_q, device=device)[:, None] + offset
k_pos = torch.arange(t_k, device=device)[None, :]
return k_pos > q_pos
# ------------------------------------------------------------------- attention
def _acc_dtype(t):
"""Accumulate in at least 32-bit floats (64-bit stays 64-bit)."""
return torch.promote_types(t.dtype, torch.float32)
class _CausalAttention(torch.autograd.Function):
"""softmax(q k^T * scale, causal) v, without keeping the T x T grid for backward.
Forward saves only q, k, v, the output and one log-sum-exp per row. Backward
recomputes the attention weights from those, one layer at a time, so memory
for the score grid is needed for a single layer instead of every layer at once.
The gradient formulas are the standard ones for softmax attention.
"""
@staticmethod
@torch.amp.custom_fwd(device_type="cuda")
def forward(ctx, q, k, v, scale):
T = q.size(-2)
acc = _acc_dtype(q)
mask = causal_mask(T, T, q.device)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(mask, float("-inf"))
m = s.amax(dim=-1, keepdim=True)
p = (s - m).exp_()
denom = p.sum(dim=-1, keepdim=True)
lse = m + denom.log()
p = (p / denom).to(v.dtype)
y = p @ v
ctx.save_for_backward(q, k, v, y, lse)
ctx.scale = scale
return y
@staticmethod
@torch.amp.custom_bwd(device_type="cuda")
def backward(ctx, dy):
q, k, v, y, lse = ctx.saved_tensors
scale = ctx.scale
T = q.size(-2)
acc = _acc_dtype(q)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(causal_mask(T, T, q.device), float("-inf"))
p = (s - lse).exp_() # the forward's attention weights, recomputed
del s
dy = dy.to(v.dtype)
dv = p.to(v.dtype).transpose(-2, -1) @ dy
dp = (dy @ v.transpose(-2, -1)).to(acc)
row = (dy.to(acc) * y.to(acc)).sum(dim=-1, keepdim=True)
ds = (p * (dp - row) * scale).to(q.dtype)
del p, dp
dq = ds @ k
dk = ds.transpose(-2, -1) @ q
return dq, dk, dv, None
def attention(q, k, v):
return _CausalAttention.apply(q, k, v, 1.0 / math.sqrt(q.size(-1)))
def rope_tables(context, head_dim, device=None, base=10000.0):
"""cos and sin tables for rotary position encoding, shape (context, head_dim / 2)."""
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
angles = torch.outer(torch.arange(context, device=device, dtype=torch.float32), inv)
return angles.cos(), angles.sin()
def apply_rope(x, cos, sin):
"""Rotate each (first-half, second-half) pair of features by an angle that grows with position.
x: (B, H, T, hd); cos, sin: (T, hd/2). Dot products between rotated queries and keys
then depend only on how far apart two tokens are, not on where they are.
"""
half = x.size(-1) // 2
x32 = x.float()
x1, x2 = x32[..., :half], x32[..., half:]
out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
return out.to(x.dtype)
# ---------------------------------------------------------------------- layers
class Linear(nn.Module):
def __init__(self, n_in, n_out, bias=True, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n_out, n_in) * std)
self.bias = nn.Parameter(torch.zeros(n_out)) if bias else None
def forward(self, x):
y = x @ self.weight.t()
return y if self.bias is None else y + self.bias
class Embedding(nn.Module):
def __init__(self, n, d, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n, d) * std)
def forward(self, idx):
return self.weight[idx]
class LayerNorm(nn.Module):
def __init__(self, d, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.bias = nn.Parameter(torch.zeros(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
mean = x32.mean(dim=-1, keepdim=True)
var = ((x32 - mean) ** 2).mean(dim=-1, keepdim=True)
y = (x32 - mean) / torch.sqrt(var + self.eps)
return y * self.weight + self.bias
class RMSNorm(nn.Module):
"""Scale each vector to unit root-mean-square, then by a learned gain. No mean, no bias."""
def __init__(self, d, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
y = x32 * torch.rsqrt((x32 * x32).mean(dim=-1, keepdim=True) + self.eps)
return (y * self.weight).to(x.dtype) if x.dtype != torch.float32 else y * self.weight
class CausalSelfAttention(nn.Module):
"""Each position looks back at itself and earlier positions, never ahead."""
def __init__(self, cfg):
super().__init__()
assert cfg.d_model % cfg.n_head == 0
self.v2 = cfg.arch == "v2"
self.n_head = cfg.n_head
bias = not self.v2
self.qkv = Linear(cfg.d_model, 3 * cfg.d_model, bias=bias)
self.proj = Linear(cfg.d_model, cfg.d_model, bias=bias, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
if not self.v2:
mask = torch.tril(torch.ones(cfg.context, cfg.context, dtype=torch.bool))
self.register_buffer("mask", mask, persistent=False)
def forward(self, x, rope=None, cache=None, offset=0):
B, T, C = x.shape
H = self.n_head
hd = C // H
q, k, v = self.qkv(x).split(C, dim=2)
q = q.view(B, T, H, hd).transpose(1, 2) # (B, H, T, hd)
k = k.view(B, T, H, hd).transpose(1, 2)
v = v.view(B, T, H, hd).transpose(1, 2)
if not self.v2:
scores = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(hd))
scores = scores.float().masked_fill(~self.mask[:T, :T], float("-inf"))
att = dropout(softmax(scores, dim=-1), self.p, self.training)
y = att.to(v.dtype) @ v
else:
cos, sin = rope
q = apply_rope(q, cos[offset:offset + T], sin[offset:offset + T])
k = apply_rope(k, cos[offset:offset + T], sin[offset:offset + T])
if cache is None:
y = attention(q, k, v)
else: # generation: attend over everything cached so far plus the new positions
if cache.get("k") is not None:
k = torch.cat([cache["k"], k], dim=2)
v = torch.cat([cache["v"], v], dim=2)
cache["k"], cache["v"] = k, v
s = (q @ k.transpose(-2, -1)).float() * (1.0 / math.sqrt(hd))
s = s.masked_fill(causal_mask(T, k.size(2), x.device, offset), float("-inf"))
y = softmax(s, dim=-1).to(v.dtype) @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return dropout(self.proj(y), self.p, self.training)
class MLP(nn.Module):
def __init__(self, cfg):
super().__init__()
self.fc = Linear(cfg.d_model, 4 * cfg.d_model)
self.proj = Linear(4 * cfg.d_model, cfg.d_model, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.proj(gelu(self.fc(x))), self.p, self.training)
class SwiGLU(nn.Module):
"""A gated MLP: one projection decides how much of another to let through."""
def __init__(self, cfg):
super().__init__()
hidden = 64 * math.ceil(8 * cfg.d_model / 3 / 64) # same parameter count as a 4x GELU MLP
self.gate = Linear(cfg.d_model, hidden, bias=False)
self.up = Linear(cfg.d_model, hidden, bias=False)
self.down = Linear(hidden, cfg.d_model, bias=False, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.down(silu(self.gate(x)) * self.up(x)), self.p, self.training)
class Block(nn.Module):
def __init__(self, cfg):
super().__init__()
v2 = cfg.arch == "v2"
self.ln1 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.attn = CausalSelfAttention(cfg)
self.ln2 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.mlp = SwiGLU(cfg) if v2 else MLP(cfg)
def forward(self, x, rope=None, cache=None, offset=0):
x = x + self.attn(self.ln1(x), rope, cache, offset)
x = x + self.mlp(self.ln2(x))
return x
class Vrel(nn.Module):
def __init__(self, cfg):
super().__init__()
if cfg.arch not in ("gpt2", "v2"):
raise ValueError(f"unknown architecture {cfg.arch!r}")
self.cfg = cfg
self.v2 = cfg.arch == "v2"
self.tok = Embedding(cfg.vocab_size, cfg.d_model)
if self.v2:
cos, sin = rope_tables(cfg.context, cfg.d_model // cfg.n_head)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
else:
self.pos = Embedding(cfg.context, cfg.d_model)
self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
self.ln_f = RMSNorm(cfg.d_model) if self.v2 else LayerNorm(cfg.d_model)
def forward(self, idx, targets=None, cache=None, offset=0):
"""cache: None for training, or a list (one dict per layer) for step-by-step generation.
offset: how many positions are already in the cache."""
B, T = idx.shape
if offset + T > self.cfg.context:
raise ValueError(f"sequence of {offset + T} tokens is longer than the context of {self.cfg.context}")
if cache is not None and not self.v2:
raise ValueError("the KV cache needs the v2 architecture")
x = self.tok(idx)
rope = None
if self.v2:
rope = (self.rope_cos, self.rope_sin)
else:
x = x + self.pos(torch.arange(T, device=idx.device))
x = dropout(x, self.cfg.dropout, self.training)
for i, block in enumerate(self.blocks):
x = block(x, rope, None if cache is None else cache[i], offset)
x = self.ln_f(x)
logits = x @ self.tok.weight.t() # output layer shares weights with the token embedding
loss = None
if targets is not None:
loss = cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
return logits, loss
def new_cache(self):
return [{} for _ in range(self.cfg.n_layer)]
def num_params(self):
return sum(p.numel() for p in self.parameters())
def config_dict(self):
return asdict(self.cfg)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Training helpers written from scratch: AdamW, gradient clipping, LR schedule."""
import math
import torch
class AdamW: """Adam with decoupled weight decay.
groups: list of {"params": [...], "weight_decay": float} """
def __init__(self, groups, lr=6e-4, betas=(0.9, 0.95), eps=1e-8): self.groups = [{"params": list(g["params"]), "weight_decay": g.get("weight_decay", 0.0)} for g in groups] self.lr = lr self.betas = betas self.eps = eps self.t = 0 self.m = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups] self.v = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups]
def zero_grad(self): for g in self.groups: for p in g["params"]: p.grad = None
@torch.no_grad() def step(self): self.t += 1 b1, b2 = self.betas bc1 = 1.0 - b1 ** self.t bc2 = 1.0 - b2 ** self.t step_size = self.lr / bc1 for gi, g in enumerate(self.groups): wd = g["weight_decay"] for pi, p in enumerate(g["params"]): if p.grad is None: continue grad = p.grad m = self.m[gi][pi] v = self.v[gi][pi] if wd: p.mul_(1.0 - self.lr * wd) m.mul_(b1).add_(grad, alpha=1.0 - b1) v.mul_(b2).addcmul_(grad, grad, value=1.0 - b2) denom = (v.sqrt() / math.sqrt(bc2)).add_(self.eps) p.addcdiv_(m, denom, value=-step_size)
def state_dict(self): return {"t": self.t, "lr": self.lr, "m": self.m, "v": self.v}
def load_state_dict(self, state): self.t = state["t"] self.lr = state["lr"] for gi in range(len(self.groups)): for pi in range(len(self.groups[gi]["params"])): self.m[gi][pi].copy_(state["m"][gi][pi]) self.v[gi][pi].copy_(state["v"][gi][pi])
def param_groups(model, weight_decay): """Matrices get weight decay; biases and layer-norm gains do not.""" decay = [p for p in model.parameters() if p.dim() >= 2] no_decay = [p for p in model.parameters() if p.dim() < 2] return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]
@torch.no_grad()def clip_grad_norm(params, max_norm): """Scale all gradients down together if their combined length exceeds max_norm.""" grads = [p.grad for p in params if p.grad is not None] total = torch.sqrt(sum((g.float() ** 2).sum() for g in grads)) coef = torch.clamp(max_norm / (total + 1e-6), max=1.0) for g in grads: g.mul_(coef.to(g.dtype)) return total
def lr_at(step, max_lr, warmup, total, min_lr): """Linear warmup, then cosine decay from max_lr down to min_lr.""" if step < warmup: return max_lr * (step + 1) / warmup progress = min(1.0, (step - warmup) / max(1, total - warmup)) return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * progress))12345678910111213141516171819202122232425"""Store weights as 8-bit integers: a quarter of the file size, measured to change nothing you can notice.
Every row of a weight matrix gets its own scale: the row's largest absolute value maps to 127, and eachweight is rounded to the nearest of the 255 steps in between. Vectors (norm weights) are tiny, so theystay in 16-bit. When the model loads, everything is turned back into ordinary float32 numbers."""
import torch
def quantize(state): out = {} for name, t in state.items(): t = t.detach().float().cpu() if t.dim() < 2: out[name] = {"w": t.half()} continue # One 32-bit scale per row: exact enough, and so few that they cost almost nothing. scale = t.abs().amax(dim=1, keepdim=True).clamp(min=1e-12) / 127 out[name] = {"q": torch.round(t / scale).clamp(-127, 127).to(torch.int8), "s": scale} return out
def dequantize(state): return {name: d["w"].float() if "w" in d else d["q"].float() * d["s"].float() for name, d in state.items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""The TinyStories dataset: download, clean, train the tokenizer, encode to token files.
TinyStories (roneneldan/TinyStories on Hugging Face, license CDLA-Sharing-1.0) is about2.7 million short, simple English stories written by GPT-4. Vrel only reads them: themodel and every weight in it are still trained from scratch here."""
import osimport timeimport urllib.requestfrom multiprocessing import Poolfrom pathlib import Path
import numpy as np
from .tokenizer import EOT, Tokenizer
BASE_URL = "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/"FILES = { "train": ("TinyStoriesV2-GPT4-train.txt", 2_227_753_162), "valid": ("TinyStoriesV2-GPT4-valid.txt", 22_502_601),}USER_AGENT = "vrel-data-fetch/0.2"
# Curly quotes become straight ones, so the model does not learn two spellings of every quote._TRANSLATE = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})_TRANSLATE.update({c: None for c in range(0x80, 0xA0)}) # stray control characters
def clean(text): return text.translate(_TRANSLATE).strip()
def download(folder, log=print): """Fetch the train and validation files, resuming partial downloads. Skips complete files.""" folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) for name, size in FILES.values(): dest = folder / name have = dest.stat().st_size if dest.exists() else 0 if have == size: continue req = urllib.request.Request(BASE_URL + name, headers={"User-Agent": USER_AGENT, "Range": f"bytes={have}-"}) log(f" downloading {name} ({size / 1e9:.2f} GB) ...") with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "ab" if have else "wb") as f: if have and resp.status != 206: f.truncate(0) # server ignored the resume request; start over while chunk := resp.read(1 << 20): f.write(chunk) if dest.stat().st_size != size: raise OSError(f"{name}: got {dest.stat().st_size:,} bytes, expected {size:,}; run again to resume")
def iter_stories(path, block=1 << 23): """Yield cleaned stories one at a time without reading the whole file into memory.""" buf = "" with open(path, encoding="utf-8", errors="replace") as f: while True: data = f.read(block) if not data: break buf += data parts = buf.split(EOT) buf = parts.pop() # the last piece may be cut off mid-story for p in parts: s = clean(p) if s: yield s s = clean(buf) if s: yield s
def tokenizer_sample(path, max_chars): out, n = [], 0 for s in iter_stories(path): out.append(s) n += len(s) + 1 if n >= max_chars: break return "\n".join(out)
_worker_tok = None
def _init_worker(tok_path): global _worker_tok _worker_tok = Tokenizer.load(tok_path)
def _encode_batch(stories): ids = [] for s in stories: ids.extend(_worker_tok.encode_ordinary(s)) ids.append(_worker_tok.eot_id) return np.array(ids, dtype=np.uint16)
def _batches(path, size=2000): batch = [] for s in iter_stories(path): batch.append(s) if len(batch) == size: yield batch batch = [] if batch: yield batch
def encode_file(src, dest, tok_path, workers, log=print): """Encode every story to `dest` as uint16 tokens, each story followed by the EOT token.""" t0 = time.time() n_tokens = n_stories = 0 tmp = Path(str(dest) + ".tmp") with Pool(workers, initializer=_init_worker, initargs=(str(tok_path),)) as pool, open(tmp, "wb") as f: for i, arr in enumerate(pool.imap(_encode_batch, _batches(src), chunksize=4)): arr.tofile(f) n_tokens += arr.size n_stories += 2000 if i % 100 == 0 and i: log(f" {Path(src).name}: ~{n_stories:,} stories, {n_tokens / 1e6:.0f}M tokens, {time.time() - t0:.0f}s") tmp.replace(dest) return n_tokens, time.time() - t0
def build(folder, vocab=4096, sample_chars=20_000_000, workers=None, log=print): folder = Path(folder) train_txt, valid_txt = (folder / FILES[k][0] for k in ("train", "valid")) workers = workers or max(1, min(6, (os.cpu_count() or 2) // 2)) text = tokenizer_sample(train_txt, sample_chars) log(f"training tokenizer on {len(text) / 1e6:.0f}M characters, vocab {vocab}") t0 = time.time() tok = Tokenizer.train(text, vocab) tok.save(folder / "tokenizer.json") log(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") results = {} for split, src in (("val", valid_txt), ("train", train_txt)): n, secs = encode_file(src, folder / f"{split}.bin", folder / "tokenizer.json", workers, log) chars = src.stat().st_size results[split] = n log(f"{split}: {n:,} tokens in {secs:.0f}s with {workers} workers ({chars / n:.2f} bytes per token)") return tok, results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Vrel's tokenizer: byte-level byte pair encoding (BPE), written from scratch.
Text is first split into rough word-like chunks, then each chunk is turned intoUTF-8 bytes (256 base tokens). Training repeatedly finds the most frequentadjacent pair of tokens and merges it into a new token, until the vocabularyreaches the requested size. Because everything starts from raw bytes, anystring can be encoded and decoded back exactly."""
import hashlibimport heapqimport jsonimport refrom collections import Counter, defaultdict
# Splits text into chunks that merges are not allowed to cross: contractions,# words (with one optional leading space), numbers, punctuation runs, whitespace.# Every character of the input lands in exactly one chunk.SPLIT = re.compile(r"'(?:[sdmt]|ll|ve|re)| ?[^\W\d_]+| ?\d+| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")
EOT = "<|endoftext|>" # marks the boundary between two separate documentsFORMAT = "vrel-bpe-1"
def _merge(ids, pair, new_id): """Replace every non-overlapping occurrence of `pair` in `ids` with `new_id`.""" out = [] i = 0 n = len(ids) a, b = pair while i < n: if i < n - 1 and ids[i] == a and ids[i + 1] == b: out.append(new_id) i += 2 else: out.append(ids[i]) i += 1 return out
class Tokenizer: def __init__(self, merges): self.merges = [tuple(m) for m in merges] self.ranks = {pair: i for i, pair in enumerate(self.merges)} self.vocab = [bytes([i]) for i in range(256)] for a, b in self.merges: self.vocab.append(self.vocab[a] + self.vocab[b]) self.eot_id = len(self.vocab) self.vocab_size = len(self.vocab) + 1 self._cache = {}
# ---------------------------------------------------------------- training @classmethod def train(cls, text, vocab_size=8192, verbose=False): """Learn merges from `text` until the vocabulary has `vocab_size` entries.""" n_merges = vocab_size - 256 - 1 # 256 bytes + merges + 1 special token if n_merges < 0: raise ValueError("vocab_size must be at least 257") counts = Counter(SPLIT.findall(text.replace(EOT, ""))) words = [list(w.encode("utf-8")) for w in counts] freqs = list(counts.values())
pair_counts = defaultdict(int) where = defaultdict(set) # pair -> indices of words that contain it for wi, w in enumerate(words): f = freqs[wi] for p in zip(w, w[1:]): pair_counts[p] += f where[p].add(wi)
# Max-heap of (count, pair). Entries go stale as counts change; a stale # entry is skipped when popped because a fresh one was pushed on change. heap = [(-c, p) for p, c in pair_counts.items()] heapq.heapify(heap)
merges = [] while len(merges) < n_merges and heap: negc, p = heapq.heappop(heap) c = pair_counts.get(p, 0) if c <= 0 or c != -negc: continue new_id = 256 + len(merges) merges.append(p) touched = set() for wi in where.pop(p, ()): w = words[wi] f = freqs[wi] for q in zip(w, w[1:]): pair_counts[q] -= f touched.add(q) nw = _merge(w, p, new_id) for q in zip(nw, nw[1:]): pair_counts[q] += f where[q].add(wi) touched.add(q) words[wi] = nw for q in touched: cq = pair_counts[q] if cq > 0: heapq.heappush(heap, (-cq, q)) else: pair_counts.pop(q, None) if verbose and len(merges) % 500 == 0: print(f" {len(merges)}/{n_merges} merges") return cls(merges)
# ---------------------------------------------------------------- encoding def _encode_chunk(self, chunk): ids = self._cache.get(chunk) if ids is not None: return ids ids = list(chunk.encode("utf-8")) ranks = self.ranks while len(ids) >= 2: best = None best_rank = None for p in zip(ids, ids[1:]): r = ranks.get(p) if r is not None and (best_rank is None or r < best_rank): best, best_rank = p, r if best is None: break ids = _merge(ids, best, 256 + best_rank) if len(self._cache) < 1_000_000: self._cache[chunk] = ids return ids
def encode_ordinary(self, text): """Encode text, treating any special-token text as ordinary characters.""" out = [] for chunk in SPLIT.findall(text): out.extend(self._encode_chunk(chunk)) return out
def encode(self, text): """Encode text; the literal string <|endoftext|> becomes the EOT token.""" out = [] for i, part in enumerate(text.split(EOT)): if i: out.append(self.eot_id) out.extend(self.encode_ordinary(part)) return out
# ---------------------------------------------------------------- decoding def token_bytes(self, i): return EOT.encode("utf-8") if i == self.eot_id else self.vocab[i]
def decode(self, ids): return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors="replace")
# ---------------------------------------------------------------- storage def to_json(self): return json.dumps( {"format": FORMAT, "merges": [list(m) for m in self.merges], "special": {EOT: self.eot_id}}, separators=(",", ":"), )
def save(self, path): with open(path, "w", encoding="utf-8") as f: f.write(self.to_json())
@classmethod def load(cls, path): with open(path, encoding="utf-8") as f: data = json.load(f) if data.get("format") != FORMAT: raise ValueError(f"{path} is not a {FORMAT} tokenizer file") return cls(data["merges"])
def fingerprint(self): """Short hash that identifies this exact set of merges.""" return hashlib.sha256(self.to_json().encode("utf-8")).hexdigest()[:16]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""The training loop: show Vrel real text, measure how wrong it was, nudge every weight."""
import csv
import json
import math
import time
from contextlib import nullcontext
from pathlib import Path
import numpy as np
import torch
from .data import load_bin
from .generate import load_model, sample
from .model import Vrel, distill_loss, make_config
from .optim import AdamW, clip_grad_norm, lr_at, param_groups
from .tokenizer import Tokenizer
def get_batch(data, batch_size, context, rng, device):
ix = rng.integers(0, len(data) - context - 1, size=batch_size)
x = np.stack([data[i : i + context] for i in ix]).astype(np.int64)
y = np.stack([data[i + 1 : i + 1 + context] for i in ix]).astype(np.int64)
x, y = torch.from_numpy(x), torch.from_numpy(y)
if device == "cuda":
return x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
return x.to(device), y.to(device)
def autocast(device):
return torch.autocast("cuda", dtype=torch.bfloat16) if device == "cuda" else nullcontext()
@torch.no_grad()
def full_loss(model, data, device, batch_size=64):
"""Loss over the whole of `data`, in back-to-back windows. Same answer every time."""
model.eval()
T = model.cfg.context
n = (len(data) - 1) // T
total, count = 0.0, 0
for start in range(0, n, batch_size):
rows = range(start, min(n, start + batch_size))
x = torch.from_numpy(np.stack([data[r * T : r * T + T] for r in rows]).astype(np.int64)).to(device)
y = torch.from_numpy(np.stack([data[r * T + 1 : r * T + T + 1] for r in rows]).astype(np.int64)).to(device)
with autocast(device):
_, loss = model(x, y)
total += loss.item() * len(rows)
count += len(rows)
model.train()
return total / max(1, count)
@torch.no_grad()
def quick_loss(model, data, device, batch_size, iters=20, seed=1234):
"""Loss on a fixed set of random windows, for progress logging during training."""
model.eval()
rng = np.random.default_rng(seed)
losses = []
for _ in range(iters):
x, y = get_batch(data, batch_size, model.cfg.context, rng, device)
with autocast(device):
_, loss = model(x, y)
losses.append(loss.item())
model.train()
return sum(losses) / len(losses)
def sample_text(model, tok, prompt, n=120, seed=0):
return sample(model, tok, prompt, max_tokens=n, temperature=0.8, top_k=50, seed=seed)
def save_checkpoint(path, model, opt, step, val_loss, tok, extra=None, with_optimizer=True):
state = {
"model": model.state_dict(),
"config": model.config_dict(),
"step": step,
"val_loss": val_loss,
"tokenizer": tok.fingerprint(),
"extra": extra or {},
}
if with_optimizer:
state["optimizer"] = opt.state_dict()
tmp = Path(str(path) + ".tmp")
torch.save(state, tmp)
tmp.replace(path)
def train(data_dir="data", out_dir="checkpoints", run_dir="runs", preset="small", steps=6000,
batch_size=32, lr=6e-4, min_lr=6e-5, warmup=200, weight_decay=0.1, grad_clip=1.0,
eval_every=250, seed=1337, resume=False, prompt="It was a dark and stormy night", about=None,
teacher=None, distill=0.5, log=print):
"""teacher: path to a trained checkpoint (same tokenizer) for this model to learn from as well as the
text. distill: the share of the loss that comes from the teacher's guesses."""
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_num_threads(4) # keep CPU use modest; the GPU does the heavy work
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
data_dir, out_dir, run_dir = Path(data_dir), Path(out_dir), Path(run_dir)
out_dir.mkdir(parents=True, exist_ok=True)
run_dir.mkdir(parents=True, exist_ok=True)
tok = Tokenizer.load(data_dir / "tokenizer.json")
train_data = load_bin(data_dir / "train.bin")
val_data = load_bin(data_dir / "val.bin")
cfg = make_config(preset, vocab_size=tok.vocab_size)
model = Vrel(cfg).to(device)
teach = None
if teacher:
teach, t_ck = load_model(teacher, device)
if t_ck.get("tokenizer") != tok.fingerprint():
raise ValueError("the teacher was trained with a different tokenizer")
if teach.cfg.context < cfg.context:
raise ValueError("the teacher's context is shorter than this model's")
for p in teach.parameters():
p.requires_grad_(False)
opt = AdamW(param_groups(model, weight_decay), lr=lr)
start_step, best_val = 0, math.inf
last_path, best_path = out_dir / "last.pt", out_dir / "vrel.pt"
if resume and last_path.exists():
ck = torch.load(last_path, map_location=device, weights_only=True)
model.load_state_dict(ck["model"])
opt.load_state_dict(ck["optimizer"])
start_step = ck["step"]
best_val = ck["extra"].get("best_val", math.inf)
rng = np.random.default_rng(seed + start_step)
log(f"resumed from step {start_step}")
about = dict(about or {})
if teach is not None:
about.update(teacher=str(Path(teacher).name), teacher_params=teach.num_params(), distill=distill)
run_info = {"preset": preset, "params": model.num_params(), "batch": batch_size, "context": cfg.context,
"steps": steps, "tokens_per_step": batch_size * cfg.context, "prompt": prompt, **about}
(run_dir / "run.json").write_text(json.dumps(run_info, indent=2), encoding="utf-8")
log(f"device {device}, {model.num_params():,} parameters, "
f"{len(train_data):,} train tokens, {len(val_data):,} val tokens")
log_path = run_dir / "log.csv"
new_log = not (resume and log_path.exists())
log_file = open(log_path, "w" if new_log else "a", newline="")
writer = csv.writer(log_file)
if new_log:
writer.writerow(["step", "lr", "train_loss", "val_loss", "tokens_per_s", "elapsed_s"])
if start_step == 0:
init_val = full_loss(model, val_data, device)
init_sample = sample_text(model, tok, prompt)
(run_dir / "sample_step0.txt").write_text(prompt + init_sample, encoding="utf-8")
log(f"random init: val loss {init_val:.4f} (perplexity {math.exp(init_val):,.0f})")
if device == "cuda":
torch.cuda.reset_peak_memory_stats()
t_start = time.time()
train_time = 0.0
tokens_done = 0
tokens_per_step = batch_size * cfg.context
model.train()
for step in range(start_step, steps + 1):
if step % eval_every == 0 or step == steps:
tr = quick_loss(model, train_data, device, batch_size)
va = quick_loss(model, val_data, device, batch_size)
tps = tokens_done / train_time if train_time else 0.0
writer.writerow([step, f"{opt.lr:.2e}", f"{tr:.4f}", f"{va:.4f}", f"{tps:.0f}", f"{time.time() - t_start:.1f}"])
log_file.flush()
log(f"step {step:5d} | train {tr:.4f} | val {va:.4f} | lr {opt.lr:.2e} | {tps:,.0f} tok/s")
if va < best_val:
best_val = va
save_checkpoint(best_path, model, opt, step, va, tok, with_optimizer=False)
save_checkpoint(last_path, model, opt, step, va, tok, extra={"best_val": best_val})
if step == steps:
break
opt.lr = lr_at(step, lr, warmup, steps, min_lr)
x, y = get_batch(train_data, batch_size, cfg.context, rng, device)
t0 = time.time()
with autocast(device):
if teach is None:
_, loss = model(x, y)
else:
with torch.no_grad():
t_logits, _ = teach(x)
logits, _ = model(x)
loss = distill_loss(logits, t_logits, y, distill)
loss.backward()
clip_grad_norm(model.parameters(), grad_clip)
opt.step()
opt.zero_grad()
if device == "cuda":
torch.cuda.synchronize()
train_time += time.time() - t0
tokens_done += tokens_per_step
log_file.close()
# Final, exact numbers on the best checkpoint.
best = torch.load(best_path, map_location=device, weights_only=True)
model.load_state_dict(best["model"])
final_val = full_loss(model, val_data, device)
final_sample = sample_text(model, tok, prompt)
(run_dir / "sample_final.txt").write_text(prompt + final_sample, encoding="utf-8")
summary = {
"params": model.num_params(),
"best_step": best["step"],
"val_loss": final_val,
"perplexity": math.exp(final_val),
"tokens_seen": tokens_done,
"train_seconds": train_time,
"wall_seconds": time.time() - t_start,
"tokens_per_s": tokens_done / train_time if train_time else 0.0,
"peak_gpu_mb": torch.cuda.max_memory_allocated() / 2**20 if device == "cuda" else 0.0,
}
for key in ("trained_on", "teacher", "teacher_params", "distill"):
if key in about:
summary[key] = about[key]
best["extra"] = summary
torch.save(best, best_path)
log(f"done: best step {best['step']}, val loss {final_val:.4f} (perplexity {math.exp(final_val):.1f})")
return summary123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Live training dashboard: python -m vrel watch, then open http://127.0.0.1:8777
Reads what training already writes (runs/<preset>/log.csv and run.json, and the preset's last.pt).
The "what Vrel writes right now" sample runs on the CPU so it never slows the GPU.
"""
import csv
import json
import math
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
PAGE = Path(__file__).with_name("watch.html")
DEFAULT_ABOUT = {"prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels",
"params": 13891584, "batch": 32, "tokens_per_step": 32 * 256}
class Dashboard:
def __init__(self, run_dir, ckpt_dir, data_dir, steps=6000):
self.run_dir = Path(run_dir)
self.data_dir = Path(data_dir)
self.last_ckpt = Path(ckpt_dir) / "last.pt"
self.steps = steps
self.bigram = None
self._sample = {"key": None, "body": None}
self._lock = threading.Lock()
threading.Thread(target=self._load_bigram, daemon=True).start()
def _load_bigram(self):
cache = self.data_dir / "bigram.json"
try:
if cache.exists():
self.bigram = json.loads(cache.read_text())["bigram_val_loss"]
return
from .bigram import bigram_loss
from .data import load_bin
from .tokenizer import Tokenizer
tok = Tokenizer.load(self.data_dir / "tokenizer.json")
loss = bigram_loss(load_bin(self.data_dir / "train.bin"), load_bin(self.data_dir / "val.bin"),
tok.vocab_size)
cache.write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)}))
self.bigram = loss
except Exception:
self.bigram = None # the chart simply leaves the baseline line out
def status(self):
rows = []
log = self.run_dir / "log.csv"
if log.exists():
with open(log, newline="") as f:
for r in csv.DictReader(f):
try:
rows.append({k: float(v) for k, v in r.items()})
except (TypeError, ValueError):
pass # a row being written right now
final = self.run_dir / "sample_final.txt"
finished = final.exists() and log.exists() and final.stat().st_mtime >= log.stat().st_mtime - 5
age = time.time() - log.stat().st_mtime if log.exists() else None
state = "finished" if finished else ("training" if age is not None and age < 600 else "waiting")
about = self.about()
return {"rows": rows, "steps": about.get("steps", self.steps), "bigram": self.bigram, "state": state,
"log_age_s": age, "prompt": about["prompt"], "about": about}
def about(self):
"""What this run is: written by training to run.json (runs before 0.2 did not write one)."""
info = dict(DEFAULT_ABOUT)
try:
info.update(json.loads((self.run_dir / "run.json").read_text(encoding="utf-8")))
except (OSError, ValueError):
pass
return info
def sample(self):
"""Text from the newest checkpoint, regenerated only when the checkpoint changes."""
step0_path = self.run_dir / "sample_step0.txt"
step0 = step0_path.read_text(encoding="utf-8") if step0_path.exists() else None
prompt = self.about()["prompt"]
if not self.last_ckpt.exists():
return {"step": None, "text": None, "step0": step0, "prompt": prompt}
key = self.last_ckpt.stat().st_mtime
with self._lock:
if self._sample["key"] != key:
import torch
from .generate import Runner
torch.set_num_threads(2)
t0 = time.time()
r = Runner(self.last_ckpt, self.data_dir / "tokenizer.json", device="cpu")
text = r.generate(prompt, max_tokens=90, temperature=0.8, top_k=50, seed=0)
self._sample = {"key": key, "body": {"step": r.ckpt["step"], "text": text,
"seconds": round(time.time() - t0, 1)}}
body = dict(self._sample["body"])
body.update(step0=step0, prompt=prompt)
return body
def serve(run_dir, ckpt_dir, data_dir, port=8777, steps=6000):
dash = Dashboard(run_dir, ckpt_dir, data_dir, steps)
class Handler(BaseHTTPRequestHandler):
def _send(self, code, body, ctype):
data = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
try:
if self.path in ("/", "/index.html"):
self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8")
elif self.path == "/api/status":
self._send(200, json.dumps(dash.status()), "application/json")
elif self.path == "/api/sample":
self._send(200, json.dumps(dash.sample()), "application/json")
else:
self._send(404, "not found", "text/plain")
except Exception as e:
self._send(500, json.dumps({"error": str(e)}), "application/json")
def log_message(self, *args):
pass # keep the terminal quiet
class Server(ThreadingHTTPServer):
allow_reuse_address = False # on Windows, True lets two servers share a port silently
try:
server = Server(("127.0.0.1", port), Handler)
except OSError:
raise SystemExit(f"port {port} is already in use; try: python -m vrel watch --port {port + 1}")
print(f"Vrel dashboard: http://127.0.0.1:{port} (Ctrl+C to stop)")
try:
server.serve_forever()
except KeyboardInterrupt:
pass123456789101112{
"name": "Vrel",
"version": "0.3.0",
"kind": "text-generator",
"entry": "vrel.generate:load",
"weights": "vrel.pt",
"tokenizer": "tokenizer.json",
"params": 13964928,
"context": 512,
"val_loss": 1.3034,
"trained_on": "TinyStories: short, simple stories written by GPT-4 (CDLA-Sharing-1.0)"
}1{"format":"vrel-bpe-1","merges":[[32,116],[104,101],[32,97],[32,115],[32,119],[256,257],[110,100],[101,100],[32,98],[256,111],[258,262],[32,104],[32,102],[105,110],[32,84],[260,97],[114,101],[105,116],[111,117],[32,108],[32,100],[32,99],[32,112],[97,121],[32,109],[101,114],[271,115],[111,109],[270,257],[32,257],[105,115],[97,114],[32,110],[105,109],[111,110],[259,97],[108,108],[105,100],[267,97],[32,103],[97,116],[269,103],[32,83],[111,116],[101,110],[97,110],[108,101],[111,114],[105,114],[101,116],[97,109],[32,72],[256,104],[32,273],[284,121],[105,103],[32,34],[105,108],[278,108],[32,269],[307,101],[111,119],[118,281],[114,105],[117,116],[32,117],[314,279],[264,101],[291,293],[273,104],[260,325],[276,279],[32,121],[32,111],[79,110],[112,112],[111,111],[32,114],[107,263],[285,114],[99,101],[32,73],[108,100],[298,257],[270,289],[267,286],[259,116],[107,101],[32,101],[99,107],[110,116],[328,274],[115,116],[318,121],[264,311],[118,101],[101,262],[117,110],[294,331],[32,290],[97,292],[319,352],[268,357],[313,121],[261,121],[32,76],[294,100],[260,101],[321,112],[271,346],[288,299],[257,114],[275,105],[329,102],[97,100],[276,111],[273,116],[115,101],[32,66],[32,77],[354,121],[300,116],[39,115],[101,115],[32,349],[308,296],[330,101],[274,338],[291,119],[268,303],[280,283],[259,104],[259,111],[372,302],[275,389],[259,257],[46,34],[99,104],[289,101],[256,394],[288,101],[288,306],[32,107],[261,272],[274,262],[397,263],[259,109],[361,359],[363,272],[264,111],[33,34],[365,263],[264,320],[84,257],[358,115],[118,263],[274,116],[270,283],[104,116],[304,100],[101,108],[264,415],[97,108],[97,343],[258,110],[283,101],[337,116],[265,111],[260,377],[293,101],[117,103],[260,104],[330,336],[32,286],[285,108],[117,101],[258,292],[430,112],[275,332],[275,111],[114,121],[32,65],[364,290],[116,281],[111,272],[105,262],[268,353],[105,292],[103,305],[306,101],[265,121],[258,115],[32,106],[258,116],[114,97],[276,293],[32,272],[444,367],[117,114],[97,345],[259,101],[265,453],[256,272],[277,296],[108,121],[332,100],[105,99],[277,383],[116,263],[371,103],[277,301],[287,107],[264,356],[261,304],[287,100],[63,34],[101,99],[322,263],[39,116],[119,279],[267,289],[304,108],[109,121],[295,111],[295,477],[333,111],[258,272],[257,100],[97,120],[97,269],[261,109],[275,101],[32,412],[398,110],[268,114],[257,110],[117,109],[291,100],[458,101],[405,121],[117,108],[277,108],[294,351],[299,367],[274,103],[280,301],[435,411],[434,334],[259,112],[342,287],[268,400],[104,297],[375,484],[290,101],[298,431],[264,455],[259,99],[317,110],[368,343],[97,272],[280,101],[277,287],[102,496],[323,99],[278,467],[115,425],[290,103],[416,116],[311,414],[32,382],[268,97],[368,334],[260,383],[268,523],[280,419],[111,112],[283,305],[456,101],[275,97],[114,400],[89,274],[32,87],[101,292],[374,320],[288,111],[274,373],[505,464],[287,263],[447,334],[396,119],[258,108],[105,336],[374,300],[277,445],[500,414],[97,103],[259,532],[313,263],[32,499],[258,103],[298,306],[259,279],[295,461],[264,114],[115,115],[402,356],[370,101],[297,115],[402,553],[319,263],[111,98],[105,97],[112,299],[258,475],[260,303],[552,507],[344,120],[268,441],[308,550],[300,263],[280,562],[427,296],[267,421],[332,107],[116,121],[280,117],[278,320],[490,283],[322,297],[344,349],[271,108],[277,111],[333,301],[287,110],[97,393],[32,74],[100,100],[105,101],[298,568],[105,302],[32,70],[276,513],[259,421],[97,351],[555,485],[268,108],[117,99],[110,121],[107,297],[267,541],[512,543],[534,426],[264,108],[97,98],[117,345],[117,272],[105,345],[101,112],[487,589],[44,34],[32,536],[280,121],[278,114],[105,102],[260,443],[423,107],[308,563],[272,116],[405,120],[258,535],[446,115],[274,100],[259,353],[259,119],[347,114],[97,115],[268,101],[261,110],[368,411],[375,567],[260,491],[286,104],[117,115],[331,263],[277,104],[557,115],[258,98],[301,107],[299,104],[84,289],[275,299],[84,104],[295,305],[295,299],[427,111],[256,565],[97,112],[117,348],[286,116],[489,317],[101,119],[492,112],[273,263],[602,121],[501,121],[315,116],[76,359],[262,281],[105,351],[286,101],[276,472],[333,263],[642,412],[278,623],[32,68],[280,440],[356,121],[113,117],[420,121],[489,656],[97,336],[32,118],[278,111],[614,263],[267,426],[277,515],[278,462],[329,112],[323,348],[519,445],[274,115],[117,373],[454,112],[102,439],[271,439],[475,115],[267,111],[321,110],[295,272],[572,99],[546,691],[97,687],[434,107],[293,263],[488,521],[344,296],[281,115],[607,483],[666,699],[298,111],[481,283],[375,283],[117,592],[361,659],[661,111],[387,317],[264,644],[519,697],[374,566],[278,101],[409,121],[110,110],[301,116],[276,370],[437,262],[308,286],[32,69],[448,657],[288,547],[333,353],[32,343],[273,101],[526,348],[102,101],[355,101],[695,658],[275,522],[89,379],[688,114],[632,416],[84,283],[258,109],[259,108],[117,292],[259,734],[274,114],[256,114],[259,303],[265,338],[256,419],[269,107],[717,97],[269,121],[315,521],[87,104],[259,107],[111,103],[669,580],[295,450],[280,111],[481,345],[344,590],[289,418],[295,599],[420,758],[581,393],[396,263],[302,119],[308,301],[66,320],[265,119],[103,263],[743,436],[114,111],[267,317],[342,114],[32,67],[305,439],[118,300],[32,303],[287,97],[321,663],[329,338],[103,101],[379,115],[497,111],[286,263],[454,116],[323,287],[97,348],[277,302],[102,102],[601,317],[294,262],[454,110],[398,441],[269,101],[451,110],[760,115],[97,262],[97,373],[354,575],[586,334],[307,286],[267,311],[271,116],[448,653],[102,116],[268,637],[268,105],[537,101],[256,436],[257,272],[112,108],[99,483],[32,425],[114,283],[268,461],[321,115],[264,773],[309,115],[275,654],[609,302],[118,297],[811,97],[103,436],[275,305],[396,287],[751,121],[256,119],[256,101],[32,300],[112,472],[285,470],[270,104],[264,426],[296,101],[387,515],[647,643],[681,518],[77,283],[32,619],[105,418],[342,303],[101,120],[264,121],[504,472],[435,351],[842,838],[646,115],[268,763],[276,290],[437,478],[264,579],[268,460],[268,111],[276,301],[396,318],[259,110],[109,440],[674,855],[277,283],[108,102],[105,290],[344,262],[97,107],[387,748],[272,306],[268,440],[256,418],[295,114],[289,98],[260,441],[344,774],[531,302],[497,867],[98,281],[437,747],[277,419],[708,300],[114,109],[786,301],[722,349],[303,116],[256,790],[264,117],[267,470],[280,551],[800,104],[264,370],[371,303],[39,109],[828,464],[277,117],[271,121],[76,305],[875,460],[267,783],[277,421],[284,110],[258,689],[715,870],[329,318],[740,782],[693,840],[900,888],[295,664],[277,257],[683,575],[268,306],[587,108],[618,627],[98,98],[65,115],[268,287],[32,289],[78,111],[682,334],[596,812],[275,627],[295,535],[764,334],[332,108],[680,767],[342,443],[295,108],[32,75],[344,318],[370,121],[117,787],[291,729],[277,356],[492,478],[97,313],[537,491],[883,462],[470,300],[295,932],[298,776],[313,100],[608,431],[32,673],[307,281],[107,279],[99,116],[906,303],[302,115],[278,287],[586,107],[500,104],[369,102],[337,110],[387,383],[402,595],[398,293],[105,112],[105,122],[905,359],[342,279],[864,348],[288,317],[97,320],[101,109],[723,263],[259,673],[111,290],[372,121],[551,101],[116,611],[342,612],[257,115],[323,957],[694,296],[100,121],[256,450],[314,676],[490,752],[272,108],[105,518],[302,796],[967,974],[264,450],[321,346],[111,121],[97,604],[120,116],[396,981],[585,509],[771,522],[781,115],[353,603],[354,359],[333,485],[766,110],[98,101],[32,80],[342,111],[978,313],[110,297],[950,115],[559,111],[839,121],[433,263],[280,305],[105,379],[258,331],[925,121],[911,112],[711,263],[427,595],[73,116],[817,300],[112,116],[682,964],[301,101],[742,610],[927,263],[78,317],[280,541],[280,303],[272,560],[111,345],[272,101],[323,297],[295,445],[277,436],[98,121],[371,292],[452,109],[294,116],[683,300],[298,672],[801,393],[116,104],[258,100],[67,301],[361,305],[87,491],[738,425],[420,821],[72,101],[388,803],[328,928],[992,639],[115,111],[788,702],[537,104],[276,101],[592,263],[276,450],[546,1040],[463,110],[260,111],[922,962],[435,348],[405,296],[108,1002],[694,300],[102,440],[726,613],[449,101],[286,115],[286,483],[264,263],[118,377],[97,122],[268,538],[287,121],[977,351],[304,348],[304,973],[103,301],[540,665],[103,281],[487,599],[526,336],[960,1066],[692,302],[278,638],[750,296],[32,82],[98,273],[260,808],[304,263],[271,876],[302,613],[609,1077],[388,290],[825,111],[323,1054],[72,105],[409,110],[373,858],[98,302],[317,108],[264,272],[789,115],[540,1044],[443,121],[596,1052],[386,478],[285,287],[333,1082],[268,269],[76,579],[647,296],[572,809],[291,116],[66,300],[279,990],[344,121],[459,393],[726,1008],[294,115],[100,279],[278,97],[101,287],[256,1079],[308,746],[516,301],[294,819],[342,440],[277,579],[628,603],[278,739],[278,485],[109,97],[32,1013],[321,373],[442,603],[264,986],[301,779],[272,119],[417,115],[323,104],[328,538],[448,111],[601,111],[117,393],[308,114],[814,263],[570,107],[678,262],[259,297],[117,273],[116,507],[106,979],[32,741],[479,297],[1106,379],[271,273],[260,114],[865,107],[278,593],[434,604],[276,114],[285,370],[276,610],[772,301],[268,1065],[554,115],[591,111],[259,400],[259,1081],[447,107],[958,872],[97,426],[1162,414],[277,450],[333,676],[32,71],[116,297],[122,121],[264,638],[608,1017],[97,304],[788,281],[87,101],[526,118],[805,120],[827,1142],[291,262],[398,273],[333,524],[110,103],[889,319],[452,418],[943,580],[292,317],[267,443],[72,538],[1186,111],[99,491],[1178,1188],[267,531],[277,290],[296,104],[559,524],[1181,686],[303,110],[677,111],[670,111],[276,619],[285,272],[1024,1161],[329,939],[272,263],[591,455],[256,319],[517,115],[387,543],[108,263],[1003,879],[289,379],[1015,418],[570,334],[323,1067],[497,97],[1030,1060],[97,99],[851,1184],[280,980],[308,297],[740,665],[32,319],[105,686],[328,470],[629,101],[280,290],[1174,303],[1225,727],[805,272],[280,780],[596,269],[452,348],[1208,718],[555,1202],[276,286],[104,110],[264,551],[292,121],[587,338],[754,560],[267,293],[276,304],[68,290],[265,112],[278,612],[32,513],[113,431],[65,116],[1130,441],[652,281],[274,346],[276,1016],[256,818],[586,604],[87,317],[385,103],[267,353],[1133,303],[99,111],[830,286],[472,116],[288,524],[801,810],[910,109],[256,356],[259,522],[277,320],[570,436],[333,117],[1196,547],[387,111],[105,263],[267,299],[287,297],[452,370],[458,379],[755,351],[256,538],[342,531],[105,343],[65,689],[348,281],[77,484],[871,263],[1070,115],[750,121],[286,121],[880,263],[256,929],[278,975],[985,281],[762,263],[371,379],[1170,115],[276,467],[32,122],[323,108],[670,370],[98,111],[32,547],[368,290],[65,747],[358,460],[1045,119],[629,297],[1255,821],[277,565],[1214,611],[258,346],[281,263],[314,301],[609,121],[387,412],[729,272],[375,114],[1131,317],[1198,1312],[1223,305],[83,431],[97,810],[1149,336],[437,115],[1022,101],[278,1248],[607,104],[830,296],[340,478],[735,297],[970,269],[298,892],[941,115],[260,305],[311,110],[256,785],[852,336],[313,97],[260,461],[276,416],[83,306],[452,924],[115,104],[1315,346],[852,99],[490,1140],[268,739],[265,1134],[629,289],[83,257],[119,808],[264,1310],[481,292],[105,377],[107,300],[781,373],[692,338],[817,575],[277,918],[420,499],[669,352],[921,370],[456,379],[618,283],[558,1321],[996,1351],[452,1318],[111,283],[99,334],[618,269],[83,892],[271,292],[278,281],[277,114],[342,610],[355,460],[737,1061],[1048,663],[526,304],[296,281],[738,317],[83,111],[32,79],[295,509],[908,263],[275,780],[331,121],[437,292],[275,924],[878,509],[77,567],[725,994],[296,367],[278,117],[294,304],[433,297],[714,111],[258,99],[708,121],[342,101],[452,809],[258,114],[276,319],[591,1010],[408,439],[468,961],[1074,483],[97,118],[83,776],[277,863],[280,524],[937,612],[402,538],[101,101],[386,377],[497,627],[262,1122],[509,121],[323,300],[271,103],[264,273],[259,273],[462,121],[698,115],[371,297],[268,356],[275,524],[269,115],[97,102],[276,769],[452,590],[397,101],[264,287],[868,317],[260,1058],[306,379],[462,263],[857,297],[276,269],[285,338],[581,348],[276,509],[97,1285],[280,296],[889,112],[1102,440],[881,121],[260,665],[268,524],[1120,263],[640,935],[276,863],[1135,945],[260,269],[849,115],[100,281],[39,272],[277,785],[267,425],[79,939],[795,121],[866,317],[374,1395],[99,302],[807,297],[1369,102],[427,121],[631,104],[256,748],[296,859],[308,643],[777,348],[769,283],[881,935],[1132,269],[105,120],[73,110],[1213,639],[504,108],[278,300],[629,306],[1311,263],[1382,290],[631,611],[1001,302],[32,351],[343,121],[487,803],[552,1209],[1397,1270],[114,263],[278,746],[952,263],[299,116],[1240,580],[559,499],[271,411],[317,281],[512,1063],[1408,460],[416,121],[610,121],[1176,263],[274,112],[940,303],[259,611],[258,876],[277,272],[295,1432],[396,348],[456,300],[350,1069],[707,478],[109,301],[546,509],[640,1171],[1200,263],[593,338],[264,763],[854,317],[259,305],[437,689],[1191,116],[1404,121],[100,115],[32,1090],[278,299],[308,1018],[280,287],[308,1128],[1335,115],[319,379],[647,286],[295,619],[271,658],[514,115],[674,1141],[954,263],[1401,102],[284,272],[754,1381],[112,101],[412,104],[448,566],[504,299],[534,262],[581,115],[79,104],[100,101],[652,101],[74,111],[277,1249],[559,301],[608,455],[280,1539],[258,304],[280,1057],[941,518],[1091,861],[1454,302],[256,524],[766,281],[287,116],[458,296],[530,115],[264,1278],[996,343],[1009,115],[268,443],[295,377],[1216,263],[631,107],[880,115],[1121,116],[114,317],[366,1433],[280,1472],[278,296],[692,639],[111,1236],[285,1520],[328,1112],[108,99],[260,290],[122,122],[570,338],[314,718],[112,104],[456,97],[116,290],[670,1439],[68,111],[1543,462],[34,46],[678,108],[1042,296],[448,117],[726,121],[1254,299],[497,299],[333,400],[585,1347],[1596,966],[72,281],[559,550],[264,1490],[83,568],[274,110],[1147,522],[342,117],[323,101],[476,1088],[280,492],[303,109],[1535,460],[452,108],[117,263],[365,115],[1336,462],[99,121],[110,281],[264,303],[336,560],[739,121],[1341,263],[302,560],[114,299],[857,112],[66,566],[363,287],[677,286],[333,425],[769,560],[1043,613],[76,659],[756,115],[267,273],[1157,1234],[111,115],[851,120],[728,281],[102,1620],[351,115],[272,110],[105,305],[286,439],[288,652],[427,727],[608,643],[259,1094],[387,1272],[276,436],[865,334],[937,1641],[1645,305],[301,336],[947,521],[259,425],[264,1090],[470,115],[1029,121],[1224,1280],[487,103],[263,969],[398,297],[515,346],[598,509],[259,1331],[570,565],[361,1334],[1519,269],[1157,101],[375,1105],[1530,116],[705,290],[1468,795],[344,109],[1220,318],[295,105],[32,1245],[77,1105],[456,99],[72,286],[1627,273],[344,108],[259,1642],[934,104],[452,672],[295,117],[452,115],[487,1425],[278,1662],[372,300],[408,1586],[448,287],[1099,1058],[371,1501],[1118,1000],[278,708],[300,336],[591,300],[70,812],[850,297],[265,1110],[1681,373],[270,111],[301,103],[306,112],[1435,1617],[1678,623],[363,1579],[437,116],[1375,121],[505,116],[1360,782],[296,263],[402,1559],[750,595],[1021,297],[268,454],[354,300],[323,590],[105,272],[949,115],[103,103],[260,637],[1667,1613],[678,269],[278,311],[681,1638],[1447,1640],[1462,1259],[363,292],[559,513],[269,263],[277,317],[70,269],[581,100],[277,1457],[585,1141],[344,302],[393,918],[701,297],[268,1514],[1547,1234],[1160,115],[122,101],[1319,115],[638,263],[1373,297],[449,116],[458,1480],[725,115],[264,1604],[722,109],[264,1192],[291,1180],[101,370],[1135,317],[1182,1489],[348,1754],[1565,263],[101,98],[259,1738],[607,507],[278,785],[1151,746],[1224,1483],[260,563],[372,297],[771,1127],[985,263],[32,45],[74,653],[1297,470],[373,115],[772,104],[344,1721],[351,108],[1001,942],[32,90],[101,121],[105,331],[278,688],[345,305],[1349,263],[289,105],[775,1127],[303,100],[267,303],[268,1018],[1416,767],[103,121],[1549,393],[259,1500],[39,292],[328,379],[570,1521],[1015,994],[836,478],[754,1413],[277,101],[755,411],[287,109],[326,412],[1114,115],[1707,421],[1780,302],[269,297],[291,313],[311,104],[1269,379],[1695,302],[1504,296],[115,305],[275,290],[105,1089],[1074,104],[65,478],[256,1660],[344,287],[368,819],[1429,334],[1812,1497],[259,1766],[286,379],[587,296],[854,455],[1164,98],[1688,115],[102,879],[280,370],[852,1069],[903,101],[631,263],[264,727],[1099,672],[292,593],[391,292],[1166,450],[97,560],[278,305],[374,1094],[1023,115],[1045,103],[280,269],[677,443],[456,263],[109,101],[260,257],[268,301],[273,393],[504,114],[512,863],[264,1568],[280,1414],[638,104],[1851,305],[102,637],[1111,560],[105,393],[292,97],[402,111],[800,367],[278,272],[648,1167],[275,419],[280,499],[353,393],[1426,639],[629,563],[1097,116],[387,531],[99,966],[115,121],[290,115],[291,1845],[827,945],[1111,119],[1295,593],[98,317],[286,107],[345,115],[504,269],[825,1424],[1398,319],[259,117],[80,975],[538,97],[854,419],[418,1657],[587,292],[277,97],[342,795],[427,654],[559,297],[903,1308],[1615,1221],[97,331],[105,318],[115,119],[277,1195],[481,370],[988,1877],[291,345],[1878,702],[264,296],[277,1163],[420,1897],[1843,963],[280,929],[335,1088],[342,272],[1262,281],[327,115],[387,1805],[1265,101],[375,1783],[481,98],[1139,297],[264,610],[333,97],[448,101],[101,478],[278,104],[268,273],[79,75],[260,440],[265,109],[1190,263],[456,287],[640,111],[278,1494],[865,604],[1578,115],[115,99],[413,478],[1332,121],[1566,302],[280,792],[342,509],[1602,302],[275,773],[1830,373],[361,101],[1244,281],[286,97],[1048,343],[517,1623],[1295,522],[111,108],[1829,686],[264,300],[278,702],[504,111],[102,1745],[278,595],[374,117],[1169,104],[98,114],[387,579],[448,979],[1841,290],[105,301],[265,602],[311,103],[315,99],[74,455],[277,741],[374,108],[694,119],[1091,370],[1882,411],[1915,299],[540,373],[280,654],[1733,672],[304,112],[642,302],[101,543],[111,348],[387,419],[1593,547],[105,281],[268,1696],[387,114],[1257,108],[1961,483],[344,631],[450,940],[1042,1902],[1786,373],[618,566],[826,1215],[278,443],[864,318],[76,1334],[306,97],[481,1538],[517,436],[302,109],[353,97],[830,643],[1965,373],[264,317],[296,303],[755,348],[943,116],[1163,121],[293,779],[1390,1383],[1989,1997],[505,115],[1584,718],[374,1885],[275,1498],[288,2005],[632,119],[387,121],[398,1057],[1737,2010],[1751,1122],[1153,115],[264,795],[275,1865],[398,727],[452,99],[1949,393],[288,320],[277,599],[280,467],[328,752],[329,98],[97,454],[260,450],[492,98],[504,467],[1076,1920],[533,109],[741,110],[1249,485],[1370,279],[1675,718],[304,1029],[364,1811],[1377,460],[448,2036],[613,352],[678,1781],[1374,518],[71,461],[735,115],[783,302],[1239,297],[105,639],[1353,297],[387,287],[742,274],[1574,1350],[2040,1110],[368,351],[1876,351],[398,1689],[657,121],[831,115],[1909,305],[2053,112],[271,114],[504,961],[766,1656],[1240,116],[1475,631],[1941,111],[256,980],[826,590],[1990,367],[296,111],[375,467],[387,652],[839,1000],[1169,121],[276,379],[540,1822],[931,418],[1390,1581],[259,602],[313,297],[1917,305],[396,345],[680,115],[103,460],[277,470],[303,115],[492,872],[264,2056],[272,370],[719,969],[1426,351],[1360,665],[281,436],[321,2087],[738,293],[267,1414],[275,832],[516,305],[370,317],[1399,318],[275,370],[304,116],[497,644],[314,1010],[538,121],[2075,379],[256,2049],[278,531],[305,281],[277,304],[496,287],[1827,818],[32,330],[259,612],[280,313],[1118,593],[2118,107],[117,346],[1267,1545],[332,112],[347,1180],[839,109],[1891,302],[2104,1452],[111,351],[282,110],[405,560],[587,318],[677,418],[952,101],[1373,263],[280,299],[361,1943],[433,518],[533,107],[587,269],[754,98],[1036,121],[1158,115],[1366,1619],[1399,351],[323,292],[315,1757],[108,297],[288,305],[1229,672],[264,301],[281,116],[591,289],[851,338],[1099,637],[1966,431],[280,590],[418,109],[1560,115],[98,356],[570,109],[772,421],[1233,1895],[259,416],[260,425],[300,115],[302,116],[504,1419],[97,302],[110,299],[331,297],[468,115],[670,752],[1204,112],[101,272],[259,426],[308,269],[466,2169],[83,611],[315,118],[866,279],[1974,121],[504,293],[775,1067],[278,1192],[437,717],[534,348],[866,2060],[1132,343],[1177,119],[903,119],[2150,301],[66,101],[857,379],[965,115],[1553,263],[2163,1855],[771,297],[1396,639],[79,102],[117,98],[786,318],[32,377],[259,892],[278,301],[271,351],[534,119],[1028,297],[1307,115],[504,101],[1859,644],[2174,348],[259,281],[280,263],[640,1127],[366,507],[591,653],[1191,1952],[866,832],[116,111],[117,112],[448,2108],[1151,492],[264,467],[276,654],[306,263],[661,2211],[1159,121],[100,779],[256,593],[448,656],[707,111],[2218,518],[101,318],[1445,297],[1921,509],[109,281],[264,509],[331,281],[385,444],[680,101],[715,676],[2230,416],[83,116],[108,1494],[640,1831],[2135,303],[100,300],[291,108],[447,104],[745,115],[826,97],[281,121],[308,945],[1306,115],[119,470],[1175,263],[1296,969],[908,942],[952,1168],[1239,2247],[1991,317],[2156,792],[374,986],[1773,2181],[269,97],[353,103],[485,263],[596,1487],[911,551],[1394,1629],[1503,115],[332,102],[332,373],[517,116],[591,443],[76,1376],[111,1365],[260,935],[531,104],[546,522],[1332,101],[1440,393],[323,861],[772,296],[1972,419],[276,105],[391,858],[1264,115],[268,302],[275,1376],[277,1629],[333,297],[391,613],[640,612],[1147,727],[1254,664],[329,774],[348,859],[456,296],[487,109],[1297,120],[83,961],[374,101],[448,752],[1043,281],[1102,303],[1542,263],[1846,416],[2226,297],[276,1128],[572,112],[2081,302],[121,470],[465,115],[1659,115],[273,121],[496,116],[1379,1834],[258,118],[511,2313],[1929,518],[1985,121],[292,111],[396,1807],[1836,1413],[1164,119],[1294,1364],[1676,2298],[2130,121],[32,78],[97,119],[109,297],[275,279],[426,103],[921,317],[2182,281],[278,455],[282,104],[755,290],[452,116],[570,604],[287,779],[311,281],[2340,790],[256,293],[262,112],[291,351],[1228,121],[2324,98],[108,664],[333,370],[355,2219],[368,729],[617,1280],[111,99],[259,741],[319,292],[84,111],[109,98],[277,2157],[742,431],[98,287],[264,550],[285,1887],[260,283],[368,803],[902,115],[1001,1976],[2365,301],[101,348],[361,1998],[375,1576],[1618,297],[2068,483],[342,613],[843,115],[1190,101],[117,672],[479,338],[537,325],[650,302],[742,653],[851,299],[270,86],[278,918],[1342,115],[303,1571],[353,107],[732,281],[75,962],[259,1134],[275,2342],[1146,297],[2345,121],[273,297],[1566,460],[1676,300],[264,97],[304,114],[305,104],[366,101],[1374,263],[1409,121],[109,377],[110,263],[291,411],[342,623],[1071,115],[1475,1464],[112,580],[303,107],[843,460],[1345,2332],[1516,1510],[1673,2410],[1883,331],[1928,1983],[278,1986],[398,612],[619,101],[828,116],[1750,336],[115,112],[287,115],[295,1389],[387,2105],[517,565],[951,101],[1166,111],[1412,115],[1635,2030],[1925,2387],[77,121],[83,672],[280,652],[337,102],[531,101],[674,509],[756,305],[256,1546],[277,274],[278,269],[632,1389],[65,262],[258,940],[267,492],[268,297],[280,1105],[290,116],[298,116],[903,281],[509,348],[582,115],[314,832],[363,861],[512,287],[101,107],[405,299],[450,560],[1673,2362],[2346,97],[2460,2459],[111,373],[298,112],[1850,263],[1898,281],[1950,290],[267,2452],[1215,263],[2249,2225],[278,741],[1409,263],[1849,279],[32,1331],[67,421],[268,419],[270,114],[280,441],[781,345],[1341,297],[1357,263],[1435,2431],[1905,281],[2417,832],[363,1272],[479,379],[677,301],[971,115],[264,589],[490,2449],[723,297],[1267,98],[118,686],[258,102],[275,792],[333,515],[387,467],[452,103],[2035,263],[276,311],[448,305],[1042,121],[281,460],[416,112],[618,299],[1294,332],[1366,336],[991,975],[1402,115],[1470,297],[2043,1778],[2172,1789],[290,379],[587,1168],[2082,1619],[110,780],[450,293],[823,1022],[1213,560],[1847,1616],[2300,290],[260,297],[284,304],[388,108],[632,305],[1810,664],[259,1245],[288,281],[1003,1016],[2494,2517],[271,787],[285,2323],[294,1180],[388,338],[534,1168],[1932,1546],[2456,102],[2528,2493],[119,101],[295,353],[489,2277],[826,2400],[1525,393],[298,532],[2038,1872],[280,286],[540,1285],[670,290],[2054,1089],[259,454],[826,302],[908,302],[1366,116],[342,296],[714,1022],[877,263],[72,2504],[335,111],[342,461],[1048,858],[462,334],[1591,547],[110,462],[268,313],[277,367],[454,373],[591,2096],[682,2563],[866,1500],[570,100],[1204,379],[280,2399],[418,107],[632,263],[985,305],[2554,431],[344,551],[450,103],[666,303],[1057,2089],[1440,439],[2243,531],[320,101],[372,281],[559,2006],[1163,281],[1364,121],[1702,453],[2189,1857],[2572,303],[328,589],[952,122],[1612,593],[289,112],[295,832],[489,1410],[640,796],[280,2037],[288,2090],[302,1956],[402,2083],[260,286],[265,785],[298,421],[386,115],[512,2580],[516,1480],[722,1858],[1798,2600],[1919,613],[1927,393],[117,336],[264,418],[504,676],[559,1853],[1220,393],[1724,464],[2241,518],[32,1419],[370,111],[632,287],[1121,464],[1407,121],[276,2586],[497,652],[629,1785],[921,1837],[1774,115],[68,370],[115,281],[258,112],[268,286],[276,637],[333,296],[1844,115],[342,304],[1060,2378],[117,418],[261,373],[287,108],[779,348],[1716,436],[299,101],[2462,263],[277,319],[301,121],[448,306],[786,287],[805,281],[375,121],[1963,1487],[342,450],[437,108],[670,1498],[1583,115],[2398,338],[2649,336],[2175,287],[2191,97],[2306,297],[32,39],[122,1168],[271,262],[281,97],[1549,1870],[1616,1460],[2113,1460],[2651,1813],[108,1639],[278,319],[581,787],[2165,664],[256,281],[271,343],[333,945],[375,1063],[1861,115],[2593,411],[114,1712],[264,419],[307,317],[908,121],[2311,2672],[99,263],[267,454],[291,102],[387,2102],[1573,263],[481,373],[1030,109],[1370,513],[264,281],[265,644],[286,112],[497,513],[693,108],[827,103],[1332,263],[2692,1528],[321,2359],[2246,2666],[2700,272],[256,377],[277,963],[398,2561],[619,102],[2477,431],[2673,319],[303,121],[329,336],[1606,908],[2710,301],[103,117],[268,2578],[276,739],[276,2259],[280,443],[427,2694],[490,653],[1394,1195],[1591,727],[121,109],[277,769],[1151,643],[276,2044],[277,652],[278,279],[282,483],[333,426],[504,2092],[628,102],[861,300],[1752,1469],[2544,1209],[2711,1195],[2714,595],[112,293],[114,566],[256,1163],[260,1848],[308,612],[423,108],[519,421],[631,112],[825,654],[1686,2421],[107,269],[267,2123],[388,652],[581,1339],[601,551],[608,1364],[1685,780],[2719,2679],[256,2732],[295,1962],[573,297],[1606,2737],[2354,1221],[2505,1259],[333,104],[492,1871],[497,2762],[678,303],[943,1623],[1171,115],[1233,1257],[1951,553],[2725,818],[108,97],[418,686],[512,515],[857,2115],[1468,461],[1919,2771],[2132,431],[2738,101],[258,2121],[264,790],[435,103],[487,370],[750,111],[1339,792],[295,300],[374,415],[497,279],[528,110],[1025,115],[1091,1192],[1612,484],[2750,1469],[256,2343],[444,818],[630,1088],[905,686],[1482,2793],[1523,2073],[2028,97],[99,313],[99,1350],[100,595],[116,115],[278,718],[342,319],[342,925],[677,792],[1257,2801],[1476,2799],[1927,810],[2527,101],[267,279],[387,951],[628,2783],[736,478],[1131,263],[2697,792],[2702,1858],[32,912],[447,604],[638,2638],[693,2820],[2213,462],[268,792],[268,918],[303,436],[420,2800],[608,317],[741,115],[854,1410],[1097,115],[1151,531],[1416,290],[1810,611],[1888,1259],[2723,2807],[2784,281],[2822,792],[32,51],[111,1383],[256,612],[258,592],[766,416],[826,348],[860,297],[1043,370],[1198,102],[2441,393],[2592,97],[2677,377],[2708,1089],[107,110],[265,426],[268,296],[269,418],[280,416],[311,2854],[374,1112],[435,345],[1164,1168],[1875,115],[2846,462],[2852,104],[264,2584],[272,300],[280,462],[281,818],[294,109],[373,2669],[435,373],[2546,2866],[342,2513],[572,306],[693,2851],[1102,2267],[2349,303],[103,653],[112,879],[120,1813],[338,2503],[481,287],[677,796],[775,2856],[999,418],[1036,272],[1043,348],[1302,297],[2248,370],[2803,115],[2824,637],[2861,2317],[2873,513],[104,1977],[109,305],[256,652],[267,287],[276,426],[311,483],[329,296],[342,455],[447,1081],[540,1521],[540,1871],[567,1089],[881,2258],[937,287],[1233,2876],[1602,283],[1615,832],[2031,112],[74,289],[105,1245],[301,767],[427,1857],[456,292],[2905,973],[277,1528],[295,2892],[645,478],[693,2911],[1132,1236],[2183,1489],[2836,686],[105,118],[344,2536],[430,2893],[548,603],[903,348],[275,317],[755,118],[755,819],[826,306],[1269,101],[1762,97],[2131,263],[69,349],[278,2848],[295,1140],[629,301],[1147,2643],[2027,305],[2613,1652],[2731,2244],[77,1576],[105,718],[111,262],[692,373],[960,515],[1042,595],[1471,263],[97,639],[100,302],[108,676],[121,418],[277,795],[388,345],[492,101],[534,98],[616,114],[618,279],[1467,518],[2906,297],[105,107],[301,320],[375,1994],[715,2963],[1954,1581],[2085,2952],[32,441],[103,535],[268,741],[293,377],[311,2002],[317,263],[648,115],[921,431],[1697,603],[2289,2878],[2937,287],[344,2879],[353,110],[640,1800],[738,2051],[2028,783],[267,1195],[432,2972],[479,296],[872,436],[1368,305],[1391,121],[1541,464],[2632,367],[121,297],[271,663],[277,609],[308,1065],[640,2912],[940,638],[1024,441],[2474,303],[99,283],[271,1639],[375,2646],[435,2953],[459,115],[490,524],[538,311],[775,100],[1618,263],[1618,1571],[2357,2944],[2447,281],[2981,297],[108,524],[111,338],[264,3010],[268,311],[296,379],[333,2469],[661,3006],[1215,257],[2031,639],[295,958],[333,2272],[387,792],[556,478],[566,121],[1051,115],[1204,1703],[2867,2236],[2994,269],[2995,121],[300,603],[374,114],[405,969],[921,2587],[991,101],[1269,299],[1476,603],[1476,2713],[2577,281],[99,942],[288,1610],[342,863],[427,2168],[551,379],[618,353],[695,2395],[2152,478],[3019,377],[32,281],[73,102],[278,304],[366,1759],[368,122],[504,377],[882,281],[1880,994],[2212,1221],[2358,453],[2529,664],[3042,418],[3053,579],[72,317],[256,1270],[281,112],[313,116],[490,513],[715,2238],[991,1576],[1612,2903],[2991,1510],[109,1977],[387,562],[640,2573],[827,1610],[1429,872],[1473,521],[1482,313],[2524,351],[2531,302],[2962,105],[3075,686],[269,780],[270,748],[275,1704],[304,273],[323,301],[546,3072],[893,115],[1061,101],[1061,122],[1398,1571],[1889,2997],[2044,377],[3005,575],[77,101],[288,929],[336,2166],[452,102],[574,518],[947,1757],[977,3098],[1267,1731],[1441,1771],[2294,300],[2767,318],[117,262],[295,2273],[504,3086],[512,114],[630,115],[742,657],[1309,305],[1846,296],[2111,2114],[2652,119],[3054,470],[83,2825],[97,1383],[640,117],[1824,115],[3112,305],[102,464],[117,100],[256,551],[277,532],[2451,518],[3033,513],[3120,2682],[65,272],[256,1209],[296,439],[387,440],[722,774],[1124,518],[1396,418],[1835,115],[2885,769],[87,808],[98,1207],[120,1221],[278,1016],[329,2350],[420,3141],[605,115],[692,2170],[755,1452],[1011,115],[2498,2114],[3028,302],[260,951],[260,1719],[263,1350],[363,1887],[418,115],[762,115],[1925,2073],[2344,263],[263,121],[280,531],[285,418],[313,580],[363,415],[1685,3162],[1903,439],[2025,115],[2029,3153],[2274,961],[3147,110],[97,787],[278,353],[393,1171],[827,99],[944,115],[1230,1622],[1759,450],[2023,1785],[2515,518],[2929,593],[2968,3094],[108,795],[280,293],[481,100],[601,2583],[681,1622],[960,1464],[1294,3176],[1856,263],[99,2971],[278,1960],[296,393],[299,111],[459,3065],[490,2006],[1888,287],[1890,297],[2319,2355],[3193,443],[105,111],[487,301],[746,121],[751,739],[1021,348],[1503,3172],[3190,111],[77,492],[112,379],[256,1719],[259,2897],[655,297],[825,311],[881,3066],[1204,1879],[3198,287],[111,299],[276,945],[306,2945],[433,115],[516,718],[754,336],[1243,115],[1276,115],[1462,1610],[1946,263],[3016,611],[103,297],[104,951],[259,1140],[267,1800],[322,518],[420,103],[429,3181],[561,281],[1059,1469],[1394,3189],[2286,3217],[3182,2951],[258,1044],[276,2112],[294,858],[328,2331],[379,1110],[601,1464],[618,111],[2016,263],[2209,263],[270,2265],[371,351],[410,3227],[462,116],[970,112],[1204,345],[1725,101],[1905,1308],[1950,654],[3138,121],[3203,418],[114,279],[283,379],[296,1350],[333,665],[368,1956],[375,1057],[587,348],[711,115],[1954,2662],[1982,2594],[2407,393],[3239,109],[3255,377],[256,643],[264,1419],[368,3123],[537,443],[1003,3260],[1747,462],[2671,269],[2718,1308],[32,85],[269,464],[454,686],[517,112],[859,115],[889,990],[903,652],[1043,1425],[1214,3281],[1336,524],[2855,290],[3050,631],[333,551],[342,1466],[385,2255],[405,470],[481,1545],[601,445],[814,297],[857,98],[1368,115],[3282,305],[66,1094],[256,2980],[268,2037],[275,273],[295,287],[301,1069],[308,2092],[693,3000],[1111,302],[1164,345],[1504,832],[2564,1657],[2696,1017],[3173,274],[3302,416],[3308,2115],[122,263],[259,313],[269,1063],[409,304],[435,1365],[531,470],[780,593],[840,116],[1220,336],[1750,2684],[2057,460],[2078,107],[2621,518],[2670,1743],[112,455],[117,990],[119,1759],[272,418],[277,566],[278,317],[342,1704],[354,3083],[512,2864],[540,1775],[601,1002],[1227,1510],[1624,305],[1798,3334],[1907,2301],[2078,1331],[2351,3199],[3039,269],[3231,416],[280,426],[291,2612],[434,112],[890,115],[1018,107],[1121,1167],[1405,104],[1849,297],[2162,111],[2796,115],[3335,3333],[77,1994],[277,3354],[278,657],[512,3132],[1606,969],[2328,115],[2443,115],[267,3259],[268,1389],[430,462],[504,353],[531,439],[540,100],[678,958],[809,279],[1355,281],[3370,3372],[71,664],[264,657],[273,367],[363,613],[373,492],[581,3382],[1133,296],[1702,1110],[2446,1089],[99,796],[259,302],[285,2228],[315,373],[454,297],[1530,464],[2032,1207],[106,1259],[278,2428],[368,1365],[489,2420],[546,2151],[557,297],[693,1460],[922,3081],[1159,297],[1233,3375],[2179,658],[2209,861],[2609,832],[3220,518],[3272,1460],[3358,3280],[120,121],[277,509],[320,104],[323,379],[344,2637],[387,1514],[775,1452],[861,121],[1548,263],[2579,832],[3290,281],[3305,963],[71,111],[277,796],[278,303],[387,1546],[409,272],[448,2266],[450,779],[487,3322],[581,302],[826,2424],[946,547],[1076,566],[1837,859],[2202,104],[3229,1622],[3269,1731],[3343,273],[3390,940],[99,1483],[112,281],[114,110],[260,918],[268,117],[355,379],[456,418],[504,1112],[692,3440],[693,1896],[1177,2301],[1267,1381],[1327,115],[1394,336],[1396,861],[1859,343],[2471,263],[3427,302],[99,320],[119,631],[258,281],[278,792],[291,553],[387,1896],[479,858],[531,108],[631,1772],[638,567],[872,1528],[937,273],[1379,75],[1591,637],[1624,320],[1624,3434],[2602,966],[2633,3459],[3007,3319],[3435,3467],[3460,3465],[3475,367],[74,1010],[277,306],[280,523],[286,859],[295,1112],[666,425],[755,302],[1130,599],[1422,115],[2038,290],[3197,2620],[3388,1008],[256,3332],[265,3442],[267,2828],[295,492],[333,293],[342,963],[452,112],[516,418],[530,2220],[587,1424],[614,297],[677,105],[1448,115],[1842,281],[1918,774],[2020,963],[2032,702],[2098,379],[264,739],[278,2566],[286,464],[335,98],[435,370],[695,727],[857,809],[1294,951],[1686,99],[1717,297],[1817,115],[3253,290],[275,2992],[385,1029],[486,2868],[501,551],[624,379],[827,118],[1336,1896],[1593,2228],[1945,115],[2326,1207],[2534,1980],[3151,263],[3243,3013],[70,1052],[112,287],[259,352],[259,746],[270,3026],[280,3090],[290,121],[489,299],[1501,121],[2539,305],[2551,1584],[256,928],[276,653],[288,3508],[455,305],[495,115],[593,102],[640,2273],[715,590],[720,121],[724,460],[742,3412],[771,3306],[943,562],[991,1779],[1128,2411],[1624,2166],[1762,436],[3424,393],[3481,2664],[3545,509],[32,263],[98,496],[99,1195],[118,2002],[273,418],[287,1960],[452,2255],[504,538],[526,3543],[593,119],[629,1848],[692,2423],[737,3567],[771,2334],[1271,416],[1737,3569],[3262,1063],[3472,281],[3577,3570],[3578,1652],[108,1584],[322,2969],[363,2457],[371,3586],[433,1622],[448,3549],[496,117],[677,3575],[751,269],[762,302],[849,3387],[984,281],[1625,111],[1777,1364],[2111,3568],[3473,832],[32,299],[77,928],[300,373],[496,98],[504,352],[791,2516],[906,741],[1003,769],[1573,281],[2337,963],[3602,439],[292,951],[342,3170],[505,263],[512,2168],[546,1800],[826,287],[992,351],[1475,273],[1548,297],[1747,1986],[3478,1010],[3613,531],[3622,664],[102,729],[116,105],[257,116],[308,3551],[329,861],[374,305],[496,619],[632,348],[678,334],[970,345],[1675,819],[2565,1528],[3626,101],[278,302],[298,110],[391,305],[435,3624],[448,2388],[504,443],[551,3628],[715,287],[805,3560],[1030,303],[1323,115],[1547,101],[1889,3632],[2043,418],[2054,3140],[2335,297],[3527,1221],[3645,3627],[99,421],[277,531],[277,818],[348,462],[355,336],[366,547],[456,3536],[504,3656],[670,301],[678,343],[715,2552],[970,1775],[1574,393],[2425,263],[3336,1452],[3648,818],[99,1983],[269,379],[272,924],[398,279],[466,101],[1223,1376],[1370,1010],[1492,115],[1550,1771],[1685,470],[2242,436],[2898,115],[2910,478],[3477,3660],[3503,1947],[3633,2923],[3651,2244],[3673,105],[74,443],[121,101],[277,1704],[277,1853],[328,590],[546,3675],[587,3638],[631,297],[692,942],[921,2128],[1169,966],[1398,103],[1553,595],[1579,301],[1751,359],[2162,1976],[2645,1781],[97,819],[104,462],[257,370],[267,579],[280,1568],[298,104],[320,379],[342,2766],[342,3393],[471,46],[677,425],[742,2388],[854,2706],[972,115],[1115,115],[1196,3704],[1423,115],[1482,3709],[1562,115],[1752,2777],[1842,116],[1861,112],[3687,269],[3688,418],[3695,116],[32,317],[65,108],[103,300],[110,1778],[277,1656],[289,3736],[375,492],[827,1775],[996,3690],[1482,262],[2224,718],[2418,547],[2418,1433],[3525,263],[3566,779],[100,283],[119,2411],[256,300],[264,3605],[323,305],[328,305],[678,302],[743,116],[826,109],[878,1347],[1477,112],[2132,117],[2685,436],[3723,111],[39,100],[108,1000],[259,2133],[385,107],[655,115],[1429,973],[1842,3714],[2533,297],[226,128],[259,524],[350,2641],[877,297],[1391,3458],[1458,297],[1545,348],[2221,1855],[2269,792],[2895,1339],[3589,269],[116,394],[260,2420],[264,443],[295,304],[922,289],[970,1339],[1273,297],[1451,257],[2213,418],[2840,305],[3116,2987],[3676,861],[3742,303],[71,450],[117,663],[329,107],[333,299],[387,320],[426,767],[439,110],[512,1128],[600,348],[866,1090],[1220,908],[1440,116],[1690,115],[2999,718],[3363,2747],[267,1779],[278,273],[280,935],[387,879],[638,483],[640,3738],[754,2461],[929,818],[1026,115],[2375,115],[2442,393],[3438,664],[3788,858],[269,2355],[280,1689],[336,263],[363,1807],[516,296],[711,297],[742,562],[1118,297],[1121,439],[1230,2030],[1798,2083],[1856,2877],[2206,121],[3783,1771],[3809,111],[3831,718],[73,115],[87,538],[275,2090],[361,3592],[452,318],[516,109],[545,2423],[915,281],[1302,563],[1724,1167],[1836,2461],[2033,460],[2082,3824],[2113,3041],[3052,832],[3561,101],[115,673],[264,796],[275,263],[308,3795],[309,393],[309,1088],[333,1061],[443,97],[591,419],[678,348],[755,3776],[789,302],[927,297],[940,531],[991,2839],[1297,969],[1883,3441],[2326,108],[2458,115],[3752,302],[118,3483],[273,111],[277,332],[329,3867],[361,579],[416,2252],[462,281],[512,3215],[534,2630],[608,269],[755,3854],[766,702],[883,1061],[1076,840],[1102,485],[1277,115],[1295,116],[1593,1419],[1918,665],[1982,746],[2176,604],[2761,3822],[3805,1016],[3834,281],[3884,3875],[3895,281],[68,1439],[99,297],[108,317],[110,306],[259,290],[277,3879],[295,2744],[406,46],[448,426],[481,299],[487,1464],[728,2370],[1176,297],[1441,115],[1482,348],[1574,3800],[2319,3816],[2551,3874],[3444,416],[3759,818],[3877,638],[3899,1635],[256,1568],[265,595],[278,418],[283,263],[308,2463],[454,263],[489,1017],[772,111],[883,110],[1448,263],[1903,257],[2464,1278],[2829,1743],[3030,305],[3515,2404],[3924,676],[32,311],[83,1410],[101,281],[108,332],[256,484],[268,595],[593,348],[596,111],[915,460],[937,952],[1732,115],[2029,3394],[2957,416],[3516,485],[3663,832],[3756,112],[3844,1248],[3923,116],[3938,3941],[3942,105],[116,300],[269,1466],[280,300],[291,638],[298,986],[302,262],[374,3323],[497,2200],[1353,115],[1951,343],[2206,110],[2223,297],[2550,102],[3036,870],[3046,101],[3860,303],[97,273],[294,292],[295,2722],[296,1497],[305,101],[322,281],[388,287],[452,441],[489,524],[628,1811],[775,3903],[780,2151],[854,101],[903,560],[1349,297],[1357,297],[1817,460],[1996,297],[2153,281],[2191,631],[2407,810],[3609,351],[3694,859],[3886,792],[3984,377],[77,114],[114,290],[270,3544],[276,3985],[295,303],[387,980],[437,272],[596,114],[628,103],[640,1652],[751,2051],[795,97],[866,513],[1106,101],[1379,2350],[1747,590],[1963,108],[2212,351],[2289,97],[2686,1497],[3981,3940],[82,101],[99,3604],[275,352],[295,769],[368,4021],[416,3657],[587,1257],[608,541],[715,2457],[825,477],[1525,436],[2175,2641],[2183,2133],[4026,97],[66,3692],[268,664],[277,2316],[321,114],[344,3380],[363,652],[414,2200],[452,1538],[516,2102],[588,393],[751,951],[1166,664],[1269,1775],[1903,4040],[2029,2630],[2416,879],[2742,115],[2810,1743],[3906,263],[108,3466],[118,305],[298,638],[452,336],[715,101],[1204,639],[1263,281],[1379,119],[1538,3159],[2279,593],[2756,1207],[3718,111],[3740,2437],[4007,4053],[46,46],[79,119],[276,664],[277,783],[313,299],[348,319],[636,2233],[871,297],[881,2552],[1182,782],[1269,1365],[1557,460],[1854,2159],[1946,115],[4003,3861],[260,2428],[280,1192],[377,859],[526,602],[601,741],[674,1347],[693,619],[769,1932],[772,2640],[1228,963],[1369,109],[1525,810],[1686,654]],"special":{"<|endoftext|>":4095}}123version https://git-lfs.github.com/spec/v1oid sha256:9dfaa92e7fe8cd43cf89581cc57642af7aa2204c997b33684de1c3c7855d0482size 14118720123"""Vrel: a small language model built from scratch."""
__version__ = "0.3.1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Command line: python -m vrel <command>"""
import argparseimport jsonimport mathimport shutilimport sysimport timefrom pathlib import Path
from . import __version__
ROOT = Path(__file__).resolve().parent.parentDATA = ROOT / "data"
BOOKS = {"data": DATA, "ckpt": ROOT / "checkpoints", "steps": 6000, "batch": 32, "lr": 6e-4, "warmup": 200, "eval_every": 250, "prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels", "trained_on": "public-domain books from Project Gutenberg", "model_version": "0.1.0"}STORIES = {"data": DATA / "stories", "ckpt": ROOT / "checkpoints" / "stories", "steps": 20000, "batch": 16, "lr": 8e-4, "warmup": 500, "eval_every": 500, "prompt": "Once upon a time", "dataset": "2.7 million short stories", "trained_on": "TinyStories: short, simple stories written by GPT-4 (CDLA-Sharing-1.0)", "model_version": "0.2.0"}# What each preset trains on and how, and which Vrel it makes. The model shapes themselves live in model.PRESETS.RUNS = { "small": BOOKS, # Quick tests save to their own folder so they never overwrite a real model. "tiny": {**BOOKS, "ckpt": ROOT / "checkpoints" / "tiny", "steps": 200, "eval_every": 50, "model_version": "0.1.0-tiny"}, "stories": STORIES, "stories-tiny": {**STORIES, "ckpt": ROOT / "checkpoints" / "stories-tiny", "steps": 200, "eval_every": 50, "model_version": "0.2.0-tiny"}, # Vrel 0.3: half the size of "stories", learning from the trained "stories" model as well as from the text. "mini": {**STORIES, "ckpt": ROOT / "checkpoints" / "mini", "teacher": ROOT / "checkpoints" / "stories" / "vrel.pt", "distill": 0.5, "model_version": "0.3.0"},}DEFAULT = "stories"
def cmd_prepare(a): from .data import HOST, MIRRORS, clean_all, fetch, read_book_ids
ids = read_book_ids(a.books) hosts = MIRRORS if a.mirror_only else (HOST,) + MIRRORS print(f"fetching {len(ids)} books from {' then '.join(hosts)} into {DATA / 'raw'} " "(already-downloaded books are skipped)") if not fetch(ids, DATA / "raw", delay=a.delay, hosts=hosts, timeout=a.timeout): sys.exit("download stopped early; run the same command again later (finished books are kept)") print("cleaning") clean_all(DATA / "raw", DATA / "clean")
def cmd_tokenizer(a): from .data import build_bins, tokenizer_sample from .tokenizer import Tokenizer
text = tokenizer_sample(DATA / "clean", a.sample_chars) print(f"training tokenizer on {len(text) / 1e6:.1f}M characters, vocab {a.vocab}") t0 = time.time() tok = Tokenizer.train(text, a.vocab, verbose=True) tok.save(DATA / "tokenizer.json") print(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") t0 = time.time() n_train, n_val = build_bins(DATA / "clean", tok, DATA, log=lambda s: None) chars = sum(p.stat().st_size for p in (DATA / "clean").glob("*.txt")) print(f"encoded in {time.time() - t0:.0f}s: {n_train:,} train + {n_val:,} val tokens " f"({chars / (n_train + n_val):.2f} bytes per token)")
def cmd_stories(a): from . import stories
folder = STORIES["data"] missing = [n for n, size in stories.FILES.values() if not (folder / n).exists() or (folder / n).stat().st_size != size] if missing: if not a.download: sys.exit(f"missing {', '.join(missing)} in {folder}. Run again with --download to fetch them " "(about 2.25 GB from huggingface.co).") stories.download(folder) stories.build(folder, vocab=a.vocab, sample_chars=a.sample_chars, workers=a.workers)
def cmd_bigram(a): from .bigram import bigram_loss from .data import load_bin from .tokenizer import Tokenizer
d = RUNS[a.preset]["data"] tok = Tokenizer.load(d / "tokenizer.json") loss = bigram_loss(load_bin(d / "train.bin"), load_bin(d / "val.bin"), tok.vocab_size) (d / "bigram.json").write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)})) print(json.dumps({"bigram_val_loss": round(loss, 4), "perplexity": round(math.exp(loss), 1)}))
def cmd_train(a): from .train import train
r = RUNS[a.preset] name = a.name or a.preset out_dir = r["ckpt"] if not a.name else ROOT / "checkpoints" / a.name teacher = None if a.teacher == "none" else (a.teacher or r.get("teacher")) if teacher and not Path(teacher).exists(): sys.exit(f"teacher checkpoint {teacher} not found. Train it first, or pass --teacher none.") summary = train(data_dir=r["data"], out_dir=out_dir, run_dir=ROOT / "runs" / name, preset=a.preset, steps=a.steps or r["steps"], batch_size=a.batch_size or r["batch"], lr=a.lr or r["lr"], min_lr=(a.lr or r["lr"]) / 10, warmup=r["warmup"], eval_every=a.eval_every or r["eval_every"], resume=a.resume, prompt=r["prompt"], about={"dataset": r["dataset"], "trained_on": r["trained_on"]}, teacher=teacher, distill=r.get("distill", 0.5) if a.distill is None else a.distill) print(json.dumps(summary, indent=2))
def _paths(a): r = RUNS[a.preset] return Path(a.checkpoint or r["ckpt"] / "vrel.pt"), Path(a.tokenizer or r["data"] / "tokenizer.json")
def cmd_generate(a): from .generate import Runner
ckpt, tok = _paths(a) r = Runner(ckpt, tok) sys.stdout.write(a.prompt) sys.stdout.flush()
def show(piece): sys.stdout.write(piece) sys.stdout.flush()
r.generate(a.prompt, a.max_tokens, a.temperature, a.top_k, a.seed, on_token=show) print()
def cmd_stats(a): import torch
ckpt, _ = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) params = sum(t.numel() for t in ck["model"].values() if t.dtype.is_floating_point) print(json.dumps({"config": ck["config"], "step": ck["step"], "params": params, "tokenizer": ck["tokenizer"], "summary": ck.get("extra", {})}, indent=2))
def export_dir(preset): """models/vrel-<the model's own version>, so exports of different models never overwrite each other.""" return ROOT / "models" / f"vrel-{RUNS[preset]['model_version']}"
def cmd_export(a): import torch
ckpt, tok = _paths(a) ck = torch.load(ckpt, map_location="cpu", weights_only=True) out = Path(a.out or export_dir(a.preset)) if out.exists(): shutil.rmtree(out) (out / "vrel").mkdir(parents=True) for src in (ROOT / "vrel").glob("*.py"): # self-contained: the code travels with the weights shutil.copy2(src, out / "vrel" / src.name) keep = {k: ck[k] for k in ("config", "step", "val_loss", "tokenizer", "extra")} if a.format == "int8": from .quant import quantize
keep["model_int8"] = quantize(ck["model"]) else: keep["model"] = ck["model"] torch.save(keep, out / "vrel.pt") shutil.copy2(tok, out / "tokenizer.json") extra = ck.get("extra", {}) manifest = { "name": "Vrel", "version": RUNS[a.preset]["model_version"], # the model's version, not this code's "kind": "text-generator", "entry": "vrel.generate:load", "weights": "vrel.pt", "tokenizer": "tokenizer.json", "params": extra.get("params"), "context": ck["config"]["context"], "val_loss": round(extra.get("val_loss", ck["val_loss"]), 4), "trained_on": extra.get("trained_on", RUNS[a.preset]["trained_on"]), } (out / "model.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") size = sum(p.stat().st_size for p in out.rglob("*") if p.is_file()) print(f"exported to {out} ({size / 1e6:.1f} MB)")
def cmd_watch(a): from .watch import serve
r = RUNS[a.preset] serve(ROOT / "runs" / a.preset, r["ckpt"], r["data"], port=a.port, steps=a.steps or r["steps"])
def main(argv=None): p = argparse.ArgumentParser(prog="vrel", description="Vrel: a small language model built from scratch.") p.add_argument("--version", action="version", version=f"vrel {__version__}") sub = p.add_subparsers(dest="cmd", required=True) presets = list(RUNS)
s = sub.add_parser("stories", help="build the TinyStories training data (tokenizer and token files)") s.add_argument("--download", action="store_true", help="download missing files (about 2.25 GB)") s.add_argument("--vocab", type=int, default=4096, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=20_000_000, help="characters to learn the tokenizer from") s.add_argument("--workers", type=int, default=None, help="encoding processes (default: half your CPU, max 6)") s.set_defaults(fn=cmd_stories)
s = sub.add_parser("prepare", help="download and clean the 0.1 training books") s.add_argument("--books", default=DATA / "books.txt", help="file with one Gutenberg book ID per line") s.add_argument("--delay", type=float, default=2.0, help="seconds to wait between downloads") s.add_argument("--timeout", type=float, default=60.0, help="seconds to wait on a stalled download") s.add_argument("--mirror-only", action="store_true", help="skip gutenberg.org and use only its official mirrors " "(by default the mirrors are fallbacks)") s.set_defaults(fn=cmd_prepare)
s = sub.add_parser("tokenizer", help="train the tokenizer and encode the 0.1 books into token files") s.add_argument("--vocab", type=int, default=8192, help="vocabulary size") s.add_argument("--sample-chars", type=int, default=5_000_000, help="characters of text to learn merges from") s.set_defaults(fn=cmd_tokenizer)
s = sub.add_parser("bigram", help="score the bigram baseline on the validation set") s.add_argument("--preset", choices=presets, default=DEFAULT, help="which dataset") s.set_defaults(fn=cmd_bigram)
s = sub.add_parser("train", help="train Vrel") s.add_argument("--preset", choices=presets, default=DEFAULT, help="stories (Vrel 0.2, default), mini (Vrel 0.3: half the size, learns from 0.2), small (Vrel 0.1 books), " "or a -tiny version for a quick test") s.add_argument("--steps", type=int, default=None, help="training rounds (default depends on the preset)") s.add_argument("--batch-size", type=int, default=None) s.add_argument("--lr", type=float, default=None, help="peak learning rate") s.add_argument("--eval-every", type=int, default=None) s.add_argument("--resume", action="store_true", help="continue from the preset's last.pt") s.add_argument("--teacher", default=None, help="checkpoint to learn from as well as the text (mini learns from Vrel 0.2); 'none' to skip") s.add_argument("--distill", type=float, default=None, help="share of the loss from the teacher, 0 to 1 (default 0.5)") s.add_argument("--name", default=None, help="save under runs/NAME and checkpoints/NAME instead of the preset's folders") s.set_defaults(fn=cmd_train)
s = sub.add_parser("watch", help="live training dashboard in your browser") s.add_argument("--port", type=int, default=8777) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which run to watch") s.add_argument("--steps", type=int, default=None, help="total rounds, if the run did not record it") s.set_defaults(fn=cmd_watch)
for name, fn, hlp in (("generate", cmd_generate, "write text from a prompt"), ("stats", cmd_stats, "show what is inside a checkpoint"), ("export", cmd_export, "package the model so other apps can load it")): s = sub.add_parser(name, help=hlp) s.add_argument("--preset", choices=presets, default=DEFAULT, help="which trained model") s.add_argument("--checkpoint", default=None, help="checkpoint file (default: the preset's vrel.pt)") s.add_argument("--tokenizer", default=None, help="tokenizer file (default: the preset's)") if name == "generate": s.add_argument("--prompt", default="", help="text for Vrel to continue") s.add_argument("--max-tokens", type=int, default=200) s.add_argument("--temperature", type=float, default=0.8, help="0 = always pick the likeliest token") s.add_argument("--top-k", type=int, default=50, help="only sample from the k likeliest tokens") s.add_argument("--seed", type=int, default=None, help="same seed + prompt = same text") if name == "export": s.add_argument("--out", default=None, help="output folder (default models/vrel-<model version>, such as models/vrel-0.3.0)") s.add_argument("--format", choices=("int8", "float32"), default="int8", help="int8 (default) is a quarter of the size with the same quality") s.set_defaults(fn=fn)
a = p.parse_args(argv) a.fn(a)
if __name__ == "__main__": main()12345678910111213141516171819202122232425"""Bigram baseline: predicts each token only from the one before it, by counting.
This is the simplest possible language model. Vrel has to beat it by a wide
margin for its attention layers to be worth anything.
"""
import numpy as np
def bigram_loss(train, val, vocab_size, k=0.1, chunk=50_000_000):
"""Mean negative log-probability on `val`, using add-k smoothed bigram counts from `train`."""
V = vocab_size
counts = np.zeros(V * V, dtype=np.int64)
# Count in slices so even hundreds of millions of tokens fit in memory. Each slice
# overlaps the next by one token so the pair across the boundary is counted once.
for start in range(0, max(1, len(train) - 1), chunk):
a = np.asarray(train[start:start + chunk + 1], dtype=np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V)
counts = counts.astype(np.float32).reshape(V, V)
val = np.asarray(val, dtype=np.int64)
counts += k
row_sums = counts.sum(axis=1)
a, b = val[:-1], val[1:]
logp = np.log(counts[a, b]) - np.log(row_sums[a])
return float(-logp.mean())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""Training data: fetch public-domain books, clean them, and turn them into token files."""
import http.client
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
import numpy as np
from .tokenizer import EOT
CACHE_PATH = "/cache/epub/{id}/pg{id}.txt"
# Where each server keeps a book's plain text. Paths are tried in order.
SOURCES = {
"www.gutenberg.org": [CACHE_PATH],
# Official Project Gutenberg mirror, classic layout: book 1342 lives at /1/3/4/1342/1342-0.txt
"mirrors.xmission.com": ["/gutenberg/{dirs}/{id}/{id}-0.txt", "/gutenberg/{dirs}/{id}/{id}.txt"],
# Project Gutenberg Literary Archive Foundation, same layout as the main site
"aleph.pglaf.org": [CACHE_PATH],
}
HOST = "www.gutenberg.org"
MIRRORS = ("mirrors.xmission.com", "aleph.pglaf.org")
USER_AGENT = "vrel-data-fetch/0.1"
def book_urls(host, book_id):
s = str(book_id)
dirs = "0" if len(s) == 1 else "/".join(s[:-1])
return [f"https://{host}" + p.format(id=book_id, dirs=dirs) for p in SOURCES.get(host, [CACHE_PATH])]
# The marker can wrap onto a second line ("...SHERLOCK" / "HOLMES ***"), so match up to its closing ***.
START_RE = re.compile(r"^\*\*\* ?START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^*]{0,300}\*\*\*", re.M | re.I)
END_RE = re.compile(r"^\*\*\* ?END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK.*$", re.M | re.I)
TITLE_RE = re.compile(r"^Title:\s*(.+)$", re.M)
def read_book_ids(path):
"""Parse a list file: one book ID per line, '#' starts a comment."""
ids = []
for line in Path(path).read_text(encoding="utf-8").splitlines():
line = line.split("#", 1)[0].strip()
if line:
ids.append(int(line))
return ids
def _download(url, timeout=60, attempts=5, pause=5.0, opener=urllib.request.urlopen, sleep=time.sleep):
"""Fetch `url`. If the connection drops or stalls partway, resume from the last
byte received (HTTP Range) instead of starting over, up to `attempts` tries.
Errors the server answers with (like 503 or 404) are not retried."""
data = b""
total = None
for attempt in range(1, attempts + 1):
headers = {"User-Agent": USER_AGENT}
if data:
headers["Range"] = f"bytes={len(data)}-"
try:
with opener(urllib.request.Request(url, headers=headers), timeout=timeout) as resp:
if data and resp.status != 206: # server ignored the range: start over
data = b""
if total is None and resp.headers.get("Content-Length"):
total = len(data) + int(resp.headers["Content-Length"])
while True:
chunk = resp.read(1 << 16)
if not chunk:
break
data += chunk
if total is None or len(data) >= total:
break
raise http.client.IncompleteRead(data, total - len(data))
except urllib.error.HTTPError:
raise
except (http.client.HTTPException, OSError) as e: # dropped, reset or timed out
if attempt == attempts:
raise
sleep(pause)
if not START_RE.search(data[:20000].decode("utf-8", errors="replace")):
raise ValueError("response is not a Project Gutenberg text")
return data
def fetch(ids, raw_dir, delay=2.0, hosts=(HOST,) + MIRRORS, max_failures_in_a_row=3, log=print,
download=_download, timeout=60):
"""Download each book once; files already on disk are never fetched again.
Each book is tried on `hosts` in order, so the main site is preferred and the
mirrors are fallbacks. Waits `delay` seconds after every request, success or
not. A host that fails `max_failures_in_a_row` times is dropped for the rest
of the run so no server is hammered (a plain "not found" does not count).
Returns False if every host was dropped.
"""
raw_dir = Path(raw_dir)
raw_dir.mkdir(parents=True, exist_ok=True)
live = list(hosts)
failures = {h: 0 for h in hosts}
for n, book_id in enumerate(ids, 1):
dest = raw_dir / f"{book_id}.txt"
if dest.exists():
continue
body = None
for host in list(live):
for url in book_urls(host, book_id):
try:
body = download(url, timeout=timeout)
break
except urllib.error.HTTPError as e:
if e.code == 404:
continue # this server keeps it under another name; try the next path
err = e
except Exception as e:
err = e
finally:
time.sleep(delay)
failures[host] += 1
log(f" [{n}/{len(ids)}] book {book_id} from {host}: FAILED ({err})")
if failures[host] >= max_failures_in_a_row:
live.remove(host)
log(f" {host}: {failures[host]} failures in a row, not asking it again this run")
break
if body is not None:
failures[host] = 0
dest.write_bytes(body)
log(f" [{n}/{len(ids)}] book {book_id} from {host}: {len(body) / 1e6:.2f} MB")
break
if body is None and live:
log(f" [{n}/{len(ids)}] book {book_id}: not downloaded this run")
if not live:
return False
return True
def strip_gutenberg(text):
"""Keep only the book itself: drop the Project Gutenberg header, footer and license."""
text = text.replace("\r\n", "\n").replace("\r", "\n").lstrip("")
start = START_RE.search(text)
end = END_RE.search(text)
body = text[start.end() if start else 0 : end.start() if end else len(text)]
return body.strip() + "\n"
def book_title(text):
m = TITLE_RE.search(text)
return m.group(1).strip() if m else "(unknown title)"
def clean_all(raw_dir, clean_dir, log=print):
raw_dir, clean_dir = Path(raw_dir), Path(clean_dir)
clean_dir.mkdir(parents=True, exist_ok=True)
titles = {}
for src in sorted(raw_dir.glob("*.txt"), key=lambda p: int(p.stem)):
raw = src.read_bytes().decode("utf-8", errors="replace")
body = strip_gutenberg(raw).replace(EOT, "")
(clean_dir / src.name).write_text(body, encoding="utf-8")
titles[int(src.stem)] = book_title(raw)
log(f" {src.stem}: {book_title(raw)} ({len(body) / 1e6:.2f} MB)")
return titles
def clean_books(clean_dir):
return sorted(Path(clean_dir).glob("*.txt"), key=lambda p: int(p.stem))
def tokenizer_sample(clean_dir, max_chars=5_000_000):
"""An even slice from every book, so the tokenizer learns from all authors."""
books = clean_books(clean_dir)
per_book = max_chars // max(1, len(books))
parts = []
for p in books:
text = p.read_text(encoding="utf-8")
mid = max(0, len(text) // 2 - per_book // 2)
parts.append(text[mid : mid + per_book])
return "\n".join(parts)
def build_bins(clean_dir, tok, out_dir, val_frac=0.05, log=print):
"""Encode every book. The last `val_frac` of each book becomes validation data."""
out_dir = Path(out_dir)
train_ids, val_ids = [], []
for p in clean_books(clean_dir):
text = p.read_text(encoding="utf-8")
cut = text.rfind("\n", 0, int(len(text) * (1 - val_frac)))
cut = cut if cut > 0 else int(len(text) * (1 - val_frac))
train_ids += tok.encode_ordinary(text[:cut]) + [tok.eot_id]
val_ids += tok.encode_ordinary(text[cut:]) + [tok.eot_id]
log(f" encoded {p.stem}: {len(train_ids):,} train / {len(val_ids):,} val tokens so far")
np.array(train_ids, dtype=np.uint16).tofile(out_dir / "train.bin")
np.array(val_ids, dtype=np.uint16).tofile(out_dir / "val.bin")
return len(train_ids), len(val_ids)
def load_bin(path):
return np.memmap(path, dtype=np.uint16, mode="r")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Make Vrel write: load a checkpoint and sample text one token at a time."""
import codecs
import json
import os
from pathlib import Path
import torch
from .model import Config, Vrel, softmax
from .quant import dequantize
from .tokenizer import Tokenizer
def pick_device(device=None):
if device:
return device
return "cuda" if torch.cuda.is_available() else "cpu"
def load_model(ckpt_path, device=None):
device = pick_device(device)
ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
model = Vrel(Config(**ckpt["config"])).to(device)
# Exports store 8-bit weights ("model_int8"); training checkpoints store float32 ("model").
model.load_state_dict(dequantize(ckpt["model_int8"]) if "model_int8" in ckpt else ckpt["model"])
model.eval()
return model, ckpt
@torch.no_grad()
def sample(model, tok, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
"""Continue `prompt`. Calls on_token(text) as each piece is ready; returns the new text."""
device = next(model.parameters()).device
was_training = model.training
model.eval()
ids = [tok.eot_id] + tok.encode(prompt) # start a new story, as in training
idx = torch.tensor([ids], dtype=torch.long, device=device)
gen = torch.Generator(device=device)
gen.manual_seed(seed if seed is not None else int.from_bytes(os.urandom(8), "little") >> 1)
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
out = []
def emit(piece):
if piece:
out.append(piece)
if on_token is not None:
on_token(piece)
ctx = model.cfg.context
cache, pos = None, 0
def prefill(window):
"""Fill a fresh KV cache with `window` and return the logits for the next token."""
nonlocal cache, pos
cache = model.new_cache()
pos = window.size(1)
return model(window, cache=cache, offset=0)[0][:, -1, :]
if model.v2:
next_logits = prefill(idx[:, -ctx:])
for _ in range(max_tokens):
if should_stop is not None and should_stop():
break
if model.v2:
logits = next_logits.float()
else: # 0.1 architecture: no cache, re-read the whole window every step
logits = model(idx[:, -ctx:])[0][:, -1, :].float()
if temperature <= 0:
nxt = logits.argmax(dim=-1, keepdim=True)
else:
logits = logits / temperature
if top_k and top_k < logits.size(-1):
kth = torch.topk(logits, top_k, dim=-1).values[:, -1:]
logits = logits.masked_fill(logits < kth, float("-inf"))
nxt = torch.multinomial(softmax(logits, dim=-1), 1, generator=gen)
t = int(nxt)
if t == tok.eot_id:
break
idx = torch.cat([idx, nxt], dim=1)
emit(decoder.decode(tok.token_bytes(t)))
if model.v2:
if pos + 1 > ctx: # window full: restart the cache from the most recent half
next_logits = prefill(idx[:, -(ctx // 2):])
else: # only the new token goes through the model; earlier ones come from the cache
next_logits = model(nxt, cache=cache, offset=pos)[0][:, -1, :]
pos += 1
emit(decoder.decode(b"", final=True))
model.train(was_training)
return "".join(out)
class Runner:
"""A loaded model plus its tokenizer, ready to generate."""
def __init__(self, ckpt_path, tokenizer_path, device=None):
self.device = pick_device(device)
self.model, self.ckpt = load_model(ckpt_path, self.device)
self.tok = Tokenizer.load(tokenizer_path)
if self.ckpt.get("tokenizer") and self.ckpt["tokenizer"] != self.tok.fingerprint():
raise ValueError("this tokenizer does not match the one the model was trained with")
def generate(self, prompt="", max_tokens=200, temperature=0.8, top_k=50, seed=None,
on_token=None, should_stop=None):
return sample(self.model, self.tok, prompt, max_tokens, temperature, top_k, seed, on_token, should_stop)
def load(path, device=None):
"""Entry point for the shared model contract: `path` is an exported model folder."""
path = Path(path)
manifest = json.loads((path / "model.json").read_text(encoding="utf-8"))
return Runner(path / manifest["weights"], path / manifest["tokenizer"], device=device)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366"""The Vrel transformer, written from scratch.
PyTorch supplies tensors, automatic gradients and the GPU. Every layer here
(linear, embedding, norms, attention, rotary positions, activations, dropout,
loss) is our own code built from basic tensor math.
Two architectures:
- "gpt2" (Vrel 0.1): LayerNorm, learned positions, GELU MLP, biases.
- "v2" (Vrel 0.2+): RMSNorm, rotary positions (RoPE), SwiGLU MLP, no biases,
memory-efficient attention for training and a KV cache for fast generation.
"""
import math
from dataclasses import asdict, dataclass, replace
import torch
from torch import nn
@dataclass
class Config:
vocab_size: int = 8192
context: int = 256 # how many tokens the model can see at once
n_layer: int = 6
n_head: int = 6
d_model: int = 384
dropout: float = 0.1
arch: str = "gpt2" # checkpoints saved before 0.2 have no arch field and load as gpt2
PRESETS = {
"small": Config(),
"tiny": Config(context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0),
"stories": Config(vocab_size=4096, context=512, n_layer=8, n_head=8, d_model=512, dropout=0.0, arch="v2"),
"stories-tiny": Config(vocab_size=4096, context=128, n_layer=2, n_head=2, d_model=128, dropout=0.0, arch="v2"),
# Half the size of "stories" (14.0M parameters), meant to learn from it as a teacher.
"mini": Config(vocab_size=4096, context=512, n_layer=7, n_head=6, d_model=384, dropout=0.0, arch="v2"),
}
def make_config(preset="small", **overrides):
return replace(PRESETS[preset], **overrides)
# ------------------------------------------------------------------ basic math
def softmax(x, dim=-1):
x = x - x.amax(dim=dim, keepdim=True)
e = x.exp()
return e / e.sum(dim=dim, keepdim=True)
def log_softmax(x, dim=-1):
shifted = x - x.amax(dim=dim, keepdim=True)
return shifted - shifted.exp().sum(dim=dim, keepdim=True).log()
def cross_entropy(logits, targets):
"""Average negative log-probability of the correct next token."""
logp = log_softmax(logits.float(), dim=-1)
return -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
def distill_loss(logits, teacher_logits, targets, weight):
"""Learn from the real next token and from a teacher model's guesses at the same time.
The teacher gives a full spread of likely next tokens, not just the one that happened, which is
much richer to learn from. `weight` is the share of the loss that comes from the teacher (0 to 1).
The teacher part is the KL divergence: how far our spread is from the teacher's.
"""
logp = log_softmax(logits.float(), dim=-1)
hard = -logp.gather(-1, targets.unsqueeze(-1)).squeeze(-1).mean()
if weight <= 0:
return hard
t_logp = log_softmax(teacher_logits.float(), dim=-1)
kl = (t_logp.exp() * (t_logp - logp)).sum(dim=-1).mean()
return (1 - weight) * hard + weight * kl
def gelu(x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x)))
def silu(x):
return x / (1.0 + torch.exp(-x))
def dropout(x, p, training):
if not training or p == 0.0:
return x
keep = (torch.rand_like(x, dtype=torch.float32) >= p).to(x.dtype)
return x * keep / (1.0 - p)
def causal_mask(t_q, t_k, device, offset=0):
"""True where a query may NOT look: keys later than the query's own position."""
q_pos = torch.arange(t_q, device=device)[:, None] + offset
k_pos = torch.arange(t_k, device=device)[None, :]
return k_pos > q_pos
# ------------------------------------------------------------------- attention
def _acc_dtype(t):
"""Accumulate in at least 32-bit floats (64-bit stays 64-bit)."""
return torch.promote_types(t.dtype, torch.float32)
class _CausalAttention(torch.autograd.Function):
"""softmax(q k^T * scale, causal) v, without keeping the T x T grid for backward.
Forward saves only q, k, v, the output and one log-sum-exp per row. Backward
recomputes the attention weights from those, one layer at a time, so memory
for the score grid is needed for a single layer instead of every layer at once.
The gradient formulas are the standard ones for softmax attention.
"""
@staticmethod
@torch.amp.custom_fwd(device_type="cuda")
def forward(ctx, q, k, v, scale):
T = q.size(-2)
acc = _acc_dtype(q)
mask = causal_mask(T, T, q.device)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(mask, float("-inf"))
m = s.amax(dim=-1, keepdim=True)
p = (s - m).exp_()
denom = p.sum(dim=-1, keepdim=True)
lse = m + denom.log()
p = (p / denom).to(v.dtype)
y = p @ v
ctx.save_for_backward(q, k, v, y, lse)
ctx.scale = scale
return y
@staticmethod
@torch.amp.custom_bwd(device_type="cuda")
def backward(ctx, dy):
q, k, v, y, lse = ctx.saved_tensors
scale = ctx.scale
T = q.size(-2)
acc = _acc_dtype(q)
s = (q @ k.transpose(-2, -1)).to(acc) * scale
s.masked_fill_(causal_mask(T, T, q.device), float("-inf"))
p = (s - lse).exp_() # the forward's attention weights, recomputed
del s
dy = dy.to(v.dtype)
dv = p.to(v.dtype).transpose(-2, -1) @ dy
dp = (dy @ v.transpose(-2, -1)).to(acc)
row = (dy.to(acc) * y.to(acc)).sum(dim=-1, keepdim=True)
ds = (p * (dp - row) * scale).to(q.dtype)
del p, dp
dq = ds @ k
dk = ds.transpose(-2, -1) @ q
return dq, dk, dv, None
def attention(q, k, v):
return _CausalAttention.apply(q, k, v, 1.0 / math.sqrt(q.size(-1)))
def rope_tables(context, head_dim, device=None, base=10000.0):
"""cos and sin tables for rotary position encoding, shape (context, head_dim / 2)."""
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
angles = torch.outer(torch.arange(context, device=device, dtype=torch.float32), inv)
return angles.cos(), angles.sin()
def apply_rope(x, cos, sin):
"""Rotate each (first-half, second-half) pair of features by an angle that grows with position.
x: (B, H, T, hd); cos, sin: (T, hd/2). Dot products between rotated queries and keys
then depend only on how far apart two tokens are, not on where they are.
"""
half = x.size(-1) // 2
x32 = x.float()
x1, x2 = x32[..., :half], x32[..., half:]
out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
return out.to(x.dtype)
# ---------------------------------------------------------------------- layers
class Linear(nn.Module):
def __init__(self, n_in, n_out, bias=True, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n_out, n_in) * std)
self.bias = nn.Parameter(torch.zeros(n_out)) if bias else None
def forward(self, x):
y = x @ self.weight.t()
return y if self.bias is None else y + self.bias
class Embedding(nn.Module):
def __init__(self, n, d, std=0.02):
super().__init__()
self.weight = nn.Parameter(torch.randn(n, d) * std)
def forward(self, idx):
return self.weight[idx]
class LayerNorm(nn.Module):
def __init__(self, d, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.bias = nn.Parameter(torch.zeros(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
mean = x32.mean(dim=-1, keepdim=True)
var = ((x32 - mean) ** 2).mean(dim=-1, keepdim=True)
y = (x32 - mean) / torch.sqrt(var + self.eps)
return y * self.weight + self.bias
class RMSNorm(nn.Module):
"""Scale each vector to unit root-mean-square, then by a learned gain. No mean, no bias."""
def __init__(self, d, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x):
x32 = x.float()
y = x32 * torch.rsqrt((x32 * x32).mean(dim=-1, keepdim=True) + self.eps)
return (y * self.weight).to(x.dtype) if x.dtype != torch.float32 else y * self.weight
class CausalSelfAttention(nn.Module):
"""Each position looks back at itself and earlier positions, never ahead."""
def __init__(self, cfg):
super().__init__()
assert cfg.d_model % cfg.n_head == 0
self.v2 = cfg.arch == "v2"
self.n_head = cfg.n_head
bias = not self.v2
self.qkv = Linear(cfg.d_model, 3 * cfg.d_model, bias=bias)
self.proj = Linear(cfg.d_model, cfg.d_model, bias=bias, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
if not self.v2:
mask = torch.tril(torch.ones(cfg.context, cfg.context, dtype=torch.bool))
self.register_buffer("mask", mask, persistent=False)
def forward(self, x, rope=None, cache=None, offset=0):
B, T, C = x.shape
H = self.n_head
hd = C // H
q, k, v = self.qkv(x).split(C, dim=2)
q = q.view(B, T, H, hd).transpose(1, 2) # (B, H, T, hd)
k = k.view(B, T, H, hd).transpose(1, 2)
v = v.view(B, T, H, hd).transpose(1, 2)
if not self.v2:
scores = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(hd))
scores = scores.float().masked_fill(~self.mask[:T, :T], float("-inf"))
att = dropout(softmax(scores, dim=-1), self.p, self.training)
y = att.to(v.dtype) @ v
else:
cos, sin = rope
q = apply_rope(q, cos[offset:offset + T], sin[offset:offset + T])
k = apply_rope(k, cos[offset:offset + T], sin[offset:offset + T])
if cache is None:
y = attention(q, k, v)
else: # generation: attend over everything cached so far plus the new positions
if cache.get("k") is not None:
k = torch.cat([cache["k"], k], dim=2)
v = torch.cat([cache["v"], v], dim=2)
cache["k"], cache["v"] = k, v
s = (q @ k.transpose(-2, -1)).float() * (1.0 / math.sqrt(hd))
s = s.masked_fill(causal_mask(T, k.size(2), x.device, offset), float("-inf"))
y = softmax(s, dim=-1).to(v.dtype) @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return dropout(self.proj(y), self.p, self.training)
class MLP(nn.Module):
def __init__(self, cfg):
super().__init__()
self.fc = Linear(cfg.d_model, 4 * cfg.d_model)
self.proj = Linear(4 * cfg.d_model, cfg.d_model, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.proj(gelu(self.fc(x))), self.p, self.training)
class SwiGLU(nn.Module):
"""A gated MLP: one projection decides how much of another to let through."""
def __init__(self, cfg):
super().__init__()
hidden = 64 * math.ceil(8 * cfg.d_model / 3 / 64) # same parameter count as a 4x GELU MLP
self.gate = Linear(cfg.d_model, hidden, bias=False)
self.up = Linear(cfg.d_model, hidden, bias=False)
self.down = Linear(hidden, cfg.d_model, bias=False, std=0.02 / math.sqrt(2 * cfg.n_layer))
self.p = cfg.dropout
def forward(self, x):
return dropout(self.down(silu(self.gate(x)) * self.up(x)), self.p, self.training)
class Block(nn.Module):
def __init__(self, cfg):
super().__init__()
v2 = cfg.arch == "v2"
self.ln1 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.attn = CausalSelfAttention(cfg)
self.ln2 = RMSNorm(cfg.d_model) if v2 else LayerNorm(cfg.d_model)
self.mlp = SwiGLU(cfg) if v2 else MLP(cfg)
def forward(self, x, rope=None, cache=None, offset=0):
x = x + self.attn(self.ln1(x), rope, cache, offset)
x = x + self.mlp(self.ln2(x))
return x
class Vrel(nn.Module):
def __init__(self, cfg):
super().__init__()
if cfg.arch not in ("gpt2", "v2"):
raise ValueError(f"unknown architecture {cfg.arch!r}")
self.cfg = cfg
self.v2 = cfg.arch == "v2"
self.tok = Embedding(cfg.vocab_size, cfg.d_model)
if self.v2:
cos, sin = rope_tables(cfg.context, cfg.d_model // cfg.n_head)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
else:
self.pos = Embedding(cfg.context, cfg.d_model)
self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
self.ln_f = RMSNorm(cfg.d_model) if self.v2 else LayerNorm(cfg.d_model)
def forward(self, idx, targets=None, cache=None, offset=0):
"""cache: None for training, or a list (one dict per layer) for step-by-step generation.
offset: how many positions are already in the cache."""
B, T = idx.shape
if offset + T > self.cfg.context:
raise ValueError(f"sequence of {offset + T} tokens is longer than the context of {self.cfg.context}")
if cache is not None and not self.v2:
raise ValueError("the KV cache needs the v2 architecture")
x = self.tok(idx)
rope = None
if self.v2:
rope = (self.rope_cos, self.rope_sin)
else:
x = x + self.pos(torch.arange(T, device=idx.device))
x = dropout(x, self.cfg.dropout, self.training)
for i, block in enumerate(self.blocks):
x = block(x, rope, None if cache is None else cache[i], offset)
x = self.ln_f(x)
logits = x @ self.tok.weight.t() # output layer shares weights with the token embedding
loss = None
if targets is not None:
loss = cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
return logits, loss
def new_cache(self):
return [{} for _ in range(self.cfg.n_layer)]
def num_params(self):
return sum(p.numel() for p in self.parameters())
def config_dict(self):
return asdict(self.cfg)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Training helpers written from scratch: AdamW, gradient clipping, LR schedule."""
import math
import torch
class AdamW: """Adam with decoupled weight decay.
groups: list of {"params": [...], "weight_decay": float} """
def __init__(self, groups, lr=6e-4, betas=(0.9, 0.95), eps=1e-8): self.groups = [{"params": list(g["params"]), "weight_decay": g.get("weight_decay", 0.0)} for g in groups] self.lr = lr self.betas = betas self.eps = eps self.t = 0 self.m = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups] self.v = [[torch.zeros_like(p) for p in g["params"]] for g in self.groups]
def zero_grad(self): for g in self.groups: for p in g["params"]: p.grad = None
@torch.no_grad() def step(self): self.t += 1 b1, b2 = self.betas bc1 = 1.0 - b1 ** self.t bc2 = 1.0 - b2 ** self.t step_size = self.lr / bc1 for gi, g in enumerate(self.groups): wd = g["weight_decay"] for pi, p in enumerate(g["params"]): if p.grad is None: continue grad = p.grad m = self.m[gi][pi] v = self.v[gi][pi] if wd: p.mul_(1.0 - self.lr * wd) m.mul_(b1).add_(grad, alpha=1.0 - b1) v.mul_(b2).addcmul_(grad, grad, value=1.0 - b2) denom = (v.sqrt() / math.sqrt(bc2)).add_(self.eps) p.addcdiv_(m, denom, value=-step_size)
def state_dict(self): return {"t": self.t, "lr": self.lr, "m": self.m, "v": self.v}
def load_state_dict(self, state): self.t = state["t"] self.lr = state["lr"] for gi in range(len(self.groups)): for pi in range(len(self.groups[gi]["params"])): self.m[gi][pi].copy_(state["m"][gi][pi]) self.v[gi][pi].copy_(state["v"][gi][pi])
def param_groups(model, weight_decay): """Matrices get weight decay; biases and layer-norm gains do not.""" decay = [p for p in model.parameters() if p.dim() >= 2] no_decay = [p for p in model.parameters() if p.dim() < 2] return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]
@torch.no_grad()def clip_grad_norm(params, max_norm): """Scale all gradients down together if their combined length exceeds max_norm.""" grads = [p.grad for p in params if p.grad is not None] total = torch.sqrt(sum((g.float() ** 2).sum() for g in grads)) coef = torch.clamp(max_norm / (total + 1e-6), max=1.0) for g in grads: g.mul_(coef.to(g.dtype)) return total
def lr_at(step, max_lr, warmup, total, min_lr): """Linear warmup, then cosine decay from max_lr down to min_lr.""" if step < warmup: return max_lr * (step + 1) / warmup progress = min(1.0, (step - warmup) / max(1, total - warmup)) return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * progress))12345678910111213141516171819202122232425"""Store weights as 8-bit integers: a quarter of the file size, measured to change nothing you can notice.
Every row of a weight matrix gets its own scale: the row's largest absolute value maps to 127, and eachweight is rounded to the nearest of the 255 steps in between. Vectors (norm weights) are tiny, so theystay in 16-bit. When the model loads, everything is turned back into ordinary float32 numbers."""
import torch
def quantize(state): out = {} for name, t in state.items(): t = t.detach().float().cpu() if t.dim() < 2: out[name] = {"w": t.half()} continue # One 32-bit scale per row: exact enough, and so few that they cost almost nothing. scale = t.abs().amax(dim=1, keepdim=True).clamp(min=1e-12) / 127 out[name] = {"q": torch.round(t / scale).clamp(-127, 127).to(torch.int8), "s": scale} return out
def dequantize(state): return {name: d["w"].float() if "w" in d else d["q"].float() * d["s"].float() for name, d in state.items()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""The TinyStories dataset: download, clean, train the tokenizer, encode to token files.
TinyStories (roneneldan/TinyStories on Hugging Face, license CDLA-Sharing-1.0) is about2.7 million short, simple English stories written by GPT-4. Vrel only reads them: themodel and every weight in it are still trained from scratch here."""
import osimport timeimport urllib.requestfrom multiprocessing import Poolfrom pathlib import Path
import numpy as np
from .tokenizer import EOT, Tokenizer
BASE_URL = "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/"FILES = { "train": ("TinyStoriesV2-GPT4-train.txt", 2_227_753_162), "valid": ("TinyStoriesV2-GPT4-valid.txt", 22_502_601),}USER_AGENT = "vrel-data-fetch/0.2"
# Curly quotes become straight ones, so the model does not learn two spellings of every quote._TRANSLATE = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})_TRANSLATE.update({c: None for c in range(0x80, 0xA0)}) # stray control characters
def clean(text): return text.translate(_TRANSLATE).strip()
def download(folder, log=print): """Fetch the train and validation files, resuming partial downloads. Skips complete files.""" folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) for name, size in FILES.values(): dest = folder / name have = dest.stat().st_size if dest.exists() else 0 if have == size: continue req = urllib.request.Request(BASE_URL + name, headers={"User-Agent": USER_AGENT, "Range": f"bytes={have}-"}) log(f" downloading {name} ({size / 1e9:.2f} GB) ...") with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "ab" if have else "wb") as f: if have and resp.status != 206: f.truncate(0) # server ignored the resume request; start over while chunk := resp.read(1 << 20): f.write(chunk) if dest.stat().st_size != size: raise OSError(f"{name}: got {dest.stat().st_size:,} bytes, expected {size:,}; run again to resume")
def iter_stories(path, block=1 << 23): """Yield cleaned stories one at a time without reading the whole file into memory.""" buf = "" with open(path, encoding="utf-8", errors="replace") as f: while True: data = f.read(block) if not data: break buf += data parts = buf.split(EOT) buf = parts.pop() # the last piece may be cut off mid-story for p in parts: s = clean(p) if s: yield s s = clean(buf) if s: yield s
def tokenizer_sample(path, max_chars): out, n = [], 0 for s in iter_stories(path): out.append(s) n += len(s) + 1 if n >= max_chars: break return "\n".join(out)
_worker_tok = None
def _init_worker(tok_path): global _worker_tok _worker_tok = Tokenizer.load(tok_path)
def _encode_batch(stories): ids = [] for s in stories: ids.extend(_worker_tok.encode_ordinary(s)) ids.append(_worker_tok.eot_id) return np.array(ids, dtype=np.uint16)
def _batches(path, size=2000): batch = [] for s in iter_stories(path): batch.append(s) if len(batch) == size: yield batch batch = [] if batch: yield batch
def encode_file(src, dest, tok_path, workers, log=print): """Encode every story to `dest` as uint16 tokens, each story followed by the EOT token.""" t0 = time.time() n_tokens = n_stories = 0 tmp = Path(str(dest) + ".tmp") with Pool(workers, initializer=_init_worker, initargs=(str(tok_path),)) as pool, open(tmp, "wb") as f: for i, arr in enumerate(pool.imap(_encode_batch, _batches(src), chunksize=4)): arr.tofile(f) n_tokens += arr.size n_stories += 2000 if i % 100 == 0 and i: log(f" {Path(src).name}: ~{n_stories:,} stories, {n_tokens / 1e6:.0f}M tokens, {time.time() - t0:.0f}s") tmp.replace(dest) return n_tokens, time.time() - t0
def build(folder, vocab=4096, sample_chars=20_000_000, workers=None, log=print): folder = Path(folder) train_txt, valid_txt = (folder / FILES[k][0] for k in ("train", "valid")) workers = workers or max(1, min(6, (os.cpu_count() or 2) // 2)) text = tokenizer_sample(train_txt, sample_chars) log(f"training tokenizer on {len(text) / 1e6:.0f}M characters, vocab {vocab}") t0 = time.time() tok = Tokenizer.train(text, vocab) tok.save(folder / "tokenizer.json") log(f"tokenizer trained in {time.time() - t0:.0f}s, fingerprint {tok.fingerprint()}") results = {} for split, src in (("val", valid_txt), ("train", train_txt)): n, secs = encode_file(src, folder / f"{split}.bin", folder / "tokenizer.json", workers, log) chars = src.stat().st_size results[split] = n log(f"{split}: {n:,} tokens in {secs:.0f}s with {workers} workers ({chars / n:.2f} bytes per token)") return tok, results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Vrel's tokenizer: byte-level byte pair encoding (BPE), written from scratch.
Text is first split into rough word-like chunks, then each chunk is turned intoUTF-8 bytes (256 base tokens). Training repeatedly finds the most frequentadjacent pair of tokens and merges it into a new token, until the vocabularyreaches the requested size. Because everything starts from raw bytes, anystring can be encoded and decoded back exactly."""
import hashlibimport heapqimport jsonimport refrom collections import Counter, defaultdict
# Splits text into chunks that merges are not allowed to cross: contractions,# words (with one optional leading space), numbers, punctuation runs, whitespace.# Every character of the input lands in exactly one chunk.SPLIT = re.compile(r"'(?:[sdmt]|ll|ve|re)| ?[^\W\d_]+| ?\d+| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")
EOT = "<|endoftext|>" # marks the boundary between two separate documentsFORMAT = "vrel-bpe-1"
def _merge(ids, pair, new_id): """Replace every non-overlapping occurrence of `pair` in `ids` with `new_id`.""" out = [] i = 0 n = len(ids) a, b = pair while i < n: if i < n - 1 and ids[i] == a and ids[i + 1] == b: out.append(new_id) i += 2 else: out.append(ids[i]) i += 1 return out
class Tokenizer: def __init__(self, merges): self.merges = [tuple(m) for m in merges] self.ranks = {pair: i for i, pair in enumerate(self.merges)} self.vocab = [bytes([i]) for i in range(256)] for a, b in self.merges: self.vocab.append(self.vocab[a] + self.vocab[b]) self.eot_id = len(self.vocab) self.vocab_size = len(self.vocab) + 1 self._cache = {}
# ---------------------------------------------------------------- training @classmethod def train(cls, text, vocab_size=8192, verbose=False): """Learn merges from `text` until the vocabulary has `vocab_size` entries.""" n_merges = vocab_size - 256 - 1 # 256 bytes + merges + 1 special token if n_merges < 0: raise ValueError("vocab_size must be at least 257") counts = Counter(SPLIT.findall(text.replace(EOT, ""))) words = [list(w.encode("utf-8")) for w in counts] freqs = list(counts.values())
pair_counts = defaultdict(int) where = defaultdict(set) # pair -> indices of words that contain it for wi, w in enumerate(words): f = freqs[wi] for p in zip(w, w[1:]): pair_counts[p] += f where[p].add(wi)
# Max-heap of (count, pair). Entries go stale as counts change; a stale # entry is skipped when popped because a fresh one was pushed on change. heap = [(-c, p) for p, c in pair_counts.items()] heapq.heapify(heap)
merges = [] while len(merges) < n_merges and heap: negc, p = heapq.heappop(heap) c = pair_counts.get(p, 0) if c <= 0 or c != -negc: continue new_id = 256 + len(merges) merges.append(p) touched = set() for wi in where.pop(p, ()): w = words[wi] f = freqs[wi] for q in zip(w, w[1:]): pair_counts[q] -= f touched.add(q) nw = _merge(w, p, new_id) for q in zip(nw, nw[1:]): pair_counts[q] += f where[q].add(wi) touched.add(q) words[wi] = nw for q in touched: cq = pair_counts[q] if cq > 0: heapq.heappush(heap, (-cq, q)) else: pair_counts.pop(q, None) if verbose and len(merges) % 500 == 0: print(f" {len(merges)}/{n_merges} merges") return cls(merges)
# ---------------------------------------------------------------- encoding def _encode_chunk(self, chunk): ids = self._cache.get(chunk) if ids is not None: return ids ids = list(chunk.encode("utf-8")) ranks = self.ranks while len(ids) >= 2: best = None best_rank = None for p in zip(ids, ids[1:]): r = ranks.get(p) if r is not None and (best_rank is None or r < best_rank): best, best_rank = p, r if best is None: break ids = _merge(ids, best, 256 + best_rank) if len(self._cache) < 1_000_000: self._cache[chunk] = ids return ids
def encode_ordinary(self, text): """Encode text, treating any special-token text as ordinary characters.""" out = [] for chunk in SPLIT.findall(text): out.extend(self._encode_chunk(chunk)) return out
def encode(self, text): """Encode text; the literal string <|endoftext|> becomes the EOT token.""" out = [] for i, part in enumerate(text.split(EOT)): if i: out.append(self.eot_id) out.extend(self.encode_ordinary(part)) return out
# ---------------------------------------------------------------- decoding def token_bytes(self, i): return EOT.encode("utf-8") if i == self.eot_id else self.vocab[i]
def decode(self, ids): return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors="replace")
# ---------------------------------------------------------------- storage def to_json(self): return json.dumps( {"format": FORMAT, "merges": [list(m) for m in self.merges], "special": {EOT: self.eot_id}}, separators=(",", ":"), )
def save(self, path): with open(path, "w", encoding="utf-8") as f: f.write(self.to_json())
@classmethod def load(cls, path): with open(path, encoding="utf-8") as f: data = json.load(f) if data.get("format") != FORMAT: raise ValueError(f"{path} is not a {FORMAT} tokenizer file") return cls(data["merges"])
def fingerprint(self): """Short hash that identifies this exact set of merges.""" return hashlib.sha256(self.to_json().encode("utf-8")).hexdigest()[:16]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""The training loop: show Vrel real text, measure how wrong it was, nudge every weight."""
import csv
import json
import math
import time
from contextlib import nullcontext
from pathlib import Path
import numpy as np
import torch
from .data import load_bin
from .generate import load_model, sample
from .model import Vrel, distill_loss, make_config
from .optim import AdamW, clip_grad_norm, lr_at, param_groups
from .tokenizer import Tokenizer
def get_batch(data, batch_size, context, rng, device):
ix = rng.integers(0, len(data) - context - 1, size=batch_size)
x = np.stack([data[i : i + context] for i in ix]).astype(np.int64)
y = np.stack([data[i + 1 : i + 1 + context] for i in ix]).astype(np.int64)
x, y = torch.from_numpy(x), torch.from_numpy(y)
if device == "cuda":
return x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
return x.to(device), y.to(device)
def autocast(device):
return torch.autocast("cuda", dtype=torch.bfloat16) if device == "cuda" else nullcontext()
@torch.no_grad()
def full_loss(model, data, device, batch_size=64):
"""Loss over the whole of `data`, in back-to-back windows. Same answer every time."""
model.eval()
T = model.cfg.context
n = (len(data) - 1) // T
total, count = 0.0, 0
for start in range(0, n, batch_size):
rows = range(start, min(n, start + batch_size))
x = torch.from_numpy(np.stack([data[r * T : r * T + T] for r in rows]).astype(np.int64)).to(device)
y = torch.from_numpy(np.stack([data[r * T + 1 : r * T + T + 1] for r in rows]).astype(np.int64)).to(device)
with autocast(device):
_, loss = model(x, y)
total += loss.item() * len(rows)
count += len(rows)
model.train()
return total / max(1, count)
@torch.no_grad()
def quick_loss(model, data, device, batch_size, iters=20, seed=1234):
"""Loss on a fixed set of random windows, for progress logging during training."""
model.eval()
rng = np.random.default_rng(seed)
losses = []
for _ in range(iters):
x, y = get_batch(data, batch_size, model.cfg.context, rng, device)
with autocast(device):
_, loss = model(x, y)
losses.append(loss.item())
model.train()
return sum(losses) / len(losses)
def sample_text(model, tok, prompt, n=120, seed=0):
return sample(model, tok, prompt, max_tokens=n, temperature=0.8, top_k=50, seed=seed)
def save_checkpoint(path, model, opt, step, val_loss, tok, extra=None, with_optimizer=True):
state = {
"model": model.state_dict(),
"config": model.config_dict(),
"step": step,
"val_loss": val_loss,
"tokenizer": tok.fingerprint(),
"extra": extra or {},
}
if with_optimizer:
state["optimizer"] = opt.state_dict()
tmp = Path(str(path) + ".tmp")
torch.save(state, tmp)
tmp.replace(path)
def train(data_dir="data", out_dir="checkpoints", run_dir="runs", preset="small", steps=6000,
batch_size=32, lr=6e-4, min_lr=6e-5, warmup=200, weight_decay=0.1, grad_clip=1.0,
eval_every=250, seed=1337, resume=False, prompt="It was a dark and stormy night", about=None,
teacher=None, distill=0.5, log=print):
"""teacher: path to a trained checkpoint (same tokenizer) for this model to learn from as well as the
text. distill: the share of the loss that comes from the teacher's guesses."""
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_num_threads(4) # keep CPU use modest; the GPU does the heavy work
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
data_dir, out_dir, run_dir = Path(data_dir), Path(out_dir), Path(run_dir)
out_dir.mkdir(parents=True, exist_ok=True)
run_dir.mkdir(parents=True, exist_ok=True)
tok = Tokenizer.load(data_dir / "tokenizer.json")
train_data = load_bin(data_dir / "train.bin")
val_data = load_bin(data_dir / "val.bin")
cfg = make_config(preset, vocab_size=tok.vocab_size)
model = Vrel(cfg).to(device)
teach = None
if teacher:
teach, t_ck = load_model(teacher, device)
if t_ck.get("tokenizer") != tok.fingerprint():
raise ValueError("the teacher was trained with a different tokenizer")
if teach.cfg.context < cfg.context:
raise ValueError("the teacher's context is shorter than this model's")
for p in teach.parameters():
p.requires_grad_(False)
opt = AdamW(param_groups(model, weight_decay), lr=lr)
start_step, best_val = 0, math.inf
last_path, best_path = out_dir / "last.pt", out_dir / "vrel.pt"
if resume and last_path.exists():
ck = torch.load(last_path, map_location=device, weights_only=True)
model.load_state_dict(ck["model"])
opt.load_state_dict(ck["optimizer"])
start_step = ck["step"]
best_val = ck["extra"].get("best_val", math.inf)
rng = np.random.default_rng(seed + start_step)
log(f"resumed from step {start_step}")
about = dict(about or {})
if teach is not None:
about.update(teacher=str(Path(teacher).name), teacher_params=teach.num_params(), distill=distill)
run_info = {"preset": preset, "params": model.num_params(), "batch": batch_size, "context": cfg.context,
"steps": steps, "tokens_per_step": batch_size * cfg.context, "prompt": prompt, **about}
(run_dir / "run.json").write_text(json.dumps(run_info, indent=2), encoding="utf-8")
log(f"device {device}, {model.num_params():,} parameters, "
f"{len(train_data):,} train tokens, {len(val_data):,} val tokens")
log_path = run_dir / "log.csv"
new_log = not (resume and log_path.exists())
log_file = open(log_path, "w" if new_log else "a", newline="")
writer = csv.writer(log_file)
if new_log:
writer.writerow(["step", "lr", "train_loss", "val_loss", "tokens_per_s", "elapsed_s"])
if start_step == 0:
init_val = full_loss(model, val_data, device)
init_sample = sample_text(model, tok, prompt)
(run_dir / "sample_step0.txt").write_text(prompt + init_sample, encoding="utf-8")
log(f"random init: val loss {init_val:.4f} (perplexity {math.exp(init_val):,.0f})")
if device == "cuda":
torch.cuda.reset_peak_memory_stats()
t_start = time.time()
train_time = 0.0
tokens_done = 0
tokens_per_step = batch_size * cfg.context
model.train()
for step in range(start_step, steps + 1):
if step % eval_every == 0 or step == steps:
tr = quick_loss(model, train_data, device, batch_size)
va = quick_loss(model, val_data, device, batch_size)
tps = tokens_done / train_time if train_time else 0.0
writer.writerow([step, f"{opt.lr:.2e}", f"{tr:.4f}", f"{va:.4f}", f"{tps:.0f}", f"{time.time() - t_start:.1f}"])
log_file.flush()
log(f"step {step:5d} | train {tr:.4f} | val {va:.4f} | lr {opt.lr:.2e} | {tps:,.0f} tok/s")
if va < best_val:
best_val = va
save_checkpoint(best_path, model, opt, step, va, tok, with_optimizer=False)
save_checkpoint(last_path, model, opt, step, va, tok, extra={"best_val": best_val})
if step == steps:
break
opt.lr = lr_at(step, lr, warmup, steps, min_lr)
x, y = get_batch(train_data, batch_size, cfg.context, rng, device)
t0 = time.time()
with autocast(device):
if teach is None:
_, loss = model(x, y)
else:
with torch.no_grad():
t_logits, _ = teach(x)
logits, _ = model(x)
loss = distill_loss(logits, t_logits, y, distill)
loss.backward()
clip_grad_norm(model.parameters(), grad_clip)
opt.step()
opt.zero_grad()
if device == "cuda":
torch.cuda.synchronize()
train_time += time.time() - t0
tokens_done += tokens_per_step
log_file.close()
# Final, exact numbers on the best checkpoint.
best = torch.load(best_path, map_location=device, weights_only=True)
model.load_state_dict(best["model"])
final_val = full_loss(model, val_data, device)
final_sample = sample_text(model, tok, prompt)
(run_dir / "sample_final.txt").write_text(prompt + final_sample, encoding="utf-8")
summary = {
"params": model.num_params(),
"best_step": best["step"],
"val_loss": final_val,
"perplexity": math.exp(final_val),
"tokens_seen": tokens_done,
"train_seconds": train_time,
"wall_seconds": time.time() - t_start,
"tokens_per_s": tokens_done / train_time if train_time else 0.0,
"peak_gpu_mb": torch.cuda.max_memory_allocated() / 2**20 if device == "cuda" else 0.0,
}
for key in ("trained_on", "teacher", "teacher_params", "distill"):
if key in about:
summary[key] = about[key]
best["extra"] = summary
torch.save(best, best_path)
log(f"done: best step {best['step']}, val loss {final_val:.4f} (perplexity {math.exp(final_val):.1f})")
return summary123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Live training dashboard: python -m vrel watch, then open http://127.0.0.1:8777
Reads what training already writes (runs/<preset>/log.csv and run.json, and the preset's last.pt).
The "what Vrel writes right now" sample runs on the CPU so it never slows the GPU.
"""
import csv
import json
import math
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
PAGE = Path(__file__).with_name("watch.html")
DEFAULT_ABOUT = {"prompt": "It was a dark and stormy night", "dataset": "67 public-domain novels",
"params": 13891584, "batch": 32, "tokens_per_step": 32 * 256}
class Dashboard:
def __init__(self, run_dir, ckpt_dir, data_dir, steps=6000):
self.run_dir = Path(run_dir)
self.data_dir = Path(data_dir)
self.last_ckpt = Path(ckpt_dir) / "last.pt"
self.steps = steps
self.bigram = None
self._sample = {"key": None, "body": None}
self._lock = threading.Lock()
threading.Thread(target=self._load_bigram, daemon=True).start()
def _load_bigram(self):
cache = self.data_dir / "bigram.json"
try:
if cache.exists():
self.bigram = json.loads(cache.read_text())["bigram_val_loss"]
return
from .bigram import bigram_loss
from .data import load_bin
from .tokenizer import Tokenizer
tok = Tokenizer.load(self.data_dir / "tokenizer.json")
loss = bigram_loss(load_bin(self.data_dir / "train.bin"), load_bin(self.data_dir / "val.bin"),
tok.vocab_size)
cache.write_text(json.dumps({"bigram_val_loss": loss, "perplexity": math.exp(loss)}))
self.bigram = loss
except Exception:
self.bigram = None # the chart simply leaves the baseline line out
def status(self):
rows = []
log = self.run_dir / "log.csv"
if log.exists():
with open(log, newline="") as f:
for r in csv.DictReader(f):
try:
rows.append({k: float(v) for k, v in r.items()})
except (TypeError, ValueError):
pass # a row being written right now
final = self.run_dir / "sample_final.txt"
finished = final.exists() and log.exists() and final.stat().st_mtime >= log.stat().st_mtime - 5
age = time.time() - log.stat().st_mtime if log.exists() else None
state = "finished" if finished else ("training" if age is not None and age < 600 else "waiting")
about = self.about()
return {"rows": rows, "steps": about.get("steps", self.steps), "bigram": self.bigram, "state": state,
"log_age_s": age, "prompt": about["prompt"], "about": about}
def about(self):
"""What this run is: written by training to run.json (runs before 0.2 did not write one)."""
info = dict(DEFAULT_ABOUT)
try:
info.update(json.loads((self.run_dir / "run.json").read_text(encoding="utf-8")))
except (OSError, ValueError):
pass
return info
def sample(self):
"""Text from the newest checkpoint, regenerated only when the checkpoint changes."""
step0_path = self.run_dir / "sample_step0.txt"
step0 = step0_path.read_text(encoding="utf-8") if step0_path.exists() else None
prompt = self.about()["prompt"]
if not self.last_ckpt.exists():
return {"step": None, "text": None, "step0": step0, "prompt": prompt}
key = self.last_ckpt.stat().st_mtime
with self._lock:
if self._sample["key"] != key:
import torch
from .generate import Runner
torch.set_num_threads(2)
t0 = time.time()
r = Runner(self.last_ckpt, self.data_dir / "tokenizer.json", device="cpu")
text = r.generate(prompt, max_tokens=90, temperature=0.8, top_k=50, seed=0)
self._sample = {"key": key, "body": {"step": r.ckpt["step"], "text": text,
"seconds": round(time.time() - t0, 1)}}
body = dict(self._sample["body"])
body.update(step0=step0, prompt=prompt)
return body
def serve(run_dir, ckpt_dir, data_dir, port=8777, steps=6000):
dash = Dashboard(run_dir, ckpt_dir, data_dir, steps)
class Handler(BaseHTTPRequestHandler):
def _send(self, code, body, ctype):
data = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
try:
if self.path in ("/", "/index.html"):
self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8")
elif self.path == "/api/status":
self._send(200, json.dumps(dash.status()), "application/json")
elif self.path == "/api/sample":
self._send(200, json.dumps(dash.sample()), "application/json")
else:
self._send(404, "not found", "text/plain")
except Exception as e:
self._send(500, json.dumps({"error": str(e)}), "application/json")
def log_message(self, *args):
pass # keep the terminal quiet
class Server(ThreadingHTTPServer):
allow_reuse_address = False # on Windows, True lets two servers share a port silently
try:
server = Server(("127.0.0.1", port), Handler)
except OSError:
raise SystemExit(f"port {port} is already in use; try: python -m vrel watch --port {port + 1}")
print(f"Vrel dashboard: http://127.0.0.1:{port} (Ctrl+C to stop)")
try:
server.serve_forever()
except KeyboardInterrupt:
pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273---license: mitlanguage:- enpipeline_tag: text-generationtags:- from-scratch- tiny- story-generationdatasets:- roneneldan/TinyStories---
# Vrel
A small language model built from scratch by Crisp Tech. Our own tokenizer, layers, attention, optimizer andtraining loop, trained from random numbers on one RTX 4060. No pretrained weights and no outside model code.
Vrel is tiny (14 to 28 million parameters). It continues text in the style it learned and nothing more: it cannotanswer questions, follow instructions or hold a conversation. It is here to show, with real numbers, how a languagemodel is built and how it learns.
Code: [github.com/crisptech/vrel](https://github.com/crisptech/vrel) ·Run it: [Lyss](https://github.com/crisptech/lyss), our terminal studio
## Versions
Each folder is a complete, self-contained model: weights (8-bit), tokenizer, `model.json` and the Vrel code that runs it.
| Folder | Parameters | Trained on | Validation loss | Perplexity ||---|---|---|---|---|| [`0.3.0/`](0.3.0) | 14.0M | TinyStories, learning from Vrel 0.2 as a teacher | 1.303 | 3.7 || [`0.2.0/`](0.2.0) | 27.8M | TinyStories (2.7M short stories) | 1.278 | 3.6 || [`0.1.0/`](0.1.0) | 13.9M | 67 public-domain novels from Project Gutenberg | 3.637 | 38.0 |
Scores for 0.2 and 0.3 are on 27,630 held-out stories (5.58M tokens); the bigram baseline scores 3.514(perplexity 33.6). Lower is better: perplexity is roughly how many words the model is torn between.
Vrel 0.3 against 0.2: half the size, nearly the same score, and faster (148 against 139 tokens/s on an RTX 4060,170 against 126 on 4 CPU threads).
## Use it
With Lyss (needs Python and PyTorch):
```bashpipx install git+https://github.com/crisptech/lysshf download crisptechdev/vrel --include "0.3.0/*" --local-dir vrel```
Copy the `0.3.0` folder into Lyss's models folder (`lyss --help` shows where), then run `lyss`.
From Python, without Lyss:
```pythonimport syssys.path.insert(0, "vrel/0.3.0")from vrel.generate import load
model = load("vrel/0.3.0")print(model.generate("Once upon a time", max_tokens=200, seed=1))```
A Vrel 0.3 story (seed 3):
> **The dog found a box in the park.** He wanted to see what was inside. He barked and ran around the box, trying> to open it. But he couldn't get it out. Then, he saw a ball. He wanted to play with it.
## Licenses
Code and weights: MIT, Crisp Tech. Vrel 0.2 and 0.3 were trained on TinyStories (Ronen Eldan and Yuanzhi Li,2023), released under CDLA-Sharing-1.0; those stories were written by GPT-4, and Vrel learns only from the text,never from another model's weights. Vrel 0.1's books are public domain in the US.0.1.0/model.jsonAdded+12
0.1.0/tokenizer.jsonAdded+1
0.1.0/vrel.ptAdded+3
0.1.0/vrel/__init__.pyAdded+3
0.1.0/vrel/__main__.pyAdded+272
0.1.0/vrel/bigram.pyAdded+25
0.1.0/vrel/data.pyAdded+194
0.1.0/vrel/generate.pyAdded+114
0.1.0/vrel/model.pyAdded+366
0.1.0/vrel/optim.pyAdded+85
0.1.0/vrel/quant.pyAdded+25
0.1.0/vrel/stories.pyAdded+143
0.1.0/vrel/tokenizer.pyAdded+172
0.1.0/vrel/train.pyAdded+216
0.1.0/vrel/watch.pyAdded+141
0.2.0/model.jsonAdded+12
0.2.0/tokenizer.jsonAdded+1
0.2.0/vrel.ptAdded+3
0.2.0/vrel/__init__.pyAdded+3
0.2.0/vrel/__main__.pyAdded+272
0.2.0/vrel/bigram.pyAdded+25
0.2.0/vrel/data.pyAdded+194
0.2.0/vrel/generate.pyAdded+114
0.2.0/vrel/model.pyAdded+366
0.2.0/vrel/optim.pyAdded+85
0.2.0/vrel/quant.pyAdded+25
0.2.0/vrel/stories.pyAdded+143
0.2.0/vrel/tokenizer.pyAdded+172
0.2.0/vrel/train.pyAdded+216
0.2.0/vrel/watch.pyAdded+141
0.3.0/model.jsonAdded+12
0.3.0/tokenizer.jsonAdded+1
0.3.0/vrel.ptAdded+3
0.3.0/vrel/__init__.pyAdded+3
0.3.0/vrel/__main__.pyAdded+272
0.3.0/vrel/bigram.pyAdded+25
0.3.0/vrel/data.pyAdded+194
0.3.0/vrel/generate.pyAdded+114
0.3.0/vrel/model.pyAdded+366
0.3.0/vrel/optim.pyAdded+85
0.3.0/vrel/quant.pyAdded+25
0.3.0/vrel/stories.pyAdded+143
0.3.0/vrel/tokenizer.pyAdded+172
0.3.0/vrel/train.pyAdded+216
0.3.0/vrel/watch.pyAdded+141
README.mdAdded+73