| |
| import os |
| import json |
| import math |
| import asyncio |
| import random |
| from typing import Dict, Any, List, Tuple, Optional |
|
|
| from openai import AsyncOpenAI, BadRequestError |
| from tqdm import tqdm |
| from itertools import count |
|
|
| from prompts import CATEGORIES_SYSTEM_PROMPTS |
|
|
| |
| |
| |
| VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "http://10.100.0.111:8020/v1") |
| VLLM_API_KEY = os.environ.get("VLLM_API_KEY", "no-key-needed") |
|
|
| |
| GEN_TEMPERATURE = float(os.environ.get("GEN_TEMPERATURE", "0.7")) |
| GEN_TOP_P = float(os.environ.get("GEN_TOP_P", "1.0")) |
| GEN_MAX_NEW_TOK = int(os.environ.get("GEN_MAX_NEW_TOK", "8192")) |
| STOP_STRINGS = ["<|im_end|>", "<|end_of_text|>"] |
| STOP_TOKEN_IDS = None |
|
|
| |
| RESP_TEMPERATURE = float(os.environ.get("RESP_TEMPERATURE", str(GEN_TEMPERATURE if GEN_TEMPERATURE else 0.3))) |
| RESP_TOP_P = float(os.environ.get("RESP_TOP_P", str(min(GEN_TOP_P, 0.9)))) |
| RESP_MAX_TOKENS = int(os.environ.get("RESP_MAX_TOKENS", "8192")) |
|
|
| Q_TEMPERATURE = float(os.environ.get("Q_TEMPERATURE", "0.7")) |
| Q_TOP_P = float(os.environ.get("Q_TOP_P", "0.95")) |
| Q_MAX_TOKENS = int(os.environ.get("Q_MAX_TOKENS", "8192")) |
|
|
| |
| |
| |
| NUM_ROWS = int(os.environ.get("NUM_ROWS", "600000")) |
| BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "16")) |
| N_TURNS = int(os.environ.get("N_TURNS", "3")) |
| OUTPUT_FILE = os.environ.get("OUTPUT_FILE", "magpie_conversations_gptoss120b_fineweb-edu-dedup.jsonl") |
| INCLUDE_SYSTEM = True |
| LOGITS_PROCESSORS: List[str] = [] |
|
|
| |
| MAX_ASYNC_TOTAL = int(os.environ.get("MAX_ASYNC", "256")) |
| CHAT_SHARE = float(os.environ.get("CHAT_SHARE", "0.8")) |
| MAX_ASYNC_CHAT = max(1, int(MAX_ASYNC_TOTAL * CHAT_SHARE)) |
| MAX_ASYNC_QGEN = max(1, MAX_ASYNC_TOTAL - MAX_ASYNC_CHAT) |
| QUEUE_MAXSIZE = int(os.environ.get("QUEUE_MAXSIZE", str(MAX_ASYNC_CHAT * 4))) |
|
|
| |
| |
| |
| WIKI_DATASET_ID = os.environ.get("WIKI_DATASET_ID", "EleutherAI/fineweb-edu-dedup-10b") |
| WIKI_SUBSET = os.environ.get("WIKI_SUBSET", "default") |
| WIKI_TEXT_FIELD = os.environ.get("WIKI_TEXT_FIELD", "text") |
| |
| WIKI_MAX_CHARS = int(os.environ.get("WIKI_MAX_CHARS", "15000")) |
| WIKI_MIN_CHARS = int(os.environ.get("WIKI_MIN_CHARS", "600")) |
|
|
| |
| |
| |
| QUESTION_STYLE_PROMPTS: Dict[str, str] = { |
| "objetiva": ( |
| "Gere UMA pergunta objetiva, direta e específica sobre o CONTEXTO a seguir. " |
| "Evite 'o que é...'. Foque em aspecto técnico/concreto. Máx. 1 sentença. PT-BR." |
| ), |
| "instrucional": ( |
| "Gere UMA pergunta instrucional que solicite etapas/procedimento com base no CONTEXTO. " |
| "Ex.: 'liste', 'descreva o processo', 'quais os passos'. Máx. 1 sentença. PT-BR." |
| ), |
| "pedagogica": ( |
| "Gere UMA pergunta pedagógica pedindo explicação acessível porém correta de um conceito do CONTEXTO, " |
| "ressaltando causa-efeito. Máx. 1 sentença. PT-BR." |
| ), |
| "aplicada": ( |
| "Gere UMA pergunta aplicada conectando o CONTEXTO a uso prático, decisão com restrições, comparação ou trade-off. " |
| "Máx. 1–2 sentenças. PT-BR." |
| ), |
| } |
| _DEFAULT_STYLE_PROBS = {"objetiva": 0.25, "instrucional": 0.25, "pedagogica": 0.25, "aplicada": 0.25} |
|
|
| QUESTION_STYLE_KERNELS_PT = { |
| "objetiva": ( |
| "Siga em pt-BR. Gere UMA pergunta direta e específica sobre um ponto ainda não resolvido " |
| "na conversa. Evite 'o que é', evite sim/não, não repita a pergunta anterior. " |
| "Máx. 1 sentença curta e clara. Termine com '?'." |
| ), |
| "instrucional": ( |
| "Siga em pt-BR. Gere UMA pergunta pedindo procedimento/critério ('como', 'quais passos', 'sob quais condições') " |
| "com base no que já foi respondido. Evite sim/não e múltiplas partes. " |
| "Máx. 1 sentença; termine com '?'." |
| ), |
| "pedagogica": ( |
| "Siga em pt-BR. Gere UMA pergunta pedindo explicação causal ou esclarecimento conceitual focado " |
| "em um detalhe citado previamente. Evite generalidades e sim/não. " |
| "Máx. 1 sentença; termine com '?'." |
| ), |
| "aplicada": ( |
| "Siga em pt-BR. Gere UMA pergunta que traga aplicação prática ou trade-off concreto ligado ao que foi dito " |
| "(restrições, riscos, decisão). Evite sim/não e perguntas vagas. " |
| "Máx. 1 sentença; termine com '?'." |
| ), |
| } |
| DEFAULT_QUESTION_KERNEL_PT = QUESTION_STYLE_KERNELS_PT["objetiva"] |
|
|
| class DropSample(Exception): |
| """Sinaliza que a amostra/conversa deve ser descartada sem interromper o pipeline.""" |
| pass |
|
|
| try: |
| QUESTION_STYLE_PROBS = json.loads(os.environ.get("QUESTION_STYLE_PROBS", "")) or _DEFAULT_STYLE_PROBS |
| except Exception: |
| QUESTION_STYLE_PROBS = _DEFAULT_STYLE_PROBS |
|
|
| QUESTION_SAMPLES_PER_ROW = int(os.environ.get("QUESTION_SAMPLES_PER_ROW", "2")) |
|
|
| def _sample_question_style(k=2) -> List[str]: |
| keys = list(QUESTION_STYLE_PROMPTS.keys()) |
| weights = [QUESTION_STYLE_PROBS.get(k, 0.0) for k in keys] |
| s = sum(weights) |
| weights = [1.0/len(keys)]*len(keys) if s <= 0 else [w/s for w in weights] |
| return random.choices(keys, weights=weights, k=k) |
|
|
| |
| |
| |
| client = AsyncOpenAI(base_url=VLLM_BASE_URL, api_key=VLLM_API_KEY) |
|
|
| |
| |
| |
| def _normalize_spaces(s: str) -> str: |
| return " ".join((s or "").split()) |
|
|
| def _truncate_context(txt: str) -> str: |
| if not isinstance(txt, str): return "" |
| t = _normalize_spaces(txt) |
| if len(t) <= WIKI_MAX_CHARS: return t |
| cut = t.rfind(".", 0, WIKI_MAX_CHARS) |
| if cut == -1 or cut < WIKI_MIN_CHARS: return t[:WIKI_MAX_CHARS] |
| return t[:cut+1] |
|
|
| def sample_system_prompt_key(prompts_with_probs: Dict[str, Tuple[str, float]]) -> str: |
| keys = list(prompts_with_probs.keys()) |
| probs = [prompts_with_probs[k][1] for k in keys] |
| s = sum(probs) |
| probs = [1.0/len(keys)]*len(keys) if s <= 0 else [p/s for p in probs] |
| return random.choices(keys, weights=probs, k=1)[0] |
|
|
| async def get_model_id() -> str: |
| models = await client.models.list() |
| if not models.data: |
| raise RuntimeError("Nenhum modelo disponível no endpoint vLLM.") |
| return models.data[0].id |
|
|
|
|
| async def chat_call( |
| messages: List[Dict[str, str]], |
| model_id: str, |
| *, |
| use_magpie_user: bool = False, |
| question_style: Optional[str] = None, |
| followup_context_text: Optional[str] = None, |
| extra_body_override: Optional[dict] = None, |
| ) -> str: |
| |
| if use_magpie_user: |
| kernel = QUESTION_STYLE_KERNELS_PT.get(question_style or "", DEFAULT_QUESTION_KERNEL_PT) |
| sys_msgs = [{"role": "system", "content": kernel}] |
| if followup_context_text: |
| sys_msgs.append({ |
| "role": "system", |
| "content": "Se necessário, use APENAS o CONTEXTO a seguir como base factual; " |
| "não cite literalmente.\n\n=== CONTEXTO ===\n" + followup_context_text |
| }) |
| final_messages = sys_msgs + messages |
| temperature = Q_TEMPERATURE |
| top_p = Q_TOP_P |
| max_tokens = Q_MAX_TOKENS |
| else: |
| final_messages = messages |
| temperature = RESP_TEMPERATURE |
| top_p = RESP_TOP_P |
| max_tokens = RESP_MAX_TOKENS |
|
|
| extra_body = { |
| "chat_template_kwargs": {"enable_thinking": False}, |
| "stop": STOP_STRINGS, |
| "stop_token_ids": STOP_TOKEN_IDS, |
| "logits_processors": LOGITS_PROCESSORS, |
| } |
| if extra_body_override: |
| |
| for k, v in extra_body_override.items(): |
| extra_body[k] = v |
|
|
| resp = await client.chat.completions.create( |
| model=model_id, |
| messages=final_messages, |
| temperature=temperature, |
| top_p=top_p, |
| max_tokens=max_tokens, |
| extra_body=extra_body, |
| ) |
| return resp.choices[0].message.content or "" |
|
|
|
|
| async def safe_chat_call(*args, **kwargs) -> Optional[str]: |
| """ |
| Chama chat_call com 1 fallback específico para BadRequest 'Expected 2 output messages...'. |
| Se falhar novamente ou surgir outro erro, retorna None (para descartar a conversa). |
| """ |
| try: |
| return await chat_call(*args, **kwargs) |
| except BadRequestError as e: |
| msg = str(e) |
| |
| |
| try: |
| eb = kwargs.pop("extra_body_override", {}) or {} |
| eb2 = {"chat_template_kwargs": {"enable_thinking": True}} |
| eb2.update(eb) |
| return await chat_call(*args, extra_body_override=eb2, **kwargs) |
| except Exception: |
| pass |
| |
| try: |
| eb = kwargs.pop("extra_body_override", {}) or {} |
| eb2 = dict(eb) |
| eb2.pop("chat_template_kwargs", None) |
| return await chat_call(*args, extra_body_override=eb2, **kwargs) |
| except Exception: |
| return None |
| except Exception: |
| return None |
|
|
| |
| |
| |
| async def generate_user_questions_pair(model_id: str, context_text: str, styles: List[str]) -> List[str]: |
| """ |
| Gera 2 perguntas por contexto com o MENOR nº de chamadas possível. |
| - Se estilos iguais: n=2 em uma chamada. |
| - Se diferentes: JSON q1/q2 em uma chamada. |
| - Fallback: duas chamadas em paralelo. |
| """ |
| s0, s1 = styles[0], styles[1] |
|
|
| |
| if s0 == s1: |
| try: |
| sys = ( |
| "Você é um GERADOR de PERGUNTAS. Use APENAS o CONTEXTO. " |
| "Saída: UMA pergunta em PT-BR, sem comentários." |
| ) |
| msg = [{"role": "system", "content": sys + f"\n\nINSTRUÇÃO DE ESTILO: {QUESTION_STYLE_PROMPTS[s0]}\n\nCONTEXTO:\n{context_text}"}] |
| resp = await client.chat.completions.create( |
| model=model_id, |
| messages=msg, |
| temperature=Q_TEMPERATURE, |
| top_p=Q_TOP_P, |
| max_tokens=Q_MAX_TOKENS, |
| n=2, |
| ) |
| outs = [(c.message.content or "").strip() for c in resp.choices] |
| if len(outs) == 2 and all(outs): |
| return outs |
| except Exception: |
| pass |
|
|
| |
| try: |
| sys = ( |
| "Você é um GERADOR de PERGUNTAS. Use APENAS o CONTEXTO. " |
| "Produza JSON exatamente no formato: {\"q1\": \"...\", \"q2\": \"...\"}." |
| ) |
| style_block = ( |
| f"q1_style: {QUESTION_STYLE_PROMPTS[s0]}\n" |
| f"q2_style: {QUESTION_STYLE_PROMPTS[s1]}" |
| ) |
| msg = [{"role": "system", "content": f"{sys}\n\n{style_block}\n\nCONTEXTO:\n{context_text}"}] |
| resp = await client.chat.completions.create( |
| model=model_id, |
| messages=msg, |
| temperature=Q_TEMPERATURE, |
| top_p=Q_TOP_P, |
| max_tokens=Q_MAX_TOKENS * 2, |
| ) |
| txt = (resp.choices[0].message.content or "").strip() |
| q1 = q2 = None |
| try: |
| obj = json.loads(txt) |
| q1 = (obj.get("q1") or "").strip() |
| q2 = (obj.get("q2") or "").strip() |
| except Exception: |
| parts = [p.strip() for p in txt.split("\n") if p.strip()] |
| if len(parts) >= 2: |
| q1, q2 = parts[0], parts[1] |
| if q1 and q2: |
| return [q1, q2] |
| except Exception: |
| pass |
|
|
| |
| async def _once(sty: str): |
| sys = ( |
| "Você é um GERADOR de PERGUNTAS. Use APENAS o CONTEXTO. " |
| "Saída: apenas UMA pergunta em PT-BR, sem comentários." |
| ) |
| msg = [{"role": "system", "content": sys + f"\n\nINSTRUÇÃO DE ESTILO: {QUESTION_STYLE_PROMPTS[sty]}\n\nCONTEXTO:\n{context_text}"}] |
| r = await client.chat.completions.create( |
| model=model_id, |
| messages=msg, |
| temperature=Q_TEMPERATURE, |
| top_p=Q_TOP_P, |
| max_tokens=Q_MAX_TOKENS, |
| ) |
| return (r.choices[0].message.content or "").strip() |
|
|
| q1, q2 = await asyncio.gather(_once(s0), _once(s1)) |
| return [q1, q2] |
|
|
| |
| |
| |
| async def generate_one_conversation( |
| model_id: str, |
| system_prompt_key: str, |
| system_prompt_text: str, |
| n_turns: int, |
| context_text: str, |
| initial_user: str, |
| question_style: str, |
| ) -> Dict[str, Any]: |
| """ |
| Gera UMA conversa: |
| - Turno 1: initial_user -> assistant |
| - Turnos 2..N: follow-ups condicionados ao histórico desta conversa |
| Output: apenas user/assistant. |
| """ |
| conversation: List[Dict[str, str]] = [] |
|
|
| |
| base_msgs: List[Dict[str, str]] = [] |
| if INCLUDE_SYSTEM and system_prompt_text: |
| base_msgs.append({"role": "system", "content": system_prompt_text}) |
| if context_text: |
| guard = ( |
| "Use PRIORITARIAMENTE o CONTEXTO a seguir. " |
| "Se faltar informação, responda de forma concisa; se não houver dados suficientes, diga: " |
| "'Informação não encontrada no contexto fornecido.'" |
| ) |
| base_msgs.append({"role": "system", "content": f"{guard}\n\n=== CONTEXTO ===\n{context_text}"}) |
|
|
| |
| conversation.append({"role": "user", "content": initial_user}) |
| first_answer = await safe_chat_call(base_msgs + [{"role": "user", "content": initial_user}], model_id, use_magpie_user=False) |
| conversation.append({"role": "assistant", "content": first_answer}) |
|
|
| |
| remaining = max(0, n_turns - 1) |
| hist_msgs = list(base_msgs) + conversation |
| for _ in range(remaining): |
| next_user = await safe_chat_call(hist_msgs, model_id, use_magpie_user=True, question_style=question_style) |
| conversation.append({"role": "user", "content": next_user}) |
| hist_msgs.append({"role": "user", "content": next_user}) |
|
|
| next_assistant = await safe_chat_call(hist_msgs, model_id, use_magpie_user=False) |
| conversation.append({"role": "assistant", "content": next_assistant}) |
| hist_msgs.append({"role": "assistant", "content": next_assistant}) |
|
|
| return {"conversation": conversation} |
|
|
| |
| |
| |
| def _wiki_stream_iter(): |
| from datasets import load_dataset |
| return load_dataset(WIKI_DATASET_ID, WIKI_SUBSET, split="train", streaming=True) |
|
|
| def _extract_context(record: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| txt = record.get(WIKI_TEXT_FIELD, "") |
| if not isinstance(txt, str): return None |
| context_text = _truncate_context(txt) |
| if len(context_text) < WIKI_MIN_CHARS: return None |
| title = record.get("title", "") |
| return {"context_text": context_text, "title": title} |
|
|
| |
| async def _execute_with_concurrency(coros: List[asyncio.Future], metas: List[dict], limit: int): |
| sem = asyncio.Semaphore(limit) |
| async def _runner(idx: int, coro): |
| async with sem: |
| res = await coro |
| return idx, res |
| tasks = [asyncio.create_task(_runner(i, c)) for i, c in enumerate(coros)] |
| try: |
| for done in asyncio.as_completed(tasks): |
| i, res = await done |
| yield res, metas[i] |
| finally: |
| for t in tasks: |
| if not t.done(): |
| t.cancel() |
|
|
| |
| def _read_resume_state(path: str) -> Tuple[int, int]: |
| if not os.path.exists(path) or os.path.getsize(path) == 0: |
| return 0, -1 |
| next_seq_id = 0 |
| last_ctx_id = -1 |
| with open(path, "r", encoding="utf-8") as fin: |
| for line in fin: |
| try: |
| obj = json.loads(line) |
| except Exception: |
| continue |
| if "seq_id" in obj: |
| next_seq_id = max(next_seq_id, int(obj["seq_id"]) + 1) |
| if "context_id" in obj: |
| last_ctx_id = max(last_ctx_id, int(obj["context_id"])) |
| return next_seq_id, last_ctx_id |
|
|
| async def _skip_accepted_contexts(ds_iter, n_to_skip: int) -> int: |
| skipped = 0 |
| if n_to_skip <= 0: |
| return 0 |
| for rec in ds_iter: |
| if _extract_context(rec): |
| skipped += 1 |
| if skipped >= n_to_skip: |
| break |
| return skipped |
|
|
| |
| |
| |
| async def run(): |
| os.makedirs(os.path.dirname(OUTPUT_FILE) or ".", exist_ok=True) |
| model_id = await get_model_id() |
|
|
| |
| next_seq_id, last_ctx_id = _read_resume_state(OUTPUT_FILE) |
| seq_id = next_seq_id |
|
|
| ds_iter = _wiki_stream_iter() |
| _ = await _skip_accepted_contexts(ds_iter, last_ctx_id + 1) |
|
|
| start_ctx = (last_ctx_id + 1) if last_ctx_id >= 0 else 0 |
| global_id = count(start_ctx) |
|
|
| total_remaining = max(0, NUM_ROWS - seq_id) |
| total_batches = math.ceil(total_remaining / BATCH_SIZE) if BATCH_SIZE > 0 else 0 |
|
|
| |
| with open(OUTPUT_FILE, "a", encoding="utf-8") as fout: |
| pbar = tqdm(total=total_batches, desc="Gerando conversas (Magpie + Wikipedia streaming)") |
|
|
| write_lock = asyncio.Lock() |
|
|
| while seq_id < NUM_ROWS: |
| |
| convs_restantes = NUM_ROWS - seq_id |
| max_contexts_este_batch = min(BATCH_SIZE, max(1, math.ceil(convs_restantes / 2))) |
|
|
| |
| batch_contexts: List[dict] = [] |
| for rec in ds_iter: |
| context_dict = _extract_context(rec) |
| if context_dict: |
| ctx_id = next(global_id) |
| batch_contexts.append({**context_dict, "ctx_sample_id": ctx_id}) |
| if len(batch_contexts) >= max_contexts_este_batch: |
| break |
|
|
| if not batch_contexts: |
| break |
|
|
| |
| key = sample_system_prompt_key(CATEGORIES_SYSTEM_PROMPTS) |
| sys_prompt_text = CATEGORIES_SYSTEM_PROMPTS[key][0] |
|
|
| |
| conv_queue: asyncio.Queue = asyncio.Queue(maxsize=QUEUE_MAXSIZE) |
|
|
| |
| qgen_sem = asyncio.Semaphore(MAX_ASYNC_QGEN) |
|
|
| async def qgen_runner(cinfo: dict): |
| async with qgen_sem: |
| ctx_text = cinfo["context_text"] |
| ctx_id = cinfo["ctx_sample_id"] |
| styles = _sample_question_style(k=2) |
| q1, q2 = await generate_user_questions_pair(model_id, ctx_text, styles) |
| |
| await conv_queue.put((ctx_id, ctx_text, q1, styles[0])) |
| await conv_queue.put((ctx_id, ctx_text, q2, styles[1])) |
|
|
| producers = [asyncio.create_task(qgen_runner(cinfo)) for cinfo in batch_contexts] |
|
|
|
|
| |
| |
| async def chat_worker(worker_id: int): |
| nonlocal seq_id |
| while True: |
| item = await conv_queue.get() |
| if item is None: |
| conv_queue.task_done() |
| break |
| ctx_id, ctx_text, question, q_style = item |
| try: |
| async with write_lock: |
| if seq_id >= NUM_ROWS: |
| return |
| r = await generate_one_conversation( |
| model_id=model_id, |
| system_prompt_key=key, |
| system_prompt_text=sys_prompt_text, |
| n_turns=N_TURNS, |
| context_text=ctx_text, |
| initial_user=question, |
| question_style=q_style, |
| |
| ) |
| async with write_lock: |
| if seq_id < NUM_ROWS: |
| record = { |
| "seq_id": seq_id, |
| "conversation": r["conversation"], |
| "question_style": q_style, |
| "context_id": ctx_id, |
| } |
| try: |
| fout.write(json.dumps(record, ensure_ascii=False) + "\n") |
| except Exception: |
| pass |
| seq_id += 1 |
| except DropSample as e: |
| |
| |
| pass |
| except Exception as e: |
| |
| |
| pass |
| finally: |
| conv_queue.task_done() |
|
|
| consumers = [asyncio.create_task(chat_worker(i)) for i in range(MAX_ASYNC_CHAT)] |
|
|
| |
| await asyncio.gather(*producers) |
| for _ in range(MAX_ASYNC_CHAT): |
| await conv_queue.put(None) |
|
|
| |
| await conv_queue.join() |
| await asyncio.gather(*consumers, return_exceptions=True) |
|
|
| pbar.update(1) |
|
|
| pbar.close() |
|
|
| if __name__ == "__main__": |
| asyncio.run(run()) |
|
|