File size: 3,689 Bytes
b4656a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render adjudication rows' states through Qwen3-14B (vLLM) into diverse
natural-language registers while preserving all decision-relevant facts.

Validation: every numeric literal and identifier-ish token in the source
state must appear in the rendered text (case-insensitive). Failures are
dropped — labels are programmatic so a faithful render is all we need.
"""
import json, re, sys, argparse, random

PROMPT = """Rewrite the following internal business document into a different but equally realistic register. Vary the structure freely — e.g. interleaved email thread, policy handbook pages, ticket + attachment layout, memo chain, multi-document case file, table-heavy annex format. You may rename headings, reorder sections, change formatting, and adjust phrasing.

HARD REQUIREMENTS:
- Preserve EVERY number, date, clause/section identifier, entity name, version string, and quoted note — they carry the decision logic.
- Keep all logical relationships intact (which rule overrides which, dates relative to each other, thresholds, definitions).
- Keep the embedded agent/intake notes expressing the same (possibly wrong) recommendation.
- Do NOT state or hint at the correct answer.
- Output ONLY the document text — no preamble, no commentary.

DOCUMENT:
%s"""

NUM = re.compile(r"\d[\d,.:%/\-]*")
ID = re.compile(r"\b[A-Z]{1,4}-?[A-Z0-9]{2,}(?:-[A-Z0-9]{2,})*\b")

def required_tokens(text):
    toks = set(NUM.findall(text)) | set(ID.findall(text))
    # normalize: strip trailing punctuation
    return {t.strip(",.:-") for t in toks if len(t.strip(",.:-")) >= 1}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in", dest="inp", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--n", type=int, default=8000)
    ap.add_argument("--model", default="/ephemeral/models/qwen3-14b")
    args = ap.parse_args()
    rows = [json.loads(l) for l in open(args.inp, encoding="utf-8")]
    rows = [r for r in rows if isinstance(r["state"], str)]
    random.seed(3); random.shuffle(rows)
    rows = rows[: args.n]
    from vllm import LLM, SamplingParams
    from transformers import AutoTokenizer
    llm = LLM(model=args.model, dtype="bfloat16", max_model_len=8192,
              gpu_memory_utilization=0.88, enforce_eager=False)
    ctok = AutoTokenizer.from_pretrained(args.model)
    sp = SamplingParams(temperature=0.85, top_p=0.95, max_tokens=3500)
    prompts = []
    for r in rows:
        m = [{"role": "user", "content": PROMPT % r["state"]}]
        try:
            prompts.append(ctok.apply_chat_template(
                m, tokenize=False, add_generation_prompt=True,
                enable_thinking=False))
        except TypeError:
            prompts.append(ctok.apply_chat_template(
                m, tokenize=False, add_generation_prompt=True)
                + "/no_think\n")
    outs = llm.generate(prompts, sp)
    kept = 0
    with open(args.out, "w") as f:
        for r, o in zip(rows, outs):
            txt = o.outputs[0].text.strip()
            if not txt or len(txt) < 200:
                continue
            need = required_tokens(r["state"])
            low = txt.lower()
            missing = [t for t in need if t.lower() not in low]
            if len(missing) > max(1, len(need) // 12):
                continue
            r2 = dict(r)
            r2["id"] = r["id"] + "-r"
            r2["group_id"] = r["group_id"] + "-r"
            r2["state"] = txt
            r2["source"] = r["source"] + "_render"
            f.write(json.dumps(r2, ensure_ascii=False) + "\n")
            kept += 1
    print(f"rendered+validated {kept}/{len(rows)}")


if __name__ == "__main__":
    main()