uploads / synthgen /generate_cemig.py
EdwardSJ151's picture
Upload folder using huggingface_hub
3af75d1 verified
"""
Synthetic conversation generator (vLLM via OpenAI-compatible API).
Pipeline summary:
1) Stream dataset records.
2) For each record, use its dataset idx as context_id.
3) For each context_id, generate exactly one conversation per question style in ALL_STYLES.
4) Existing JSONL output is scanned to learn which (context_id, style)
pairs already exist, and only missing pairs are generated on reruns.
"""
import os
import json
import math
import asyncio
from typing import Dict, Any, List, Tuple, Optional
from openai import AsyncOpenAI
from tqdm import tqdm
from prompts_cemig import (
RESPONSE_PROMPTS,
QUESTION_STYLE_PROMPTS,
QGEN_SYSTEM_PROMPT,
QGEN_SYSTEM_PROMPT_FIRST,
QGEN_SYSTEM_PROMPT_JSON,
QGEN_SYSTEM_PROMPT_JSON_FIRST,
DEFAULT_QUESTION_KERNEL_PT,
ALL_STYLES,
)
VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "http://10.100.0.111:8021/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"))
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", "60000000"))
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "32"))
N_TURNS = int(os.environ.get("N_TURNS", "3"))
OUTPUT_FILE = os.environ.get("OUTPUT_FILE", "magpie_conversations_cemig_v2_preproc_objetiva.jsonl")
INCLUDE_SYSTEM = True
LOGITS_PROCESSORS: List[str] = []
MAX_ASYNC_TOTAL = int(os.environ.get("MAX_ASYNC", "24"))
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", "cemig-ceia/energy_dataset_v1")
WIKI_DATASET_ID = os.environ.get("WIKI_DATASET_ID", "cemig-ceia/energy_dataset_preproc_v2")
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"))
idx_col_name = os.environ.get("IDX_COL_NAME", "idx")
client = AsyncOpenAI(base_url=VLLM_BASE_URL, api_key=VLLM_API_KEY)
def _normalize_spaces(s: str) -> str:
"""Collapse whitespace."""
return " ".join((s or "").split())
def _truncate_context(txt: str) -> str:
"""
Limit context size by cutting at a sentence boundary near WIKI_MAX_CHARS when possible.
If no good boundary exists, fall back to a hard cut.
"""
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 _wiki_stream_iter():
"""Return a streaming iterator over the dataset."""
from datasets import load_dataset
return load_dataset(WIKI_DATASET_ID, WIKI_SUBSET, split="train", streaming=True)
def _get_train_num_examples() -> Optional[int]:
"""
Get split size from dataset metadata without iterating the dataset.
Returns None if the metadata is not available.
"""
from datasets import load_dataset_builder
builder = load_dataset_builder(WIKI_DATASET_ID, WIKI_SUBSET)
splits = getattr(builder.info, "splits", None)
if not splits or "train" not in splits:
raise RuntimeError("Dataset metadata missing train split size (num_examples).")
n = getattr(splits["train"], "num_examples", None)
if n is None:
raise RuntimeError("Dataset train split size (num_examples) is None; cannot size tqdm without scanning.")
return int(n)
def _extract_context(record: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Extract and validate the text used as context.
Records can be rejected (None) if:
- text is missing or not a string
- text is too short after normalization and truncation
"""
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}
def _skip_until_idx(ds_iter, start_idx: int) -> Optional[Dict[str, Any]]:
"""
Advance a streaming iterator until record[idx_col_name] >= start_idx.
Returns the first matching record so the caller can process it; iterators cannot
be rewound, so without returning it, that record would be lost.
"""
if start_idx <= 0:
return None
for rec in ds_iter:
rid = rec.get(idx_col_name)
if rid is None:
continue
try:
rid_int = int(rid)
except Exception:
continue
if rid_int >= start_idx:
return rec
return None
def _read_next_seq(path: str) -> int:
"""
Compute the next seq_id by scanning the output JSONL.
seq_id is only a running counter for output rows. Resume logic for content is
based on (context_id, question_style), not seq_id.
"""
if not os.path.exists(path) or os.path.getsize(path) == 0:
return 0
next_seq_id = 0
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)
return next_seq_id
def _build_existing_index(path: str) -> Tuple[int, Dict[int, set]]:
"""
Scan OUTPUT_FILE and build:
- present_by_ctx: context_id -> set(question_style) already written
- first_incomplete_ctx: earliest idx that needs work
Because idx is assumed sequential 0..n-1:
- A gap means the missing context_id has zero styles and must be resumed first.
- Otherwise, resume at the first context_id missing at least one style.
- If everything up to the last seen id is complete, resume at (last + 1).
"""
present: Dict[int, set] = {}
if not os.path.exists(path) or os.path.getsize(path) == 0:
return 0, present
with open(path, "r", encoding="utf-8") as fin:
for line in fin:
try:
obj = json.loads(line)
except Exception:
continue
ctx = obj.get("context_id")
sty = obj.get("question_style")
if ctx is None or sty is None:
continue
try:
ctx = int(ctx)
except Exception:
continue
present.setdefault(ctx, set()).add(sty)
if not present:
return 0, present
expected = 0
for ctx_id in sorted(present.keys()):
if ctx_id > expected:
return expected, present
if len(present[ctx_id]) < len(ALL_STYLES):
return ctx_id, present
expected = ctx_id + 1
return expected, present
async def get_model_id() -> str:
"""Pick the first model exposed by the vLLM endpoint."""
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,
) -> str:
"""
Single entry point for LLM calls.
Two modes:
- Assistant response mode: send messages as-is.
- User mode: generate the next user question using the full history and the
same context_text to keep the conversation grounded.
"""
if use_magpie_user:
kernel = QUESTION_STYLE_PROMPTS.get(question_style or "", DEFAULT_QUESTION_KERNEL_PT)
system_content = f"{QGEN_SYSTEM_PROMPT}\n\n{kernel}"
hist_txt = "\n".join(
f"{(m.get('role', '') or '').upper()}: {m.get('content', '')}"
for m in messages
)
user_text = (
f"CONTEXTO:\n{followup_context_text}\n\n"
f"HISTÓRICO:\n{hist_txt}\n\n"
"Gere uma nova pergunta que um usuário faria para continuar a conversa."
)
final_messages = [
{"role": "system", "content": system_content},
{"role": "user", "content": user_text},
]
temperature, top_p, max_tokens = Q_TEMPERATURE, Q_TOP_P, Q_MAX_TOKENS
else:
final_messages = messages
temperature, top_p, max_tokens = RESP_TEMPERATURE, RESP_TOP_P, RESP_MAX_TOKENS
extra_body = {
"chat_template_kwargs": {"enable_thinking": False},
"stop": STOP_STRINGS,
"stop_token_ids": STOP_TOKEN_IDS,
"logits_processors": LOGITS_PROCESSORS,
}
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]:
"""
Swallows exceptions and returns None. This can be used to later identify failed requests and clean them.
"""
try:
return await chat_call(*args, **kwargs)
except Exception:
return None
async def _qgen_single(model_id: str, context_text: str, style: str) -> str:
"""
Generate one user question for a given style. Used as a fallback when batching fails.
"""
system_content = f"{QGEN_SYSTEM_PROMPT_FIRST}\n\n{QUESTION_STYLE_PROMPTS[style]}"
msg = [
{"role": "system", "content": system_content},
{"role": "user", "content": f"CONTEXTO:\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,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
return (r.choices[0].message.content or "").strip()
async def generate_user_questions_pair(model_id: str, context_text: str, styles: List[str]) -> List[str]:
"""
Generate two questions per context when possible, to reduce LLM calls.
- If the two styles are identical: request n=2 completions in a single call.
- Otherwise: request a strict JSON object {"q1": "...", "q2": "..."} that carries
both questions with different style requirements in one response.
- If anything fails fall back to two independent _qgen_single calls.
"""
s0, s1 = styles[0], styles[1]
if s0 == s1:
try:
system_content = f"{QGEN_SYSTEM_PROMPT_FIRST}\n\n{QUESTION_STYLE_PROMPTS[s0]}"
msg = [
{"role": "system", "content": system_content},
{"role": "user", "content": f"CONTEXTO:\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,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
outs = [(c.message.content or "").strip() for c in resp.choices]
if len(outs) == 2 and all(outs):
return outs
except Exception:
pass
try:
style_block = (
f"q1_style: {QUESTION_STYLE_PROMPTS[s0]}\n"
f"q2_style: {QUESTION_STYLE_PROMPTS[s1]}"
)
system_content = f"{QGEN_SYSTEM_PROMPT_JSON_FIRST}\n\n{style_block}"
msg = [
{"role": "system", "content": system_content},
{"role": "user", "content": f"CONTEXTO:\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,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
txt = (resp.choices[0].message.content or "").strip()
# Some models wrap JSON in fences; strip them defensively.
if txt.startswith("```"):
lines = [l for l in txt.split("\n") if not l.strip().startswith("```")]
txt = "\n".join(lines).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
q1, q2 = await asyncio.gather(
_qgen_single(model_id, context_text, s0),
_qgen_single(model_id, context_text, s1),
)
return [q1, q2]
async def generate_one_conversation(
model_id: str,
system_prompt_text: str,
n_turns: int,
context_text: str,
initial_user: str,
question_style: str,
) -> Dict[str, Any]:
"""
Generate a multi-turn conversation for a single (context_id, question_style).
"""
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})
first_user_content = f"CONTEXTO:\n{context_text}\n\n{initial_user}" if context_text else initial_user
conversation.append({"role": "user", "content": initial_user})
first_answer = await safe_chat_call(
base_msgs + [{"role": "user", "content": first_user_content}],
model_id,
use_magpie_user=False,
)
conversation.append({"role": "assistant", "content": first_answer})
remaining = max(0, n_turns - 1)
hist_msgs = list(base_msgs) + [
{"role": "user", "content": first_user_content},
{"role": "assistant", "content": first_answer},
]
for _ in range(remaining):
next_user = await safe_chat_call(
hist_msgs,
model_id,
use_magpie_user=True,
question_style=question_style,
followup_context_text=context_text,
)
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}
async def run():
"""
Main loop: generate up to NUM_ROWS output records in JSONL.
Concurrency model:
- Producers generate initial questions for missing styles and enqueue them.
- Consumers generate full conversations from queued items and write JSONL records.
- write_lock protects seq_id allocation and file writes.
"""
os.makedirs(os.path.dirname(OUTPUT_FILE) or ".", exist_ok=True)
model_id = await get_model_id()
first_incomplete_ctx, present_by_ctx = _build_existing_index(OUTPUT_FILE)
seq_id = _read_next_seq(OUTPUT_FILE)
ds_iter = iter(_wiki_stream_iter())
pending_rec = _skip_until_idx(ds_iter, first_incomplete_ctx)
dataset_n = _get_train_num_examples()
total_remaining = max(0, NUM_ROWS - seq_id)
remaining_ctx = max(0, dataset_n - first_incomplete_ctx)
max_possible_rows = remaining_ctx * len(ALL_STYLES)
# Cap tqdm plan to dataset size
total_remaining = min(total_remaining, max_possible_rows)
contexts_per_batch = max(
1,
min(BATCH_SIZE, math.ceil(total_remaining / max(1, len(ALL_STYLES)))),
)
total_batches = (
math.ceil(total_remaining / (contexts_per_batch * max(1, len(ALL_STYLES))))
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 + dataset)")
write_lock = asyncio.Lock()
while seq_id < NUM_ROWS:
batch_contexts: List[dict] = []
while len(batch_contexts) < contexts_per_batch:
if pending_rec is not None:
rec = pending_rec
pending_rec = None
else:
try:
rec = next(ds_iter)
except StopIteration:
rec = None
if rec is None:
break
rid = rec.get(idx_col_name)
if rid is None:
continue
try:
ctx_id = int(rid)
except Exception:
continue
# Skip fully complete contexts to avoid wasted work on reruns.
if len(present_by_ctx.get(ctx_id, set())) >= len(ALL_STYLES):
continue
context_dict = _extract_context(rec)
if context_dict:
batch_contexts.append({**context_dict, "ctx_sample_id": ctx_id})
if not batch_contexts:
break
conv_queue: asyncio.Queue = asyncio.Queue(maxsize=QUEUE_MAXSIZE)
qgen_sem = asyncio.Semaphore(MAX_ASYNC_QGEN)
async def qgen_runner(cinfo: dict):
"""
Producer for one context.
Enqueues work items of shape:
(context_id, context_text, initial_question, style)
"""
async with qgen_sem:
ctx_text = cinfo["context_text"]
ctx_id = cinfo["ctx_sample_id"]
already = present_by_ctx.get(ctx_id, set())
missing = [s for s in ALL_STYLES if s not in already]
if not missing:
return
pairs: List[Tuple[str, Optional[str]]] = []
i = 0
while i < len(missing):
if i + 1 < len(missing):
pairs.append((missing[i], missing[i + 1]))
i += 2
else:
pairs.append((missing[i], None))
i += 1
for s0, s1 in pairs:
try:
if s1 is None:
q = await _qgen_single(model_id, ctx_text, s0)
await conv_queue.put((ctx_id, ctx_text, q, s0))
else:
q1, q2 = await generate_user_questions_pair(model_id, ctx_text, [s0, s1])
await conv_queue.put((ctx_id, ctx_text, q1, s0))
await conv_queue.put((ctx_id, ctx_text, q2, s1))
except Exception:
import traceback
traceback.print_exc()
producers = [asyncio.create_task(qgen_runner(cinfo)) for cinfo in batch_contexts]
async def chat_worker():
"""
Consumer that turns queued items into JSONL records.
None sentinel values are used to stop workers after producers finish.
"""
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_text=RESPONSE_PROMPTS[q_style],
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,
}
fout.write(json.dumps(record, ensure_ascii=False) + "\n")
fout.flush()
present_by_ctx.setdefault(ctx_id, set()).add(q_style)
seq_id += 1
except Exception:
import traceback
traceback.print_exc()
finally:
conv_queue.task_done()
consumers = [asyncio.create_task(chat_worker()) for _ 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())