├── LICENSE ├── README.md ├── cond_pretrain_second_image.PNG ├── cond_pretraining_first_image.PNG └── data-processing └── ul2-document-tagging.py /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Conditional Pretraining of Large Language Models 2 | 3 | Large language models (LLMs), such as OpenAI's ChatGPT and similar chatbot products from other organizations, have recently gained widespread adoption. These models can extend text or respond to instructions in a natural and helpful manner. Despite the core technologies behind LLMs, namely the transformer architecture and the GPT decoder-only causal language model, remaining relatively unchanged for over five years, the surge in popularity of ChatGPT can be largely attributed to recent approaches that better align the output of LLMs with users' and service providers' intentions. 4 | 5 | Two primary approaches have been employed to better align large language models with human expectations. The first is known as supervised finetuning (SFT) on natural instructions, while the second is called reinforcement learning from human feedback (RLHF). Both methods aim to improve the performance and usability of LLMs, but they differ in their implementation. SFT involves training the model using labeled datasets that contain natural instructions, which helps the model understand and respond more accurately to user queries. RLHF, on the other hand, is a technique that uses human preferences as a reward signal to fine-tune models. It involves collecting a dataset of human-written demonstrations on prompts, training supervised learning baselines, and then gathering a dataset of human-labeled comparisons between two model outputs on a larger set of prompts. A reward model (RM) is trained on this dataset to predict which output labelers would prefer, and this RM is used as a reward function to fine-tune the GPT-3 policy using the PPO algorithm. However, there is an "alignment tax" associated with this approach, which can result in worse performance in some situations. 6 | 7 |
8 | Example Image 9 | 10 | **Figure 1.** An example of document tagging on a popular user generated content website. The tags inform potential readers what kind of content will be in the text without spoiling the story. 11 |
12 | 13 | A third approach to align language models with human expectations in a more transparent and end-user controllable manner is called Conditional Pretraining. In this method, a large number of pretraining examples are tagged with labels that describe the content using human-understandable classifiers. This labeling can be performed in a mostly unsupervised fashion, utilizing encoder-only or encoder-decoder natural language understanding (NLU) machine learning models, such as the BERT or T5 family of models. Content tagging is used in nearly all human generated online information-sharing environments as a way to organize content, and help users find information most relevant to their interests. 14 | 15 | There are many widely used tags online that help categorize and filter content based on user preferences. "Suitable for work" (SFW) and "not suitable for work" (NSFW) tags are commonly found on sites like Reddit, Imgur, and various online forums. Additionally, book and movie reviews often utilize the "Spoilers" tag to indicate if the review contains information that may negatively impact the enjoyment of the content. User-generated story sites, such as Archive of Our Own (AO3) and FanFiction.net, employ diverse tags to provide clear indications of the content readers can expect within the stories (Figure 1). Furthermore, labels like G, PG, PG-13, and R, have been utilized for decades to inform users about television and movie content. 16 | 17 | By leveraging conditional pretraining, language models could be better adapted to users' interests and preferences, resulting in a more aligned and enjoyable experience. 18 | 19 | ### Converting Existing Pretraining Data into Conditional Pretraining Data 20 | 21 | The prevailing method for training LLMs involves collecting vast quantities of text from the internet and feeding this minimally processed text into the LLM. The pretraining objective is to predict the subsequent word given all prior words in the training example. Often, the text is divided in a manner that allows documents to be fragmented at any point, such as in the middle of a paragraph. These fragments are then randomly incorporated into larger batches of training examples, typically ranging from 2 to 4 million examples per training step. Although this approach has proven effective, it may not be the most optimal way to train these models. 22 | 23 |
24 | Example Image 25 | 26 | **Figure 2.** Comparison of existing LLM training strategies and the conditional pretraining approach. Theoretically every example used to train the model could be tagged. 27 |
28 | 29 | In contrast, conditional pretraining aims to prepend each training example with a set of descriptive tags and a brief synopsis that accurately represents the text in the training example (Figure 2). These tags and synopses can be efficiently generated using natural language understanding (NLU) models such as BERT or T5. Although there is considerable computational cost associated with processing all the training examples, once the conditional pretraining examples are generated, they become reusable and easily understandable by humans. This approach enhances the training process, resulting in more accurate and user-friendly language models. 30 | 31 | ### Transparency and Accountability 32 | 33 | Another significant advantage of conditional pretraining is the transparency of the tags used on documents, which can be easily understood by auditors or end users of the models. At present, the instructions and reward models employed in most LLMs are proprietary and not available for public review. This lack of transparency makes it challenging to comprehend how and why models respond to culturally or politically sensitive topics. Even when there are disagreements among people about how these models should be aligned and what values they should uphold, it is difficult to engage in meaningful discussions or debates on these sensitive topics as long as the values of the organizations developing the LLMs remain concealed or obscured by carefully crafted press releases and position papers. 34 | 35 | 36 | ### References 37 | 38 | - [Pretraining Language Models with Human Preferences](https://arxiv.org/abs/2302.08582) 39 | - [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) 40 | 41 | -------------------------------------------------------------------------------- /cond_pretrain_second_image.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LAION-AI/Conditional-Pretraining-of-Large-Language-Models/39b61f54b0635d6a9b20b99e19b260794c201190/cond_pretrain_second_image.PNG -------------------------------------------------------------------------------- /cond_pretraining_first_image.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LAION-AI/Conditional-Pretraining-of-Large-Language-Models/39b61f54b0635d6a9b20b99e19b260794c201190/cond_pretraining_first_image.PNG -------------------------------------------------------------------------------- /data-processing/ul2-document-tagging.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """This code is a work in progress. The default is to use flan-ul2 4 | however this same code is compatible with any of the flan-T5 models 5 | available on the huggingface hub. Use whatever is the largest model 6 | that your hardware can support. Having good labels is important for 7 | good quality conditional pretraining examples.""" 8 | 9 | # Load all needed libraries 10 | from transformers import AutoTokenizer, AutoModelForSeq2SeqLM 11 | import torch 12 | import re 13 | import math 14 | import sys 15 | import time 16 | 17 | # Set input and output files 18 | inputfile = sys.argv[1] 19 | device_id = int(sys.argv[2]) 20 | outfile = inputfile + ".out" 21 | 22 | # Load device map for FLAN_UL2 23 | device_map = { 24 | 'shared': device_id, 25 | 'lm_head': device_id, 26 | 'encoder': device_id, 27 | 'decoder': device_id, 28 | 'decoder.final_layer_norm': device_id, 29 | 'decoder.dropout': device_id 30 | } 31 | 32 | # Load the model in bfloat16 33 | tokenizer = AutoTokenizer.from_pretrained("google/flan-ul2") 34 | model = AutoModelForSeq2SeqLM.from_pretrained( 35 | "google/flan-ul2", 36 | device_map=device_map, 37 | torch_dtype=torch.bfloat16, 38 | load_in_8bit=False, 39 | ) 40 | 41 | 42 | # Load strings as knowledge sources for QA generation from a text file 43 | with open(inputfile) as my_file: 44 | data = my_file.read() 45 | 46 | # Split entries by EOS token and remove any unneeded newlines 47 | paragraphs=data.split("<|endoftext|>") 48 | 49 | # Sort_Tuple sorts a list of tuples by the second element 50 | def Sort_Tuple(tup): 51 | tup.sort(key=lambda x: x[1], reverse=True) 52 | return tup 53 | 54 | 55 | # ask_UL2 takes a text input and returns the 56 | # response of FLAN_UL2 and a normalized logits 57 | # score for the generation. 58 | 59 | def ask_UL2(input_text): 60 | inputs = tokenizer([sentence for sentence in input_text], return_tensors="pt", padding=True) 61 | outputs = model.generate( 62 | input_ids=inputs["input_ids"].to(device_id), 63 | attention_mask=inputs["attention_mask"].to(device_id), 64 | do_sample=True, 65 | top_p=0.95, 66 | eos_token_id=1, 67 | max_new_tokens=5, 68 | bos_token_id=0, 69 | temperature=0.9, 70 | return_dict_in_generate=True, 71 | output_scores=True, 72 | ) 73 | output_tuple=[] 74 | probs = torch.stack(outputs.scores, dim=1).softmax(-1) 75 | for z,i in enumerate(outputs.sequences): 76 | out_text = tokenizer.decode(i, skip_special_tokens=True) 77 | logprobs = 0 78 | counter = 0 79 | if 1 in i[1:]: 80 | for k in i[1:]: 81 | word_prob = (round(probs[z][counter][k.item()].item(), 2)) + 0.001 82 | logprobs = logprobs + math.log(word_prob) 83 | counter += 1 84 | out_tuple = (out_text, round((logprobs/(counter+1)), 2)) 85 | output_tuple.append(out_tuple) 86 | else: 87 | pass 88 | 89 | return output_tuple 90 | 91 | 92 | # Generate a topic classifier for a paragraph of text 93 | def generate_topic(paragraph): 94 | results = [] 95 | length=int(len(paragraph) / 2) 96 | length2=int(length/2) 97 | 98 | para1=paragraph[0:length] 99 | para2=paragraph[(length-length2):(2*length-length2)] 100 | para3=paragraph[length:(2*length)] 101 | 102 | toklens=[] 103 | input_1 = ( 104 | "Task: Generate a theme or category label for the provided document.\nDocument:\n" + para1 + "\nTheme: " 105 | ) 106 | toklens.append(len(tokenizer.encode(input_1))) 107 | input_2 = ( 108 | "Task: Generate a theme or category label for the provided document.\nDocument:\n" + para2 + "\nTheme: " 109 | ) 110 | toklens.append(len(tokenizer.encode(input_2))) 111 | input_3 = ( 112 | "Task: Generate a theme or category label for the provided document.\nDocument:\n" + para3 + "\nTheme: " 113 | ) 114 | toklens.append(len(tokenizer.encode(input_3))) 115 | 116 | minlen=min(toklens) 117 | if minlen > 800: 118 | minlen=800 119 | 120 | input_1f=tokenizer.decode(tokenizer.encode(input_1)[0:minlen]) 121 | input_2f=tokenizer.decode(tokenizer.encode(input_2)[0:minlen]) 122 | input_3f=tokenizer.decode(tokenizer.encode(input_3)[0:minlen]) 123 | 124 | inputs=[] 125 | # The tags are more biased towards the beginning. 126 | for k in range(0, 12): 127 | inputs.append(input_1f) 128 | for k in range(0, 8): 129 | inputs.append(input_2f) 130 | for k in range(0, 4): 131 | inputs.append(input_3f) 132 | 133 | result_tuple = ask_UL2(inputs) 134 | # Filter out any results that are not of good quality. 135 | for result in result_tuple: 136 | if result[1] > -5: 137 | if len(re.findall(r"\d{2}", result[0])) > 0 or len(re.findall(r'[A-Z]{4}', result[0])) > 0 or len(re.findall(r"\W", result[0].replace(" ","").replace(")","").replace("(","").replace(".","").replace("'",""))) > 0: 138 | pass 139 | else: 140 | results.append(result) 141 | 142 | if len(results) < 1: 143 | results.append(("no_topic",-50)) 144 | return results 145 | 146 | else: 147 | sorted_results = Sort_Tuple(results) 148 | return sorted_results[0:16] 149 | 150 | # Use this to deduplicate the list 151 | def dedup_list(toplist): 152 | temptops=set() 153 | for topic in toplist: 154 | if topic[1] > -6: 155 | item=topic[0].lower().replace(": ",":").replace("label:","").replace("category:","") 156 | if len(item.split(" ")) > 3: 157 | pass 158 | else: 159 | temptops.add(item) 160 | return list(temptops) 161 | 162 | excluded_list = {"label", "tag", "tags", "chapter", "labels", "story", "stories", "category", "movie", "movies"} 163 | 164 | def order_topics(combined_topics_lists): 165 | strings_list=[] 166 | for i in combined_topics_lists: 167 | for k in i: 168 | if k in excluded_list or len(k) < 3: 169 | pass 170 | else: 171 | strings_list.append(k) 172 | print(strings_list[0:10]) 173 | # Count the frequency of each string in the input list 174 | frequency_dict = {} 175 | for string in strings_list: 176 | if string in frequency_dict: 177 | frequency_dict[string] += 1 178 | else: 179 | frequency_dict[string] = 1 180 | 181 | # Sort the strings based on their frequency, from most to least frequent 182 | sorted_strings = sorted(frequency_dict.keys(), key=lambda x: frequency_dict[x], reverse=True) 183 | 184 | return sorted_strings 185 | 186 | # Start analysis. Prints out to the "outfile" file in the same directory as the input. 187 | start_time = time.perf_counter() 188 | questions_dict = {} 189 | uniq_id = 100000 190 | for paragraph in paragraphs: 191 | start_time=time.perf_counter() 192 | if paragraph[0]=="\n": 193 | paragraph=paragraph[1:] 194 | if paragraph[0]=="\n": 195 | paragraph=paragraph[1:] 196 | topic_list=[] 197 | print("-"*8) 198 | print(paragraph[0:40]) 199 | topic1a=dedup_list(generate_topic(paragraph)) 200 | ordered_tops=order_topics([topic1a]) 201 | newstring="^-^-^-^-^-^-^\n[ " 202 | for topic in ordered_tops: 203 | newstring+=topic+", " 204 | finalstring=newstring[:-2]+"]" 205 | print(finalstring,file=open(outfile,"a")) 206 | print(paragraph,file=open(outfile,"a")) 207 | stop_time=time.perf_counter() 208 | generation_time=stop_time-start_time 209 | print("Generation time:",generation_time) 210 | 211 | --------------------------------------------------------------------------------