Spaces:
Runtime error
Runtime error
Download app.py from maximercl/merlin-7b-compare: direct link, hf CLI and curl.
- Browser
- Download file 8.12 kB
-
https://huggingface.co/spaces/maximercl/merlin-7b-compare/resolve/main/app.py
- Command line
-
hf download hf://spaces/maximercl/merlin-7b-compare/app.py
-
curl -L -o app.py https://huggingface.co/spaces/maximercl/merlin-7b-compare/resolve/main/app.py
8.12 kB
| """Merlin-7B compare: one prompt, three answers side by side (base Qwen2.5-7B, Merlin-7B-CPT-v1, Merlin-7B-SFT-v1). | |
| Runs as a Hugging Face Space (Gradio). Environment: | |
| MODELS comma-separated model ids or paths (default: the three Merlin versions) | |
| LABELS comma-separated column titles (same order) | |
| LOAD_4BIT "1" (default) loads every model in 4-bit NF4 (three 7B models fit an L4 24 GB); "0" loads bf16 | |
| HF_TOKEN read token for the private repos (Space secret) | |
| APP_PASSWORD if set, the page shows a password box first and refuses prompts from sessions that did not unlock | |
| MAX_NEW max new tokens per answer (default 400) | |
| Prompt formats: the base and CPT models are text continuers and get the raw "Pergunta/Resposta" prompt used in | |
| the project's narrative probe; the fine-tuned model gets its chat template and training system prompt. An optional | |
| passage box grounds all three (the fine-tuned one was trained for that). | |
| """ | |
| import os, threading, time | |
| import gradio as gr | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer | |
| MODELS = [m.strip() for m in os.environ.get("MODELS", "Qwen/Qwen2.5-7B,maximercl/Merlin-7B-CPT-v1,maximercl/Merlin-7B-SFT-v1").split(",")] | |
| LABELS = [l.strip() for l in os.environ.get("LABELS", "Base Qwen2.5-7B,Merlin-7B-CPT-v1 (continued pretraining),Merlin-7B-SFT-v1 (CPT + fine-tune)").split(",")] | |
| CHAT = [("SFT" in m) or ("Instruct" in m) or os.environ.get("CHAT_FLAGS", "0,0,1").split(",")[i].strip() == "1" for i, m in enumerate(MODELS)] | |
| LOAD_4BIT = os.environ.get("LOAD_4BIT", "1") == "1" | |
| MAX_NEW = int(os.environ.get("MAX_NEW", "400")) | |
| TOKEN = os.environ.get("HF_TOKEN") | |
| PASSWORD = os.environ.get("APP_PASSWORD") or None | |
| SYSTEM_PT = ("És o Merlin, assistente técnico de contabilidade, fiscalidade e processamento salarial em Portugal, " | |
| "para contabilistas certificados. Respondes em português europeu, com rigor e concisão, citando os " | |
| "artigos e normas aplicáveis. Quando é fornecido um excerto, respondes com base nele e indicas o que " | |
| "ele não cobre; quando não é fornecido, indicas a norma que deve ser confirmada. Terminas a resposta " | |
| "quando ela está completa.") | |
| HEADER = "Consultório técnico de contabilidade e fiscalidade portuguesa. Responda de forma rigorosa e completa, citando os artigos aplicáveis.\n\n" | |
| EXAMPLES = [ | |
| "Quais são os requisitos formais para o exercício do direito à dedução do IVA e que consequência tem a falta de um deles?", | |
| "Que limites definem uma microentidade no SNC e que regime contabilístico e de relato lhe é aplicável?", | |
| "Quais são as consequências do incumprimento do prazo de entrega da declaração Modelo 22 de IRC?", | |
| "Uma sociedade apurou um lucro tributável de 120.000,00 € e tem prejuízos reportáveis de 30.000,00 €, dedutíveis até 65 % do lucro tributável. A taxa de IRC é 20 % e a derrama municipal 1,5 %. Calcule a matéria coletável, a coleta e o imposto a pagar.", | |
| ] | |
| _models = {} | |
| _lock = threading.Lock() | |
| def load_all(): | |
| from transformers import BitsAndBytesConfig | |
| q = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True) if LOAD_4BIT else None | |
| for m in MODELS: | |
| t0 = time.time() | |
| tok = AutoTokenizer.from_pretrained(m, token=TOKEN) | |
| if tok.pad_token_id is None: tok.pad_token = tok.eos_token | |
| kw = dict(token=TOKEN, device_map="auto", attn_implementation="sdpa") | |
| model = AutoModelForCausalLM.from_pretrained(m, quantization_config=q, **kw) if q else AutoModelForCausalLM.from_pretrained(m, dtype=torch.bfloat16, **kw) | |
| model.eval(); _models[m] = (tok, model) | |
| print(f"loaded {m} in {time.time()-t0:.0f}s", flush=True) | |
| def build_prompt(i, question, passage): | |
| tok, _ = _models[MODELS[i]] | |
| passage = (passage or "").strip(); question = question.strip() | |
| if CHAT[i]: | |
| user = f"Excerto:\n{passage}\n\nPergunta: {question}" if passage else question | |
| return tok.apply_chat_template([{"role": "system", "content": SYSTEM_PT}, {"role": "user", "content": user}], tokenize=False, add_generation_prompt=True) | |
| ctx = f"Excerto:\n{passage}\n\n" if passage else "" | |
| return HEADER + ctx + f"Pergunta: {question}\nResposta:" | |
| def stream_one(i, prompt): | |
| tok, model = _models[MODELS[i]] | |
| enc = tok(prompt, return_tensors="pt", add_special_tokens=False).to(model.device) | |
| streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True) | |
| eos = [tok.eos_token_id] + ([tok.convert_tokens_to_ids("<|im_end|>")] if "<|im_end|>" in tok.get_vocab() else []) | |
| kw = dict(**enc, max_new_tokens=MAX_NEW, do_sample=False, repetition_penalty=1.0 if CHAT[i] else 1.05, pad_token_id=tok.pad_token_id, eos_token_id=eos, streamer=streamer) | |
| th = threading.Thread(target=model.generate, kwargs=kw); th.start() | |
| text = "" | |
| for piece in streamer: | |
| text += piece | |
| if not CHAT[i] and "\nPergunta:" in text: # the raw-prompt models do not stop; cut at the next question they invent | |
| text = text.split("\nPergunta:")[0]; yield text.strip(); break | |
| yield text.strip() | |
| th.join() | |
| def answer(question, passage, unlocked): | |
| if PASSWORD and not unlocked: | |
| yield ("Introduza a palavra-passe primeiro.", "", ""); return | |
| if not question or not question.strip(): | |
| yield ("", "", ""); return | |
| outs = ["", "", ""] | |
| with _lock: # one GPU: the three models answer one after the other, each streaming into its column | |
| for i in range(len(MODELS)): | |
| outs[i] = "…"; yield tuple(outs) | |
| for text in stream_one(i, build_prompt(i, question, passage)): | |
| outs[i] = text; yield tuple(outs) | |
| yield tuple(outs) | |
| def unlock(pw): | |
| ok = (not PASSWORD) or (pw == PASSWORD) | |
| return ok, gr.update(visible=not ok), gr.update(visible=ok), ("" if ok else "Palavra-passe incorreta.") | |
| with gr.Blocks(title="Merlin-7B compare") as demo: | |
| unlocked = gr.State(not bool(PASSWORD)) | |
| with gr.Column(visible=bool(PASSWORD)) as gate: | |
| gr.Markdown("## Merlin-7B compare\nIntroduza a palavra-passe para aceder.") | |
| pw_box = gr.Textbox(label="Palavra-passe", type="password") | |
| pw_btn = gr.Button("Entrar", variant="primary"); pw_msg = gr.Markdown("") | |
| with gr.Column(visible=not bool(PASSWORD)) as main: | |
| gr.Markdown("## Merlin-7B: base vs continued pretraining vs fine-tune\nUma pergunta, três respostas. Opcionalmente cole um excerto (lei, norma, decisão) para fundamentar as respostas; o modelo afinado foi treinado para responder com base nele.") | |
| with gr.Row(): | |
| question = gr.Textbox(label="Pergunta", lines=3, placeholder="Escreva a pergunta em português…", scale=3) | |
| passage = gr.Textbox(label="Excerto (opcional)", lines=3, placeholder="Cole aqui o texto da norma ou decisão…", scale=3) | |
| btn = gr.Button("Responder", variant="primary") | |
| with gr.Row(): | |
| boxes = [gr.Textbox(label=LABELS[i], lines=18, interactive=False) for i in range(len(MODELS))] | |
| gr.Examples(examples=[[e, ""] for e in EXAMPLES], inputs=[question, passage]) | |
| gr.Markdown("Base e CPT recebem um prompt de continuação de texto (cortado à próxima 'Pergunta:' ou a %d tokens); o modelo afinado usa o seu template de chat e termina sozinho. Respostas geradas em sequência num único GPU." % MAX_NEW) | |
| btn.click(answer, inputs=[question, passage, unlocked], outputs=boxes) | |
| question.submit(answer, inputs=[question, passage, unlocked], outputs=boxes) | |
| pw_btn.click(unlock, inputs=[pw_box], outputs=[unlocked, gate, main, pw_msg]) | |
| pw_box.submit(unlock, inputs=[pw_box], outputs=[unlocked, gate, main, pw_msg]) | |
| if __name__ == "__main__": | |
| print("password gate:", "on" if PASSWORD else "OFF (APP_PASSWORD not set)", flush=True) | |
| load_all() | |
| demo.queue(max_size=8).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")), theme=gr.themes.Soft()) | |