Spaces:
Sleeping
Sleeping
File size: 6,264 Bytes
abaea54 c9c4d75 9c2ae81 c9c4d75 9c2ae81 c9c4d75 9c2ae81 c9c4d75 9c2ae81 c9c4d75 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
import gradio as gr
from huggingface_hub import login
# ! pip install accelerate peft bitsandbytes pip install git+https://github.com/huggingface/transformers trl py7zr auto-gptq optimum
import torch
# from datasets import Dataset
# from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig, TrainingArguments
# from trl import SFTTrainer
# import pandas as pd
# import json
# import pandas as pd
# def load_data_to_dataframe(json_file_path):
# """
# Load data from a JSON file and create a DataFrame with questions and answers.
# Args:
# json_file_path (str): Path to the JSON file.
# Returns:
# pd.DataFrame: DataFrame containing the questions and answers.
# """
# questions = []
# answers = []
# with open(json_file_path, 'r') as f:
# data = json.load(f)
# for entry in data:
# for message in entry["messages"]:
# if message["role"] == "user":
# questions.append(message["content"])
# elif message["role"] == "assistant":
# answers.append(message["content"])
# # Create DataFrame
# df = pd.DataFrame({
# 'question': questions,
# 'answer': answers
# })
# return df
# def finetune_mistral_7b():
# # Replace 'your_token' with your actual Hugging Face token
# json_file_path = 'Dataset for finetuning Viv.json'
# df = load_data_to_dataframe(json_file_path)
# df["text"] = df[["question", "answer"]].apply(lambda x: "###Human: Answer this question: " + x["question"] + "\n###Assistant: " +x["answer"], axis=1)
# print(df.iloc[0])
# data = Dataset.from_pandas(df)
# tokenizer = AutoTokenizer.from_pretrained("TheBloke/Mistral-7B-Instruct-v0.1-GPTQ")
# tokenizer.pad_token = tokenizer.eos_token
# quantization_config_loading = GPTQConfig(bits=4, disable_exllama=True, tokenizer=tokenizer)
# model = AutoModelForCausalLM.from_pretrained(
# "TheBloke/Mistral-7B-Instruct-v0.1-GPTQ",
# quantization_config=quantization_config_loading,
# device_map="auto"
# )
# print(model)
# model.config.use_cache = False
# model.config.pretraining_tp = 1
# model.gradient_checkpointing_enable()
# model = prepare_model_for_kbit_training(model)
# peft_config = LoraConfig(
# r=16, lora_alpha=16, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", target_modules=["q_proj", "v_proj"]
# )
# model = get_peft_model(model, peft_config)
# training_arguments = TrainingArguments(
# output_dir="mistral-finetuned-Viv",
# per_device_train_batch_size=8,
# gradient_accumulation_steps=1,
# optim="paged_adamw_32bit",
# learning_rate=2e-4,
# lr_scheduler_type="cosine",
# save_strategy="epoch",
# logging_steps=100,
# num_train_epochs=1,
# max_steps=100,
# fp16=True,
# push_to_hub=True,
# hub_model_id="Dumele/viv-updated2", # Specify the repository name
# hub_strategy="every_save"
# )
# trainer = SFTTrainer(
# model=model,
# train_dataset=data,
# peft_config=peft_config,
# dataset_text_field="text",
# args=training_arguments,
# tokenizer=tokenizer,
# packing=False,
# max_seq_length=512
# )
# trainer.train()
# trainer.push_to_hub()
# if __name__ == "__main__":
# finetune_mistral_7b()
from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig
import torch
# Define the repository where your model is saved
model_repo = "Dumele/viv-updated2" # Replace with your actual repository
# Load the tokenizer from the repository
tokenizer = AutoTokenizer.from_pretrained(model_repo)
# Define the configuration with `disable_exllama` set to True
quantization_config = GPTQConfig(bits=4, disable_exllama=True)
# Load the model with the custom configuration
model = AutoModelForCausalLM.from_pretrained(model_repo, quantization_config=quantization_config)
# Move the model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
from transformers import pipeline
# Create a text generation pipeline
text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
# Define a prompt
prompt = "###Human: Answer this question: What exactly does Viv do?\n###Assistant:"
# Generate text
generated_text = text_generator(prompt, max_length=100, num_return_sequences=1)
# Print the generated text
print(generated_text[0]['generated_text'])
# pip install gradio
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import gradio as gr
# Define the repository where your model is saved
model_repo = "Dumele/viv-updated2" # Replace with your actual repository name
# Load the tokenizer from the repository
tokenizer = AutoTokenizer.from_pretrained(model_repo)
# Define the configuration with `disable_exllama` set to True
quantization_config = GPTQConfig(bits=4, disable_exllama=True)
# Load the model with the custom configuration
model = AutoModelForCausalLM.from_pretrained(model_repo, quantization_config=quantization_config)
# Move the model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Create a text generation pipeline
text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
def generate_response(prompt):
generated_text = text_generator(prompt, max_length=100, num_return_sequences=1)
return generated_text[0]['generated_text']
# Create a Gradio interface
iface = gr.Interface(
fn=generate_response,
inputs=gr.Textbox(lines=2, placeholder="Enter your prompt here..."),
outputs="text",
title="Chat with VivBeta",
description="Enter a prompt to interact with the fine-tuned model."
)
iface.launch()
# Commented out IPython magic to ensure Python compatibility.
# %%bash
#
|