{"id":16935224,"url":"https://github.com/bsmth/jeremybrain","last_synced_at":"2025-08-02T13:06:11.484Z","repository":{"id":128760346,"uuid":"75496994","full_name":"bsmth/jeremybrain","owner":"bsmth","description":"Karpathy's Char-RNN with some minor tweaks","archived":false,"fork":false,"pushed_at":"2016-12-03T23:28:05.000Z","size":28174,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-07-31T09:58:33.070Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Lua","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bsmth.png","metadata":{"files":{"readme":"README.adoc","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-12-03T19:57:27.000Z","updated_at":"2019-12-18T14:13:02.000Z","dependencies_parsed_at":"2023-04-17T12:46:17.922Z","dependency_job_id":null,"html_url":"https://github.com/bsmth/jeremybrain","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/bsmth/jeremybrain","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bsmth%2Fjeremybrain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bsmth%2Fjeremybrain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bsmth%2Fjeremybrain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bsmth%2Fjeremybrain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bsmth","download_url":"https://codeload.github.com/bsmth/jeremybrain/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bsmth%2Fjeremybrain/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268393869,"owners_count":24243314,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-02T02:00:12.353Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T20:53:59.629Z","updated_at":"2025-08-02T13:06:11.476Z","avatar_url":"https://github.com/bsmth.png","language":"Lua","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n= char-rnn\n\nOriginally forked from https://github.com/karpathy/char-rnn\n\n## Requirements\n\nThis code is written in Lua and requires [Torch](http://torch.ch/). If you're on Ubuntu, installing Torch in your home directory may look something like: \n\n```bash\n$ curl -s https://raw.githubusercontent.com/torch/ezinstall/master/install-deps | bash\n$ git clone https://github.com/torch/distro.git ~/torch --recursive\n$ cd ~/torch; \n$ ./install.sh      # and enter \"yes\" at the end to modify your bashrc\n$ source ~/.bashrc\n```\n\nSee the Torch installation documentation for more details. After Torch is installed we need to get a few more packages using [LuaRocks](https://luarocks.org/) (which already came with the Torch install). In particular:\n\n```bash\n$ luarocks install nngraph \n$ luarocks install optim\n$ luarocks install nn\n```\n\n== Usage\n\n=== Data\n\n**Your own data**: If you'd like to use your own data then create a single file `input.txt` and place it into a folder in the `data/` directory. For example, `data/some_folder/input.txt`. The first time you run the training script it will do some preprocessing and write two more convenience cache files into `data/some_folder`.\n\n**Dataset sizes**: Note that if your data is too small (1MB is already considered very small) the RNN won't learn very effectively. Remember that it has to learn everything completely from scratch. Conversely if your data is large (more than about 2MB), feel confident to increase `rnn_size` and train a bigger model (see details of training below). It will work *significantly better*. For example with 6MB you can easily go up to `rnn_size` 300 or even more. The biggest that fits on my GPU and that I've trained with this code is `rnn_size` 700 with `num_layers` 3 (2 is default).\n\n### Training\n\nStart training the model using `train.lua`. As a sanity check, to run on the included example dataset simply try:\n\n```\n$ th train.lua -gpuid -1\n```\n\nNotice that here we are setting the flag `gpuid` to -1, which tells the code to train using CPU, otherwise it defaults to GPU 0.  There are many other flags for various options. Consult `$ th train.lua -help` for comprehensive settings. Here's another example that trains a bigger network and also shows how you can run on your own custom dataset (this already assumes that `data/some_folder/input.txt` exists):\n\n```\n$ th train.lua -data_dir data/some_folder -rnn_size 512 -num_layers 2 -dropout 0.5\n```\n\n**Checkpoints.** While the model is training it will periodically write checkpoint files to the `cv` folder. The frequency with which these checkpoints are written is controlled with number of iterations, as specified with the `eval_val_every` option (e.g. if this is 1 then a checkpoint is written every iteration). The filename of these checkpoints contains a very important number: the **loss**. For example, a checkpoint with filename `lm_lstm_epoch0.95_2.0681.t7` indicates that at this point the model was on epoch 0.95 (i.e. it has almost done one full pass over the training data), and the loss on validation data was 2.0681. This number is very important because the lower it is, the better the checkpoint works. Once you start to generate data (discussed below), you will want to use the model checkpoint that reports the lowest validation loss. Notice that this might not necessarily be the last checkpoint at the end of training (due to possible overfitting).\n\nAnother important quantities to be aware of are `batch_size` (call it B), `seq_length` (call it S), and the `train_frac` and `val_frac` settings. The batch size specifies how many streams of data are processed in parallel at one time. The sequence length specifies the length of each stream, which is also the limit at which the gradients can propagate backwards in time. For example, if `seq_length` is 20, then the gradient signal will never backpropagate more than 20 time steps, and the model might not *find* dependencies longer than this length in number of characters. Thus, if you have a very difficult dataset where there are a lot of long-term dependencies you will want to increase this setting. Now, if at runtime your input text file has N characters, these first all get split into chunks of size `BxS`. These chunks then get allocated across three splits: train/val/test according to the `frac` settings. By default `train_frac` is 0.95 and `val_frac` is 0.05, which means that 95% of our data chunks will be trained on and 5% of the chunks will be used to estimate the validation loss (and hence the generalization). If your data is small, it's possible that with the default settings you'll only have very few chunks in total (for example 100). This is bad: In these cases you may want to decrease batch size or sequence length.\n\nNote that you can also initialize parameters from a previously saved checkpoint using `init_from`.\n\n### Sampling\n\nGiven a checkpoint file (such as those written to `cv`) we can generate new text. For example:\n\n```\n$ th sample.lua cv/some_checkpoint.t7 -gpuid -1\n```\n\nMake sure that if your checkpoint was trained with GPU it is also sampled from with GPU, or vice versa. Otherwise the code will (currently) complain. As with the train script, see `$ th sample.lua -help` for full options. One important one is (for example) `-length 10000` which would generate 10,000 characters (default = 2000).\n\n**Temperature**. An important parameter you may want to play with is `-temperature`, which takes a number in range \\(0, 1\\] (0 not included), default = 1. The temperature is dividing the predicted log probabilities before the Softmax, so lower temperature will cause the model to make more likely, but also more boring and conservative predictions. Higher temperatures cause the model to take more chances and increase diversity of results, but at a cost of more mistakes.\n\n**Priming**. It's also possible to prime the model with some starting text using `-primetext`. This starts out the RNN with some hardcoded characters to *warm* it up with some context before it starts generating text. E.g. a fun primetext might be `-primetext \"the meaning of life is \"`. \n\n**Training with GPU but sampling on CPU**. Right now the solution is to use the `convert_gpu_cpu_checkpoint.lua` script to convert your GPU checkpoint to a CPU checkpoint. In near future you will not have to do this explicitly. E.g.:\n\n```\n$ th convert_gpu_cpu_checkpoint.lua cv/lm_lstm_epoch30.00_1.3950.t7\n```\n\nwill create a new file `cv/lm_lstm_epoch30.00_1.3950.t7_cpu.t7` that you can use with the sample script and with `-gpuid -1` for CPU mode.\n\nHappy sampling!\n\n## Tips and Tricks\n\n### Monitoring Validation Loss vs. Training Loss\nIf you're somewhat new to Machine Learning or Neural Networks it can take a bit of expertise to get good models. The most important quantity to keep track of is the difference between your training loss (printed during training) and the validation loss (printed once in a while when the RNN is run on the validation data (by default every 1000 iterations)). In particular:\n\n- If your training loss is much lower than validation loss then this means the network might be **overfitting**. Solutions to this are to decrease your network size, or to increase dropout. For example you could try dropout of 0.5 and so on.\n- If your training/validation loss are about equal then your model is **underfitting**. Increase the size of your model (either number of layers or the raw number of neurons per layer)\n\n### Approximate number of parameters\n\nThe two most important parameters that control the model are `rnn_size` and `num_layers`. I would advise that you always use `num_layers` of either 2/3. The `rnn_size` can be adjusted based on how much data you have. The two important quantities to keep track of here are:\n\n- The number of parameters in your model. This is printed when you start training.\n- The size of your dataset. 1MB file is approximately 1 million characters.\n\n=== Best models strategy\n\nThe winning strategy to obtaining very good models (if you have the compute time) is to always err on making the network larger (as large as you're willing to wait for it to compute) and then try different dropout values (between 0,1). Whatever model has the best validation performance (the loss, written in the checkpoint filename, low is good) is the one you should use in the end.\n\nIt is very common in deep learning to run many different models with many different hyperparameter settings, and in the end take whatever checkpoint gave the best validation performance.\n\n== Additional Pointers and Acknowledgements\n\nThis code was originally based on Oxford University Machine Learning class [practical 6](https://github.com/oxford-cs-ml-2015/practical6), which is in turn based on [learning to execute](https://github.com/wojciechz/learning_to_execute) code from Wojciech Zaremba. Chunks of it were also developed in collaboration with my labmate [Justin Johnson](http://cs.stanford.edu/people/jcjohns/).\n\n== License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbsmth%2Fjeremybrain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbsmth%2Fjeremybrain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbsmth%2Fjeremybrain/lists"}