File size: 12,752 Bytes
5bb2330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
import { ArrowLeft, Upload, Save } from 'lucide-react';
import '../App.css';

const CreateProject = ({ onBack, onProjectCreated }) => {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    base_model: '',
    rank: 4,
    alpha: 32,
    dropout: 0.1,
    learning_rate: 0.0001,
    batch_size: 1,
    num_epochs: 10,
    use_8bit_optimizer: true,
    use_gradient_checkpointing: true,
    mixed_precision: 'fp16'
  });

  const [availableModels, setAvailableModels] = useState([]);
  const [loading, setLoading] = useState(false);
  const [datasetFile, setDatasetFile] = useState(null);

  useEffect(() => {
    fetchAvailableModels();
  }, []);

  const fetchAvailableModels = async () => {
    try {
      const response = await fetch('/api/models');
      const data = await response.json();
      setAvailableModels(data);
    } catch (error) {
      console.error('Erro ao buscar modelos:', error);
    }
  };

  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    setDatasetFile(file);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

    try {
      // Create project
      const response = await fetch('/api/projects', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('Erro ao criar projeto');
      }

      const project = await response.json();

      // Upload dataset if provided
      if (datasetFile) {
        const formDataUpload = new FormData();
        formDataUpload.append('dataset', datasetFile);

        const uploadResponse = await fetch(`/api/projects/${project.id}/upload-dataset`, {
          method: 'POST',
          body: formDataUpload,
        });

        if (!uploadResponse.ok) {
          throw new Error('Erro ao fazer upload do dataset');
        }
      }

      onProjectCreated(project);
    } catch (error) {
      console.error('Erro ao criar projeto:', error);
      alert('Erro ao criar projeto: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="outline" onClick={onBack} className="flex items-center gap-2">
          <ArrowLeft className="w-4 h-4" />
          Voltar
        </Button>
        <div>
          <h1 className="text-3xl font-bold">Criar Novo Projeto LoRA</h1>
          <p className="text-gray-600 mt-2">
            Configure os parâmetros para seu novo projeto de treinamento
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Basic Information */}
          <Card>
            <CardHeader>
              <CardTitle>Informações Básicas</CardTitle>
              <CardDescription>
                Configure as informações básicas do seu projeto
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="name">Nome do Projeto *</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  placeholder="Ex: Meu Primeiro LoRA"
                  required
                />
              </div>

              <div>
                <Label htmlFor="description">Descrição</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="Descreva o objetivo do seu projeto..."
                  rows={3}
                />
              </div>

              <div>
                <Label htmlFor="base_model">Modelo Base *</Label>
                <Select
                  value={formData.base_model}
                  onValueChange={(value) => handleInputChange('base_model', value)}
                  required
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Selecione um modelo base" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableModels.map((model) => (
                      <SelectItem key={model.id} value={model.id}>
                        {model.name} ({model.size})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="dataset">Dataset</Label>
                <Input
                  id="dataset"
                  type="file"
                  onChange={handleFileChange}
                  accept=".zip,.tar,.tar.gz"
                  className="cursor-pointer"
                />
                <p className="text-sm text-gray-500 mt-1">
                  Formatos aceitos: ZIP, TAR, TAR.GZ
                </p>
              </div>
            </CardContent>
          </Card>

          {/* LoRA Parameters */}
          <Card>
            <CardHeader>
              <CardTitle>Parâmetros LoRA</CardTitle>
              <CardDescription>
                Configure os parâmetros específicos do LoRA
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="rank">Rank: {formData.rank}</Label>
                <Slider
                  id="rank"
                  min={1}
                  max={128}
                  step={1}
                  value={[formData.rank]}
                  onValueChange={(value) => handleInputChange('rank', value[0])}
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  Menor rank = menos parâmetros, mais eficiente
                </p>
              </div>

              <div>
                <Label htmlFor="alpha">Alpha: {formData.alpha}</Label>
                <Slider
                  id="alpha"
                  min={1}
                  max={128}
                  step={1}
                  value={[formData.alpha]}
                  onValueChange={(value) => handleInputChange('alpha', value[0])}
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  Controla a força da adaptação LoRA
                </p>
              </div>

              <div>
                <Label htmlFor="dropout">Dropout: {formData.dropout}</Label>
                <Slider
                  id="dropout"
                  min={0}
                  max={0.5}
                  step={0.01}
                  value={[formData.dropout]}
                  onValueChange={(value) => handleInputChange('dropout', value[0])}
                  className="mt-2"
                />
                <p className="text-sm text-gray-500 mt-1">
                  Previne overfitting durante o treinamento
                </p>
              </div>
            </CardContent>
          </Card>

          {/* Training Parameters */}
          <Card>
            <CardHeader>
              <CardTitle>Parâmetros de Treinamento</CardTitle>
              <CardDescription>
                Configure como o treinamento será executado
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="learning_rate">Taxa de Aprendizado</Label>
                <Input
                  id="learning_rate"
                  type="number"
                  step="0.00001"
                  value={formData.learning_rate}
                  onChange={(e) => handleInputChange('learning_rate', parseFloat(e.target.value))}
                />
              </div>

              <div>
                <Label htmlFor="batch_size">Tamanho do Batch</Label>
                <Select
                  value={formData.batch_size.toString()}
                  onValueChange={(value) => handleInputChange('batch_size', parseInt(value))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">1 (Mais eficiente em memória)</SelectItem>
                    <SelectItem value="2">2</SelectItem>
                    <SelectItem value="4">4</SelectItem>
                    <SelectItem value="8">8</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="num_epochs">Número de Épocas: {formData.num_epochs}</Label>
                <Slider
                  id="num_epochs"
                  min={1}
                  max={50}
                  step={1}
                  value={[formData.num_epochs]}
                  onValueChange={(value) => handleInputChange('num_epochs', value[0])}
                  className="mt-2"
                />
              </div>
            </CardContent>
          </Card>

          {/* Optimization Settings */}
          <Card>
            <CardHeader>
              <CardTitle>Otimizações de GPU</CardTitle>
              <CardDescription>
                Configure otimizações para reduzir o uso de GPU
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <Label htmlFor="use_8bit_optimizer">Otimizador 8-bit</Label>
                  <p className="text-sm text-gray-500">
                    Reduz uso de memória em ~50%
                  </p>
                </div>
                <Switch
                  id="use_8bit_optimizer"
                  checked={formData.use_8bit_optimizer}
                  onCheckedChange={(checked) => handleInputChange('use_8bit_optimizer', checked)}
                />
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <Label htmlFor="use_gradient_checkpointing">Gradient Checkpointing</Label>
                  <p className="text-sm text-gray-500">
                    Troca velocidade por menos memória
                  </p>
                </div>
                <Switch
                  id="use_gradient_checkpointing"
                  checked={formData.use_gradient_checkpointing}
                  onCheckedChange={(checked) => handleInputChange('use_gradient_checkpointing', checked)}
                />
              </div>

              <div>
                <Label htmlFor="mixed_precision">Precisão Mista</Label>
                <Select
                  value={formData.mixed_precision}
                  onValueChange={(value) => handleInputChange('mixed_precision', value)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="fp16">FP16 (Recomendado)</SelectItem>
                    <SelectItem value="bf16">BF16 (Para GPUs mais novas)</SelectItem>
                    <SelectItem value="fp32">FP32 (Sem otimização)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end">
          <Button type="submit" disabled={loading} className="flex items-center gap-2">
            <Save className="w-4 h-4" />
            {loading ? 'Criando...' : 'Criar Projeto'}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default CreateProject;