Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#BS_app.py_03
|
2 |
+
#Training NOK
|
3 |
+
|
4 |
+
#testing bloom1b training
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import os
|
8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, DataCollatorForLanguageModeling
|
9 |
+
from datasets import load_dataset, Dataset
|
10 |
+
from huggingface_hub import HfApi, HfFolder
|
11 |
+
import requests
|
12 |
+
from io import BytesIO
|
13 |
+
|
14 |
+
# Récupérer token depuis les variables d'environnement
|
15 |
+
hf_token = os.getenv("MisterAI_bigscience_bloom_560m")
|
16 |
+
|
17 |
+
# Configurer le token pour l'utilisation avec Hugging Face
|
18 |
+
if hf_token:
|
19 |
+
HfFolder.save_token(hf_token)
|
20 |
+
else:
|
21 |
+
raise ValueError("Le token Hugging Face n'est pas configuré. Assurez-vous qu'il est défini dans les variables d'environnement.")
|
22 |
+
|
23 |
+
# Chargement du modèle et du tokenizer
|
24 |
+
model_name = "MisterAI/bigscience_bloom-560m"
|
25 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
27 |
+
|
28 |
+
# Fonction pour générer une réponse
|
29 |
+
def generate_response(input_text):
|
30 |
+
inputs = tokenizer(input_text, return_tensors="pt")
|
31 |
+
outputs = model.generate(**inputs, max_length=100)
|
32 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
33 |
+
return response
|
34 |
+
|
35 |
+
# Fonction pour le fine-tuning
|
36 |
+
#def fine_tune_model(dataset_path, dataset_file, epochs, batch_size, prefix):
|
37 |
+
# # Chargement du dataset
|
38 |
+
# if dataset_path.startswith("https://huggingface.co/datasets/"):
|
39 |
+
# dataset = load_dataset('json', data_files={dataset_file: dataset_path})
|
40 |
+
# else:
|
41 |
+
# dataset = load_dataset('json', data_files={dataset_file: dataset_path})
|
42 |
+
#
|
43 |
+
# # Préparation des données
|
44 |
+
# dataset = Dataset.from_dict(dataset[dataset_file])
|
45 |
+
# dataset = dataset.map(lambda x: tokenizer(x['question'] + ' ' + x['chosen'], truncation=True, padding='max_length'), batched=True)
|
46 |
+
# dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
|
47 |
+
#
|
48 |
+
# data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
49 |
+
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
def fine_tune_model(dataset_path, dataset_file, epochs, batch_size, prefix):
|
54 |
+
# Récupération du fichier à partir de l'URL fournie
|
55 |
+
response = requests.get(dataset_path)
|
56 |
+
dataset_lines = response.text.strip().split('\n')
|
57 |
+
|
58 |
+
# Convertir les lignes en dictionnaires
|
59 |
+
dataset_dict = [json.loads(line) for line in dataset_lines]
|
60 |
+
|
61 |
+
# Créer un Dataset Hugging Face
|
62 |
+
dataset = Dataset.from_dict({
|
63 |
+
'question': [item['question'] for item in dataset_dict],
|
64 |
+
'chosen': [item['chosen'] for item in dataset_dict]
|
65 |
+
})
|
66 |
+
|
67 |
+
# Préparation des données
|
68 |
+
def preprocess_function(examples):
|
69 |
+
inputs = [q + ' ' + c for q, c in zip(examples['question'], examples['chosen'])]
|
70 |
+
model_inputs = tokenizer(inputs, truncation=True, padding='max_length', max_length=512)
|
71 |
+
model_inputs["labels"] = model_inputs["input_ids"].copy()
|
72 |
+
return model_inputs
|
73 |
+
|
74 |
+
dataset = dataset.map(preprocess_function, batched=True)
|
75 |
+
dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
|
76 |
+
|
77 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
|
78 |
+
|
79 |
+
# Configuration de l'entraînement
|
80 |
+
training_args = TrainingArguments(
|
81 |
+
output_dir=f"./{prefix}_{model_name.split('/')[-1]}",
|
82 |
+
num_train_epochs=epochs,
|
83 |
+
per_device_train_batch_size=batch_size,
|
84 |
+
save_steps=10_000,
|
85 |
+
save_total_limit=2,
|
86 |
+
push_to_hub=True,
|
87 |
+
hub_model_id=f"{prefix}_{model_name.split('/')[-1]}",
|
88 |
+
hub_strategy="checkpoint",
|
89 |
+
hub_token=hf_token,
|
90 |
+
)
|
91 |
+
|
92 |
+
trainer = Trainer(
|
93 |
+
model=model,
|
94 |
+
args=training_args,
|
95 |
+
data_collator=data_collator,
|
96 |
+
train_dataset=dataset,
|
97 |
+
)
|
98 |
+
|
99 |
+
# Lancement de l'entraînement
|
100 |
+
trainer.train()
|
101 |
+
|
102 |
+
# Sauvegarde du modèle avec un préfixe
|
103 |
+
trainer.save_model(f"./{prefix}_{model_name.split('/')[-1]}")
|
104 |
+
tokenizer.save_pretrained(f"./{prefix}_{model_name.split('/')[-1]}")
|
105 |
+
|
106 |
+
# Push vers Hugging Face Hub
|
107 |
+
api = HfApi()
|
108 |
+
api.upload_folder(
|
109 |
+
folder_path=f"./{prefix}_{model_name.split('/')[-1]}",
|
110 |
+
repo_id=f"{prefix}_{model_name.split('/')[-1]}",
|
111 |
+
repo_type="model"
|
112 |
+
)
|
113 |
+
|
114 |
+
return "Fine-tuning terminé et modèle sauvegardé."
|
115 |
+
|
116 |
+
|
117 |
+
|