Spaces:
Sleeping
Sleeping
Download app.py from elrplays/peter-training: direct link, hf CLI and curl.
- Browser
- Download file 5.12 kB
-
https://huggingface.co/spaces/elrplays/peter-training/resolve/main/app.py
- Command line
-
hf download hf://spaces/elrplays/peter-training/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elrplays/peter-training/resolve/main/app.py
5.12 kB
| import gradio as gr | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, DataCollatorForLanguageModeling, BitsAndBytesConfig | |
| from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training | |
| from datasets import load_dataset | |
| from huggingface_hub import login, create_repo | |
| import torch | |
| import os | |
| import logging | |
| import json | |
| # Configuração de Logs | |
| logging.basicConfig(level=logging.INFO) | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| if HF_TOKEN: | |
| login(token=HF_TOKEN) | |
| MODEL_NAME = "Qwen/Qwen2.5-Coder-1.5B-Instruct" | |
| def treinar_peter(dataset_file, texto_direto, hf_repo_name): | |
| # Lógica para priorizar a Textarea (Modo Celular) | |
| caminho_final = None | |
| if texto_direto and texto_direto.strip(): | |
| caminho_final = "treino_mobile.jsonl" | |
| with open(caminho_final, "w", encoding="utf-8") as f: | |
| f.write(texto_direto.strip()) | |
| elif dataset_file: | |
| caminho_final = dataset_file.name | |
| else: | |
| return "❌ Erro: Suba um arquivo ou cole o texto na área abaixo." | |
| if not hf_repo_name or "/" not in hf_repo_name: | |
| return "❌ Erro: Formato 'usuario/nome-do-repo' obrigatório." | |
| try: | |
| logging.info("Carregando cérebro base...") | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| use_cuda = torch.cuda.is_available() | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| device_map="auto", | |
| torch_dtype=torch.float16 if use_cuda else torch.float32, | |
| low_cpu_mem_usage=True | |
| ) | |
| # Configuração LoRA mais forte (r=64) para gravar a identidade | |
| peft_config = LoraConfig( | |
| r=64, | |
| lora_alpha=128, | |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], | |
| lora_dropout=0.05, | |
| bias="none", | |
| task_type="CAUSAL_LM" | |
| ) | |
| model = get_peft_model(model, peft_config) | |
| # Processar Dataset (Aumentamos o max_length para 1024) | |
| dataset = load_dataset("json", data_files=caminho_final, split="train") | |
| def tokenize_function(examples): | |
| return tokenizer( | |
| examples["text"], | |
| truncation=True, | |
| max_length=1024, # Mais espaço para o raciocínio Newtoniano | |
| padding="max_length" | |
| ) | |
| tokenized_dataset = dataset.map(tokenize_function, batched=True) | |
| training_args = TrainingArguments( | |
| output_dir="./peter-results", | |
| per_device_train_batch_size=1, | |
| gradient_accumulation_steps=4, | |
| max_steps=50, # Um pouco mais de passos para fixar o "Eu" | |
| learning_rate=1e-4, | |
| fp16=use_cuda, | |
| logging_steps=1, | |
| save_strategy="no", | |
| push_to_hub=False, | |
| report_to="none" | |
| ) | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=tokenized_dataset, | |
| data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False) | |
| ) | |
| logging.info("Treinando o Peter...") | |
| trainer.train() | |
| # Salvar e Enviar | |
| create_repo(hf_repo_name, private=True, exist_ok=True) | |
| model.push_to_hub(hf_repo_name) | |
| tokenizer.push_to_hub(hf_repo_name) | |
| return f"✅ Treino Finalizado! Identidade 'Eu' atualizada em: {hf_repo_name}" | |
| except Exception as e: | |
| return f"❌ Erro: {str(e)}" | |
| # Interface Gradio | |
| # Interface Gradio - Ajustada para compatibilidade total | |
| with gr.Blocks() as demo: | |
| gr.Markdown(""" | |
| # 🧠 Peter Trainer v2 (Modo Newton) | |
| Configure a identidade do Peter usando a área de texto ou suba um arquivo. | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| # Componente de Arquivo | |
| file_in = gr.File(label="1. Subir arquivo .jsonl (Opcional)") | |
| # TEXTAREA CORRIGIDA (Removido show_copy_button para evitar o erro) | |
| texto_in = gr.Textbox( | |
| label="2. Treino Rápido / Modo Celular (Cole seu JSONL aqui)", | |
| placeholder='Exemplo: {"text": "Eu sou o Peter e eu calculo..."}', | |
| lines=10, | |
| interactive=True | |
| ) | |
| repo_in = gr.Textbox( | |
| label="3. Repositório no Hugging Face", | |
| placeholder="seu-usuario/peter-lora", | |
| value="elrplays/peter-training" | |
| ) | |
| btn = gr.Button("🚀 Iniciar Fine-Tuning", variant="primary") | |
| with gr.Column(): | |
| out = gr.Markdown("### Status do Treinamento\nAguardando comandos...") | |
| # Conexão dos inputs com a função de treino | |
| btn.click( | |
| fn=treinar_peter, | |
| inputs=[file_in, texto_in, repo_in], | |
| outputs=out | |
| ) | |
| if __name__ == "__main__": | |
| # O tema (Soft) foi movido para o launch() como o erro sugeriu | |
| demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft()) |