portalniy-dev commited on
Commit
8d2aba0
1 Parent(s): fc46763

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -139
app.py CHANGED
@@ -1,141 +1,40 @@
1
- import gradio as gr
2
  import torch
3
- from datasets import load_dataset, concatenate_datasets
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
5
-
6
- # Predefined datasets with their configurations
7
- dataset_names = {
8
- 'imdb': None,
9
- 'ag_news': None,
10
- 'squad': None,
11
- 'cnn_dailymail': '1.0.0', # Specify configuration for cnn_dailymail
12
- 'wiki40b': 'en' # Specify language for wiki40b
13
- }
14
-
15
- # Global variables for model and tokenizer
16
- model = None
17
- tokenizer = None
18
-
19
- # Function to load and prepare datasets
20
- def load_and_prepare_datasets():
21
- datasets = []
22
- for name, config in dataset_names.items():
23
- ds = load_dataset(name, config)
24
- datasets.append(ds)
25
-
26
- # Print dataset features for debugging
27
- print(f"Dataset: {name}, Features: {ds['train'].features}")
28
-
29
- # Extract only the relevant fields from each dataset for training
30
- train_datasets = []
31
- eval_datasets = []
32
-
33
- for ds in datasets:
34
- if 'train' in ds:
35
- # Extract text field based on available keys
36
- if 'text' in ds['train'].features:
37
- train_datasets.append(ds['train'].map(lambda x: {'text': x['text']}))
38
- elif 'content' in ds['train'].features: # Example for CNN/DailyMail
39
- train_datasets.append(ds['train'].map(lambda x: {'text': x['content']}))
40
- else:
41
- print(f"Warning: No suitable text field found in {ds['train'].features}")
42
-
43
- if 'test' in ds:
44
- # Extract text field based on available keys
45
- if 'text' in ds['test'].features:
46
- eval_datasets.append(ds['test'].map(lambda x: {'text': x['text']}))
47
- elif 'content' in ds['test'].features: # Example for CNN/DailyMail
48
- eval_datasets.append(ds['test'].map(lambda x: {'text': x['content']}))
49
- else:
50
- print(f"Warning: No suitable text field found in {ds['test'].features}")
51
-
52
- # Concatenate train datasets only for training
53
- train_dataset = concatenate_datasets(train_datasets)
54
-
55
- # Concatenate eval datasets only for evaluation
56
- eval_dataset = concatenate_datasets(eval_datasets)
57
-
58
- return train_dataset, eval_dataset
59
-
60
- # Function to preprocess data
61
- def preprocess_function(examples):
62
- return tokenizer(examples['text'], truncation=True, padding='max_length', max_length=512)
63
-
64
- # Function to train the model
65
- def train_model():
66
- global model, tokenizer
67
-
68
- # Load model and tokenizer
69
- model_name = 'gpt2' # You can choose another model if desired
70
- model = AutoModelForCausalLM.from_pretrained(model_name)
71
- tokenizer = AutoTokenizer.from_pretrained(model_name)
72
-
73
- # Load and prepare datasets
74
- train_dataset, eval_dataset = load_and_prepare_datasets()
75
-
76
- # Preprocess the datasets
77
- train_dataset = train_dataset.map(preprocess_function, batched=True)
78
-
79
- # Set training arguments
80
- training_args = TrainingArguments(
81
- output_dir='./results',
82
- num_train_epochs=3,
83
- per_device_train_batch_size=4,
84
- per_device_eval_batch_size=4,
85
- warmup_steps=500,
86
- weight_decay=0.01,
87
- logging_dir='./logs',
88
- logging_steps=10,
89
- save_steps=1000,
90
- evaluation_strategy="steps",
91
- learning_rate=5e-5 # Adjust learning rate if necessary
92
- )
93
-
94
- # Train the model
95
- trainer = Trainer(
96
- model=model,
97
- args=training_args,
98
- train_dataset=train_dataset,
99
- eval_dataset=eval_dataset,
100
- )
101
-
102
- trainer.train()
103
-
104
- return "Model trained successfully!"
105
-
106
- # Function to generate text
107
- def generate_text(prompt):
108
- global tokenizer # Ensure we use the global tokenizer variable
109
-
110
- if tokenizer is None:
111
- return "Tokenizer not initialized. Please train the model first."
112
-
113
- input_ids = tokenizer.encode(prompt, return_tensors='pt')
114
-
115
- # Adjust generation parameters for better quality output
116
- output = model.generate(input_ids, max_length=100, temperature=0.7, top_k=50)
117
-
118
- generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
119
-
120
- return generated_text
121
-
122
- # Gradio interface
123
- with gr.Blocks() as demo:
124
- gr.Markdown("# LLM Training and Text Generation")
125
-
126
- with gr.Row():
127
- with gr.Column():
128
- train_button = gr.Button("Train Model")
129
- output_message = gr.Textbox(label="Training Status", interactive=False)
130
-
131
- with gr.Column():
132
- prompt_input = gr.Textbox(label="Enter prompt for text generation")
133
- generate_button = gr.Button("Generate Text")
134
- generated_output = gr.Textbox(label="Generated Text", interactive=False)
135
-
136
- # Button actions
137
- train_button.click(train_model, outputs=output_message)
138
- generate_button.click(generate_text, inputs=prompt_input, outputs=generated_output)
139
 
140
- # Launch the app with share=True to create a public link
141
- demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, Trainer, TrainingArguments, pipeline
3
+ from datasets import load_dataset
4
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Шаг 1: Загружаем и подготавливаем датасеты
7
+ datasets = [
8
+ load_dataset('squad'),
9
+ load_dataset('conll2003'),
10
+ load_dataset('glue', 'mrpc'),
11
+ load_dataset('trec'),
12
+ load_dataset('babi')
13
+ ]
14
+
15
+ # Шаг 2: Загружаем модель и токенизатор
16
+ model_name = 'distilbert-base-uncased'
17
+ tokenizer = DistilBertTokenizer.from_pretrained(model_name)
18
+ model = DistilBertForSequenceClassification.from_pretrained(model_name)
19
+
20
+ # Шаг 3: Токенизация и тренировка модели
21
+ def tokenize_function(examples):
22
+ return tokenizer(examples["text"], padding="max_length", truncation=True)
23
+
24
+ tokenized_datasets = []
25
+ for ds in datasets:
26
+ tokenized_ds = ds.map(tokenize_function, batched=True)
27
+ tokenized_datasets.append(tokenized_ds)
28
+
29
+ # Шаг 4: Оптимизация модели с помощью quantization
30
+ model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
31
+
32
+ # Шаг 5: Создание функции для классификации текста
33
+ def classify_text(text):
34
+ tokens = tokenizer(text, return_tensors="pt")
35
+ outputs = model(**tokens)
36
+ return torch.nn.functional.softmax(outputs.logits, dim=-1).tolist()
37
+
38
+ # Шаг 6: Настройка Gradio интерфейса
39
+ interface = gr.Interface(fn=classify_text, inputs="text", outputs="json")
40
+ interface.launch()