File size: 23,677 Bytes
3af75d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# magpie_vllm_async.py
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  # dict: {name: (prompt, prob)}

# ---------------------------------------------------------------------
# Config vLLM OpenAI-compatible
# ---------------------------------------------------------------------
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")

# Decoding (globais)
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

# Decoding diferenciada (resposta vs pergunta)
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"))

# ---------------------------------------------------------------------
# Controle de execução
# ---------------------------------------------------------------------
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  # (não será salvo no output)
LOGITS_PROCESSORS: List[str] = []

# Concorrência
MAX_ASYNC_TOTAL = int(os.environ.get("MAX_ASYNC", "256"))
CHAT_SHARE      = float(os.environ.get("CHAT_SHARE", "0.8"))  # 80% chat / 20% qgen
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)))

# ---------------------------------------------------------------------
# Dataset Wikipedia em streaming (HuggingFaceFW/clean-wikipedia, 'pt')
# ---------------------------------------------------------------------
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", "40000")) # Not resumos
WIKI_MAX_CHARS   = int(os.environ.get("WIKI_MAX_CHARS", "15000")) # Resumos
WIKI_MIN_CHARS   = int(os.environ.get("WIKI_MIN_CHARS", "600"))

# ---------------------------------------------------------------------
# Estilos de PERGUNTA
# ---------------------------------------------------------------------
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
# ---------------------------------------------------------------------
client = AsyncOpenAI(base_url=VLLM_BASE_URL, api_key=VLLM_API_KEY)

# ---------------------------------------------------------------------
# Utilidades (sem regex)
# ---------------------------------------------------------------------
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,   # já existia se você aplicou a versão anterior; se não, pode deixar None
    extra_body_override: Optional[dict] = None,    # NEW
) -> str:
    # Pergunta (follow-up) vs. resposta
    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:
        # sobrescreve/mescla campos problemáticos quando necessário (fallback)
        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)
        # Fallback: alguns servidores esperam 'enable_thinking=True' ou rejeitam o campo.
        # 1) tenta habilitar
        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
        # 2) tenta remover o campo por completo
        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

# ---------------------------------------------------------------------
# Geração de PERGUNTA — otimizada (n=2/JSON/fallback paralelo)
# ---------------------------------------------------------------------
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]

    # Caso A: estilos iguais → n=2
    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  # fallback

    # Caso B: estilos diferentes → JSON em uma chamada
    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  # fallback

    # Fallback: duas chamadas em paralelo
    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]

# ---------------------------------------------------------------------
# Conversa (apenas user/assistant no output)
# ---------------------------------------------------------------------
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]] = []

    # Mensagens base (NÃO entram no output)
    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}"})

    # Turno 1 (Q→A)
    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})

    # Follow-ups (turnos 2..N)
    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}

# ---------------------------------------------------------------------
# Streaming do dataset + helpers
# ---------------------------------------------------------------------
def _wiki_stream_iter():
    from datasets import load_dataset  # lazy import
    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}

# --- Execução com limite de concorrência (utilitário genérico; opcional) ---
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()

# --- Resume helpers ---
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

# ---------------------------------------------------------------------
# Runner com pipeline produtor→fila→consumidores (80/20 chat)
# ---------------------------------------------------------------------
async def run():
    os.makedirs(os.path.dirname(OUTPUT_FILE) or ".", exist_ok=True)
    model_id = await get_model_id()

    # === RESUME ===
    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

    # Abra em append
    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:
            # Limita contextos por batch (2 conversas/ctx)
            convs_restantes = NUM_ROWS - seq_id
            max_contexts_este_batch = min(BATCH_SIZE, max(1, math.ceil(convs_restantes / 2)))

            # Coleta contextos aceitos
            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  # fim do stream

            # Estilo da RESPOSTA por batch
            key = sample_system_prompt_key(CATEGORIES_SYSTEM_PROMPTS)
            sys_prompt_text = CATEGORIES_SYSTEM_PROMPTS[key][0]

            # ===== Pipeline =====
            conv_queue: asyncio.Queue = asyncio.Queue(maxsize=QUEUE_MAXSIZE)

            # PRODUTORES (QGEN)
            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)
                    # Enfileira duas conversas
                    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]


            # CONSUMIDORES (CHAT)
    
            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,
                            # diss_chunks=chunks  # se você estiver com o modo dissertação
                        )
                        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:
                        # Log leve e segue
                        # print(f"[drop] ctx={ctx_id}: {e}")
                        pass
                    except Exception as e:
                        # Qualquer outra falha também não para o worker
                        # print(f"[erro] ctx={ctx_id}: {e}")
                        pass
                    finally:
                        conv_queue.task_done()

            consumers = [asyncio.create_task(chat_worker(i)) for i in range(MAX_ASYNC_CHAT)]

            # Aguarda produtores concluírem e envia sentinelas
            await asyncio.gather(*producers)
            for _ in range(MAX_ASYNC_CHAT):
                await conv_queue.put(None)

            # Aguarda fila esvaziar e consumidores finalizarem
            await conv_queue.join()
            await asyncio.gather(*consumers, return_exceptions=True)

            pbar.update(1)

        pbar.close()

if __name__ == "__main__":
    asyncio.run(run())