-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
support supervised fine tuning on d2l.
execute with "python -m example.rlhf.supervised_finetuning_d2l"
- Loading branch information
Showing
4 changed files
with
164 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
"""Demo for the supervised fine tuning. | ||
python -m example.rlhf.supervised_finetuning_demo | ||
""" | ||
|
||
from pykoi.chat import QuestionAnswerDatabase | ||
from pykoi.chat.db.constants import (QA_CSV_HEADER_ANSWER, QA_CSV_HEADER_ID, | ||
QA_CSV_HEADER_QUESTION, | ||
QA_CSV_HEADER_VOTE_STATUS) | ||
from pykoi.rlhf import RLHFConfig, SupervisedFinetuning | ||
|
||
# get data from local database | ||
qa_database = QuestionAnswerDatabase() | ||
my_data_pd = qa_database.retrieve_all_question_answers_as_pandas() | ||
my_data_pd = my_data_pd[ | ||
[ | ||
QA_CSV_HEADER_ID, | ||
QA_CSV_HEADER_QUESTION, | ||
QA_CSV_HEADER_ANSWER, | ||
QA_CSV_HEADER_VOTE_STATUS, | ||
] | ||
] | ||
|
||
# analyze the data | ||
print(my_data_pd) | ||
print("My local database has {} samples in total".format(my_data_pd.shape[0])) | ||
|
||
# run supervised finetuning | ||
from peft import LoraConfig | ||
config = RLHFConfig(base_model_path="mistralai/Mistral-7B-Instruct-v0.1", | ||
dataset_type="local_csv", dataset_name="data/chapter22_trnvalfromseed_data_processed.csv", | ||
train_test_split_ratio=0.1, | ||
max_seq_length=896, | ||
per_device_eval_batch_size = 1, | ||
lora_config_rl = LoraConfig( | ||
r=512, | ||
lora_alpha=1024, | ||
lora_dropout=0.05, | ||
target_modules=["q_proj","k_proj","v_proj","o_proj",], # "gate_proj","up_proj","down_proj",], #"lm_head",], | ||
bias="none", | ||
task_type="CAUSAL_LM" | ||
), | ||
) | ||
rlhf_step1_sft = SupervisedFinetuning(config) | ||
rlhf_step1_sft.train_and_save("./models/rlhf_step1_sft") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from typing import Any, Dict, List, Tuple, Union | ||
from transformers import DataCollatorForLanguageModeling | ||
import numpy as np | ||
class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling): | ||
def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: | ||
batch = super().torch_call(examples) | ||
|
||
# The prompt ends with the response key plus a newline. We encode this and then try to find it in the | ||
# sequence of tokens. This should just be a single token. | ||
RESPONSE_KEY = "### Response:" | ||
RESPONSE_KEY_NL = f"{RESPONSE_KEY}\n" | ||
response_token_ids = self.tokenizer.encode(RESPONSE_KEY_NL) | ||
|
||
labels = batch["labels"].clone() | ||
|
||
for i in range(len(examples)): | ||
|
||
response_token_ids_start_idx = None | ||
for idx in np.where(batch["labels"][i] == response_token_ids[0])[0]: | ||
response_token_ids_start_idx = idx | ||
break | ||
|
||
if response_token_ids_start_idx is None: | ||
raise RuntimeError( | ||
f'Could not find response key {response_token_ids} in token IDs {batch["labels"][i]}' | ||
) | ||
|
||
response_token_ids_end_idx = response_token_ids_start_idx + 1 | ||
|
||
# Make pytorch loss function ignore all tokens up through the end of the response key | ||
labels[i, :response_token_ids_end_idx] = -100 | ||
|
||
batch["labels"] = labels | ||
|
||
return batch |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters