├── LICENSE ├── convert.py ├── dataset.py └── readme.md /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /convert.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | import sys 4 | input_file = 'alpaca_data_cleaned.json' 5 | output_txt_file = "alpaca_data_cleaned_for_training.txt" 6 | 7 | # Load the JSON file 8 | with open(input_file , 'r') as f: 9 | data = json.load(f) 10 | 11 | #Shuffle data 12 | random.shuffle(data) 13 | # Concatenate the records into a single string in the desired format 14 | text = '' 15 | dtext = '' 16 | q = 0 17 | basic_text='' 18 | for record in data: 19 | print(q,end='\r') 20 | q =q +1 21 | if not 'instruction' in record: 22 | continue 23 | period = "." if random.randint(0,1)==0 else "" 24 | 25 | instruction = record['instruction'] 26 | if random.randint(0,1)==0: 27 | instruction = instruction[:-1] 28 | if random.randint(0,1)==0: 29 | instruction = instruction[0].strip().lower() + instruction[1:] 30 | 31 | 32 | if random.randint(0,1)==0: 33 | 34 | text = f"user: {instruction} {record['input']}{period}\nbot: {record['output']}<|endoftext|>\n".replace('\n\n','\n').replace(" . ",'').replace(" .\n",'\n') 35 | else: 36 | text = f"user: {record['input']}. {instruction}\nbot: {record['output']}<|endoftext|>\n".replace('\n\n','\n').replace(" . ",'').replace(" .\n",'\n') 37 | d={} 38 | d['text'] = text 39 | dtext = dtext+'\n'+json.dumps(d) 40 | basic_text= basic_text+text 41 | # Print the resulting text 42 | #print(text) 43 | # write resulting text to a file 44 | #with open('output_alpaca_cleaned.jsonl', 'w') as f: 45 | # f.write(dtext) 46 | 47 | with open(output_txt_file,'w') as f: 48 | f.write(basic_text) 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | ######################################################################################################## 2 | # The RWKV Language Model - https://github.com/BlinkDL/RWKV-LM 3 | ######################################################################################################## 4 | 5 | import json, math, random, os, sys 6 | import numpy as np 7 | import torch 8 | from torch.utils.data import Dataset 9 | from pytorch_lightning.utilities import rank_zero_info 10 | from .binidx import MMapIndexedDataset 11 | from .utils import MaybeIsPrime 12 | 13 | 14 | from .utils import TOKENIZER 15 | TOKEN_MODE = "pile" 16 | WORD_NAME = [ 17 | "20B_tokenizer.json", 18 | "20B_tokenizer.json", 19 | ] # [vocab, vocab] for Pile model 20 | UNKNOWN_CHAR = None 21 | vocab_size = 50277 22 | tokenizer = TOKENIZER(WORD_NAME, UNKNOWN_CHAR=UNKNOWN_CHAR) 23 | 24 | class MyDataset(Dataset): 25 | def __init__(self, args): 26 | self.args = args 27 | self.vocab_size = args.vocab_size 28 | 29 | if args.data_type == "binidx": 30 | self.vocab_size = args.vocab_size 31 | rank_zero_info(f"Current vocab size = {self.vocab_size} (make sure it's correct)") 32 | 33 | if args.data_file.endswith('/'): 34 | d_all = [] 35 | for p in os.listdir(args.data_file): 36 | if p.endswith(".idx"): 37 | d_all += [p[:-4]] 38 | d_all.sort() 39 | rank_zero_info(d_all) 40 | exit(0) 41 | else: 42 | self.data = MMapIndexedDataset(args.data_file) 43 | self.data_size = len(self.data._bin_buffer) // 2 44 | rank_zero_info(f"Data has {self.data_size} tokens.") 45 | 46 | if args.my_qa_mask > 0: 47 | self.data_pile = MMapIndexedDataset('/fsx/BlinkDL/pile/pile_20B_tokenizer_text_document') 48 | self.data_pile_size = len(self.data_pile._bin_buffer) // 2 49 | 50 | if args.my_pile_stage > 0: 51 | # assert self.data_size == 332115325534 and self.vocab_size == 50277 52 | self.samples_per_epoch = args.epoch_steps * args.real_bsz 53 | assert self.samples_per_epoch == 40320 54 | rank_zero_info(f"########## Pile 20b-tokenized stage {args.my_pile_stage} ##########") 55 | dataset_slot = self.data_size // args.ctx_len 56 | if args.my_pile_stage != 4: 57 | assert MaybeIsPrime(args.magic_prime) 58 | assert args.magic_prime % 3 == 2 59 | assert args.magic_prime / dataset_slot > 0.99 and args.magic_prime / dataset_slot <= 1 60 | elif args.data_type == "numpy": 61 | self.data = np.load(args.data_file).astype("int") 62 | self.vocab_size = args.vocab_size 63 | rank_zero_info("Current vocab size =", self.vocab_size, "(make sure it's correct)") 64 | self.data_size = len(self.data) 65 | rank_zero_info(f"Data has {self.data_size} tokens.") 66 | elif args.data_type == "uint16": 67 | self.data = np.fromfile(args.data_file, dtype=np.uint16).astype("int32").reshape(-1, args.my_sample_len) 68 | self.vocab_size = args.vocab_size 69 | rank_zero_info("Current vocab size =", self.vocab_size, "(make sure it's correct)") 70 | self.data_size = self.data.shape[0] 71 | rank_zero_info(f"Data has {self.data_size} samples.") 72 | elif args.data_type == "wds_img": 73 | self.vocab_size = -1 74 | self.data_size = -1 75 | self.data = None 76 | self.error_count = 0 77 | else: 78 | if args.data_type == "dummy": 79 | rank_zero_info("Building dummy data...") 80 | self.data = "" 81 | for i in range(100000): 82 | aa = (i) % 10000 83 | bb = (i * i) % 10000 84 | cc = aa + bb 85 | self.data += f".{aa}+{bb}={cc}." 86 | else: 87 | self.data = tokenizer.tokenizer.encode(open(args.data_file, "r", encoding=args.data_type).read()) 88 | rank_zero_info("Building token list...") 89 | unique = sorted(list(set(self.data))) 90 | # self.vocab_size = len(unique) 91 | # rank_zero_info() 92 | # for u in unique: 93 | # print(u, end=' ') 94 | # rank_zero_info('\n\n') 95 | xx = 0 96 | xxObj = {} 97 | for u in unique: 98 | xxObj[xx] = u 99 | xx += 1 100 | # with open(f"{args.proj_dir}/vocab.json", "w", encoding="utf-16le") as vocab_file: 101 | # vocab_file.write(json.dumps(xxObj, ensure_ascii=False)) 102 | self.data_size = len(self.data) 103 | rank_zero_info(f"Data has {self.data_size} tokens, {self.vocab_size} vocab size.") 104 | # self.stoi = tokenizer.stoi #{ch: i for i, ch in enumerate(unique)} 105 | # self.itos = tokenizer.itos #{i: ch for i, ch in enumerate(unique)} 106 | 107 | def __len__(self): 108 | return self.args.epoch_steps * self.args.micro_bsz 109 | 110 | def __getitem__(self, idx): 111 | args = self.args 112 | rank = self.global_rank 113 | epoch = self.real_epoch 114 | world_size = self.world_size 115 | # print(f"epoch {epoch} idx {idx} rank {rank}/{world_size}") 116 | 117 | if args.data_type == "wds_img": 118 | def init_wds(self, bias=0): 119 | def identity(x): 120 | return x 121 | import webdataset as wds 122 | import torchvision.transforms as transforms 123 | # img_transform = transforms.Compose( 124 | # [transforms.CenterCrop(256)] 125 | # ) 126 | img_transform = transforms.Compose([ 127 | transforms.CenterCrop(512), 128 | transforms.Resize((args.my_img_size)) 129 | ]) 130 | self.data_raw = wds.WebDataset(args.data_file, resampled=True).shuffle(10000, initial=1000, rng=random.Random(epoch*100000+rank+bias*1e9)).decode("torchrgb").to_tuple("jpg", "json", "txt").map_tuple(img_transform, identity, identity) 131 | for pp in self.data_raw.pipeline: 132 | if 'Resampled' in str(pp): 133 | pp.deterministic = True 134 | def worker_seed(): 135 | return rank*100000+epoch+bias*1e9 136 | pp.worker_seed = worker_seed 137 | self.data = iter(self.data_raw) 138 | # print(f"WebDataset loaded for rank {rank} epoch {epoch}") 139 | if self.data == None: 140 | init_wds(self) 141 | trial = 0 142 | while trial < 10: 143 | try: 144 | dd = next(self.data) # jpg, json, txt 145 | break 146 | except: 147 | print(f'[dataloader error - epoch {epoch} rank {rank} - trying a new shuffle]') 148 | self.error_count += 1 149 | init_wds(self, self.error_count) 150 | trial += 1 151 | pass 152 | # print(f"epoch {epoch} idx {idx} rank {rank}/{world_size} {dd[2]}") 153 | # with open(f"sample_{rank}.txt", "a", encoding="utf-8") as tmp: 154 | # tmp.write(f"epoch {epoch} idx {idx} rank {rank}/{world_size} {int(dd[1]['key'])}\n") 155 | return dd[0], dd[2] 156 | else: 157 | if args.data_type == "uint16": 158 | i = np.random.randint(0, self.data_size-1) 159 | dix = self.data[i] 160 | x = torch.tensor(dix[:-1], dtype=torch.long) 161 | y = torch.tensor(dix[1:], dtype=torch.long) 162 | else: 163 | ctx_len = args.ctx_len 164 | req_len = ctx_len + 1 165 | magic_prime = args.magic_prime 166 | data = self.data 167 | 168 | if args.my_pile_stage > 0 and args.my_pile_stage != 4: 169 | ii = 1 + epoch * self.samples_per_epoch + (idx * world_size) + rank 170 | 171 | if args.my_qa_mask > 0: 172 | ii_orig = ii 173 | if ii % 2 == 0: 174 | ii = (ii // 2) * args.magic_prime 175 | if args.ctx_len == 1024: 176 | magic_prime = 324331313 177 | elif args.ctx_len == 2048: 178 | magic_prime = 162165671 179 | elif args.ctx_len == 4096: 180 | magic_prime = 81082817 181 | data = self.data_pile 182 | else: 183 | ii = ii // 2 184 | 185 | factor = (math.sqrt(5) - 1) / 2 186 | factor = int(magic_prime * factor) 187 | i = ((factor * ii * ii * ii) % magic_prime) * ctx_len 188 | if (args.my_qa_mask == 0) or (data == self.data_pile): 189 | i = i + args.my_pile_shift 190 | # print(f"epoch {epoch} idx {idx} rank {rank}/{world_size} ii {ii} pos {round(i / self.data_size, 3)}") 191 | else: 192 | # cheat: pick a random spot in dataset 193 | i = np.random.randint(0, self.data_size - req_len) 194 | 195 | if args.data_type == "binidx": 196 | dix = data.get(idx=0, offset=i, length=req_len).astype(int) 197 | elif args.data_type == "numpy": 198 | dix = data[i : i + req_len] 199 | else: 200 | dix = data[i : i + req_len] 201 | 202 | # dix = [self.stoi[s] for s in data[i : i + req_len]] 203 | 204 | if args.my_qa_mask == 1: 205 | if data == self.data_pile: 206 | z = [1] * ctx_len 207 | else: 208 | z = [0] * ctx_len 209 | z_sum = 0 210 | isGood = False 211 | for i in range(3, ctx_len): 212 | if dix[i] == 27 and dix[i-1] == 34 and dix[i-2] == 187 and dix[i-3] == 187: 213 | isGood = True 214 | if dix[i] == 0: 215 | isGood = False 216 | if isGood: 217 | z[i] = 1 218 | z_sum += 1 219 | if z_sum == 0: 220 | z = [1] * ctx_len 221 | i = np.random.randint(0, self.data_pile_size - req_len) 222 | dix = self.data_pile.get(idx=0, offset=i, length=req_len).astype(int) 223 | z = torch.tensor(z, dtype=torch.bfloat16) 224 | 225 | x = torch.tensor(dix[:-1], dtype=torch.long) 226 | y = torch.tensor(dix[1:], dtype=torch.long) 227 | 228 | # if ii_orig < 50: 229 | # # if rank == 1: 230 | # print('rank', rank, 'i', ii_orig, ii, i, 'x', x[:5], '...', x[-5:]) 231 | # else: 232 | # exit(0) 233 | 234 | if args.my_qa_mask == 1: 235 | return x, y, z 236 | 237 | return x, y 238 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Fine Tuning RWKV 2 | This repository contains code and instructions on how to fine tune 3 | [RWKV](https://github.com/BlinkDL/RWKV-LM) models on your data, particularly on 4 | Alpaca and its derivatives. 5 | 6 | This is a quick and dirty solution and not very optimal in many aspects. This guide will 7 | probably work on Ubuntu 22 operating systems. To my knowledge, it has not been tested on 8 | Windows, Mac OS, or other Linux operating systems. If you want to test it out on one of these systems, please report back/make a pull request with your results! 9 | 10 | # Setup 11 | ## Install CUDA drivers 12 | To speed up training, RWKV uses a CUDA kernel that is compiled just in time. In order for 13 | the kernel to be compiled, you need a CUDA toolkit and drivers for your GPU. Through (way too much) testing, we've figured out that the cuda drivers for 11.7 are compatible with everything else we're using. 14 | 15 | You can install the CUDA toolkit at https://developer.nvidia.com/cuda-11-7-0-download-archive. 16 | 17 | You can install drivers for your GPU through the driver manager on your operating system. (On Ubuntu, this can be found by typing "driver" in the application search bar.) According to [the official Nvidia documentation](https://docs.nvidia.com/deploy/cuda-compatibility/index.html#binary-compatibility__table-toolkit-driver), you need to install a driver version that is >=450.80.02*. I am using **nvidia-driver-470**. Alternatively, you can also install a driver using the command line as follows: 18 | 19 | 1. Remove your old Nvidia driver: 20 | ``` 21 | sudo apt update 22 | sudo apt remove '^nvidia' 23 | sudo apt autoremove 24 | sudo apt-get purge 'nvidia*' 25 | sudo apt autoremove 26 | ``` 27 | 2. Reboot your computer: 28 | ```sh 29 | sudo reboot 30 | ``` 31 | 3. Install the new Nvidia driver: 32 | ``` 33 | sudo apt install nvidia-driver-470 34 | ``` 35 | 4. Reboot again: 36 | ``` 37 | sudo reboot 38 | ``` 39 | 40 | ## Set up a Conda environment 41 | This is not strictly necessary, but highly recommended. Doing this will save you a lot of grief if something goes wrong in the installation process. 42 | 43 | First, install Miniconda at https://docs.conda.io/en/latest/miniconda.html. 44 | 45 | Next, create a new Conda enviornment: 46 | ``` 47 | conda create -n rwkv python=3.10 48 | ``` 49 | I recommend using Python 3.10 for your conda environment. This is what I am using, and it's the only version of Python I've tested the setup on. 50 | 51 | Finally, activate your Conda environment: 52 | ``` 53 | conda activate rwkv 54 | ``` 55 | Make sure your Conda environment is active for the rest of the steps. 56 | 57 | ## Install RWKV and dependencies 58 | ### Install RWKV 59 | Clone . 60 | ``` 61 | git clone git@github.com:Blealtan/RWKV-LM-LoRA.git 62 | ``` 63 | This uses [LoRA](https://arxiv.org/pdf/2106.09685.pdf) (small trainable weight matrices right before the attention mechanism) to fine tune the model, which has the advantage of (1) using less memory than fine tuning the model directly and (2) takes less memory to store the end result. 64 | 65 | Note: The above repository can also be used to fine tune the entire model (instead of just doing LoRA). If you're interested in this, look at the documentation/code in this repository. 66 | 67 | ### Install the dependencies 68 | Install pytorch 1.13.1+cu117. (For details, see here https://pytorch.org/get-started/previous-versions/.) 69 | ``` 70 | pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu117 71 | ``` 72 | It's very important that you install *this particular* version of Pytorch. Later versions are not compatible with pytorch_lightning. This is also the version that works with the CUDA 11.7 toolkit you installed earlier. 73 | 74 | Next, install pytorch-lightning==1.9. MAKE SURE TO INSTALL THE 1.9.x VERSION OR EARLIER. The 2.0 version does not work! Also, install DeepSpeed==0.7.0. 75 | 76 | ``` 77 | pip install pytorch-lightning==1.9 deepspeed==0.7.0 78 | ``` 79 | 80 | ### (If you want to use the LLaMA Dataset) 81 | Replace `RWKV-LM-LoRA/RWKV-v4neo/src/dataset.py` with the file `dataset.py` in this repository. I made changes so the text file can be directly loaded and pre-tokenized. This is not the best (or a very good) way to do this, but it does the job for small datasets well enough. 82 | 83 | # Usage 84 | There are two main steps to fine tune with a custom dataset. First, you need to prepare your dataset so it's in the format the fine tuner is expecting. Second, you need to actually fine tune on the dataset. 85 | 86 | The following is an account of how I did this on the LLaMa dataset. You can adapt it to your own dataset as needed. 87 | 88 | ## Prepare your data 89 | As written, the fine tuner expects a single text file as input. The script `convert.py` in this repository takes a JSON file with alpaca-style data and converts it to a *.txt file by concatenating together the questions and answers in the following format: 90 | ``` 91 | user: What are the most important values in life 92 | bot: The most important values in life are kindness 93 | <|endoftext|> 94 | user: Write an 1850-word horror story. 95 | ... 96 | ``` 97 | User input is generated by appending instruction and input (in random order, since I think that in real settings users sometimes can provide input before instruction), and adds some other minor variations. 98 | To use the script, edit this 99 | ``` 100 | input_file = 'alpaca_data_cleaned.json' 101 | output_txt_file = "alpaca_data_cleaned_for_training.txt" 102 | ``` 103 | at the beginning of the script. (TODO: If anyone feels like making a pull request for this, it would be nice to make this a command line interface. This is relatively low priority, though.) 104 | 105 | ## Running 106 | Next, we need to actually fine tune the model. Go to `RWKV-LM-LoRA/RWKV-v4neo/` and run the script `train.py` with the command `python train.py`. There are lots of different arguments you can use for training that are detailed in the given repository. 107 | 108 | Example arguments: 109 | ``` 110 | 7B, full fine tuning, all weights, needs 4 A100 80GB 111 | 112 | python3 train.py --load_model --proj_dir --data_file ./alpaca_extended.txt() --data_type utf-8 --vocab_size 50277 --ctx_len 384 --epoch_steps 600 --epoch_count 30 --epoch_begin 0 --epoch_save 1 --micro_bsz 2 --n_layer 32 --n_embd 4096 --pre_ffn 0 --head_qk 0 --lr_init 2e-5 --lr_final 5e-7 --warmup_steps 0 --beta1 0.9 --beta2 0.999 --adam_eps 1e-8 --accelerator gpu --devices 4 --precision bf16 --strategy deepspeed_stage_2 --grad_cp 1 113 | 114 | 14B (not tested!, I think that need 8 A100 to work) 115 | python3 train.py --load_model --proj_dir --data_file ./alpaca_extended.txt() --data_type utf-8 --vocab_size 50277 --ctx_len 384 --epoch_steps 600 --epoch_count 30 --epoch_begin 0 --epoch_save 1 --micro_bsz 2 --n_layer 40 --n_embd 5120 --pre_ffn 0 --head_qk 0 --lr_init 2e-5 --lr_final 5e-7 --warmup_steps 0 --beta1 0.9 --beta2 0.999 --adam_eps 1e-8 --accelerator gpu --devices 8 --precision bf16 --strategy deepspeed_stage_2 --grad_cp 1 116 | ``` 117 | Try a longer ctx_len and larger micro_bsz if you have enough combined GPU memory. 118 | 119 | You can try offloading to CPU if you have a lot of RAM - 120 | ``` 121 | --strategy deepspeed_stage_2_offload 122 | ``` 123 | That will fit into one GPU 124 | 125 | For LoRA training, add LoRA arguments, see the README of https://github.com/Blealtan/RWKV-LM-LoRA for an example. With LoRa 14B can be fine-tuned with 1 A100 GPU without offloading to CPU. 126 | 127 | ### How to choose the number of epochs 128 | An epoch is a single pass through your dataset. In practice, however, you will want to save checkpoints and log progress more often. So choose some good number of steps (I used 100 or 500) and do the following: 129 | 130 | After starting, `train.py` will print the number of tokens in your dataset. Divide that by (micro_bsz * ctx_len * epoch_steps) and you will get number of epochs needed to pass through dataset once. Adjust numbers in this equation as you see fit. 131 | 132 | # Testing Your New Model 133 | Okay, so you just fine tuned a RWKV model on a custom dataset! How can you test to see if it works? Probably the easiest way to do this is via [Rwkvstic](https://github.com/harrisonvanderbyl/rwkvstic). Go check out their repository for how to set it up. --------------------------------------------------------------------------------