File size: 9,346 Bytes
3c0bb29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build a training-oriented source mix from existing Polish DynaWord parquets.

The raw corpus is provenance-first. This script creates a training view with:
- temperature/sqrt sampling by source,
- a hard cap for legal/parliamentary sources,
- an optional high-quality final-phase manifest,
- optional sampled parquet materialization.
"""

from __future__ import annotations

import argparse
import json
import math
import random
from pathlib import Path

import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq


def load_config(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def source_inventory(data_root: Path) -> dict[str, dict]:
    inventory = {}
    for parquet_path in sorted((data_root / "data").glob("*/*.parquet")):
        source = parquet_path.parent.name
        stats_path = parquet_path.with_name(f"{source}.stats.json")
        docs = None
        tokens = None
        if stats_path.exists():
            stats = json.loads(stats_path.read_text(encoding="utf-8"))
            docs = int(stats.get("kept", 0))
            tokens = int(stats.get("tokens", 0))

        if not docs or not tokens:
            pf = pq.ParquetFile(parquet_path)
            docs = pf.metadata.num_rows
            tokens = 0
            for rg in range(pf.num_row_groups):
                tbl = pf.read_row_group(rg, columns=["token_count"])
                tokens += int(pc.sum(tbl["token_count"]).as_py())

        inventory[source] = {
            "path": str(parquet_path),
            "docs": docs,
            "tokens": tokens,
        }
    return inventory


def normalize(weights: dict[str, float], total: float = 1.0) -> dict[str, float]:
    denom = sum(weights.values())
    if denom <= 0:
        return {k: 0.0 for k in weights}
    return {k: v / denom * total for k, v in weights.items()}


def compute_mix(inventory: dict[str, dict], config: dict) -> dict[str, dict]:
    alpha = float(config.get("temperature_alpha", 0.5))
    multipliers = config.get("source_multipliers", {})
    legal_sources = set(config.get("legal_sources", []))
    legal_cap = float(config.get("legal_cap_share", 0.15))

    base_weights = {}
    for source, meta in inventory.items():
        multiplier = float(multipliers.get(source, 1.0))
        base_weights[source] = math.pow(meta["tokens"], alpha) * multiplier

    legal_weights = {s: w for s, w in base_weights.items() if s in legal_sources}
    other_weights = {s: w for s, w in base_weights.items() if s not in legal_sources}
    raw_share = normalize(base_weights)
    raw_legal_share = sum(raw_share.get(s, 0.0) for s in legal_sources)

    if raw_legal_share > legal_cap and other_weights:
        legal_share = legal_cap
    else:
        legal_share = raw_legal_share
    other_share = max(0.0, 1.0 - legal_share)

    final_shares = {}
    final_shares.update(normalize(legal_weights, legal_share))
    final_shares.update(normalize(other_weights, other_share))

    mix = {}
    total_tokens = sum(meta["tokens"] for meta in inventory.values())
    for source, meta in inventory.items():
        raw_corpus_share = meta["tokens"] / total_tokens if total_tokens else 0.0
        target_share = final_shares.get(source, 0.0)
        mix[source] = {
            **meta,
            "raw_corpus_share": raw_corpus_share,
            "target_share": target_share,
            "sampling_multiplier": target_share / raw_corpus_share if raw_corpus_share else 0.0,
            "is_legal_capped": source in legal_sources,
        }
    return dict(sorted(mix.items()))


def add_token_targets(mix: dict[str, dict], token_budget: int | None) -> None:
    for meta in mix.values():
        target_tokens = int(round(meta["target_share"] * token_budget)) if token_budget else 0
        meta["target_tokens"] = target_tokens
        meta["sampling_probability"] = min(1.0, target_tokens / meta["tokens"]) if token_budget else 0.0


def write_report(mix: dict[str, dict], config: dict, out_path: Path, token_budget: int | None) -> None:
    legal_sources = set(config.get("legal_sources", []))
    raw_legal = sum(v["raw_corpus_share"] for k, v in mix.items() if k in legal_sources)
    target_legal = sum(v["target_share"] for k, v in mix.items() if k in legal_sources)
    lines = [
        "# Polish DynaWord training mix",
        "",
        f"- config: `{config.get('name', 'unnamed')}`",
        f"- temperature alpha: `{config.get('temperature_alpha', 0.5)}`",
        f"- legal/parliamentary raw share: `{raw_legal * 100:.2f}%`",
        f"- legal/parliamentary target share: `{target_legal * 100:.2f}%`",
    ]
    if token_budget:
        lines.append(f"- token budget: `{token_budget:,}`")
    lines.extend([
        "",
        "| source | raw tokens | raw share | target share | sampling multiplier | target tokens |",
        "|---|---:|---:|---:|---:|---:|",
    ])
    for source, meta in mix.items():
        lines.append(
            f"| `{source}` | {meta['tokens']:,} | {meta['raw_corpus_share'] * 100:.2f}% | "
            f"{meta['target_share'] * 100:.2f}% | {meta['sampling_multiplier']:.3f} | "
            f"{meta['target_tokens']:,} |"
        )

    final_phase_sources = config.get("final_phase_sources", [])
    final_phase_share = float(config.get("final_phase_share", 0.10))
    lines.extend([
        "",
        "## Final training phase",
        "",
        f"Reserve the last `{final_phase_share * 100:.0f}%` of training tokens for higher-quality sources:",
        "",
    ])
    for source in final_phase_sources:
        lines.append(f"- `{source}`")

    missing = config.get("target_missing_sources", [])
    if missing:
        lines.extend(["", "## Missing source classes for v0.3+", ""])
        for item in missing:
            lines.append(f"- {item}")

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def write_manifest(mix: dict[str, dict], out_path: Path) -> None:
    payload = {
        "sources": [
            {
                "source": source,
                "path": meta["path"],
                "tokens": meta["tokens"],
                "raw_corpus_share": meta["raw_corpus_share"],
                "target_share": meta["target_share"],
                "target_tokens": meta["target_tokens"],
                "sampling_probability": meta["sampling_probability"],
            }
            for source, meta in mix.items()
        ]
    }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def sample_source(source: str, meta: dict, seed: int) -> pa.Table:
    rng = random.Random(f"{seed}:{source}")
    target = meta["target_tokens"]
    if target <= 0:
        return pa.table({})

    pf = pq.ParquetFile(meta["path"])
    batches = []
    sampled_tokens = 0
    probability = meta["sampling_probability"]
    for rg in range(pf.num_row_groups):
        tbl = pf.read_row_group(rg)
        keep = [rng.random() < probability for _ in range(tbl.num_rows)]
        if not any(keep):
            continue
        sampled = tbl.filter(pa.array(keep))
        batches.append(sampled)
        sampled_tokens += int(pc.sum(sampled["token_count"]).as_py())
        if sampled_tokens >= target:
            break

    return pa.concat_tables(batches, promote_options="default") if batches else pa.table({})


def write_sampled_parquet(mix: dict[str, dict], out_path: Path, seed: int) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    writer = None
    try:
        for source, meta in mix.items():
            tbl = sample_source(source, meta, seed)
            if tbl.num_rows == 0:
                continue
            if writer is None:
                writer = pq.ParquetWriter(out_path, tbl.schema, compression="zstd")
            writer.write_table(tbl)
            print(f"{source}: wrote {tbl.num_rows:,} docs")
    finally:
        if writer is not None:
            writer.close()


def parse_args() -> argparse.Namespace:
    ap = argparse.ArgumentParser()
    ap.add_argument("--data-root", type=Path, default=Path("."))
    ap.add_argument("--config", type=Path, default=Path("configs/training_mix_v0_3.json"))
    ap.add_argument("--token-budget", type=int, default=None)
    ap.add_argument("--out-report", type=Path, default=Path("artifacts/training_mix_v0_3.md"))
    ap.add_argument("--out-manifest", type=Path, default=Path("artifacts/training_mix_v0_3.json"))
    ap.add_argument("--write-parquet", type=Path, default=None)
    ap.add_argument("--seed", type=int, default=13)
    return ap.parse_args()


def main() -> None:
    args = parse_args()
    config = load_config(args.config)
    inventory = source_inventory(args.data_root)
    mix = compute_mix(inventory, config)
    add_token_targets(mix, args.token_budget)
    write_report(mix, config, args.out_report, args.token_budget)
    write_manifest(mix, args.out_manifest)
    if args.write_parquet:
        if not args.token_budget:
            raise SystemExit("--write-parquet requires --token-budget")
        write_sampled_parquet(mix, args.write_parquet, args.seed)
    print(f"wrote: {args.out_report}")
    print(f"wrote: {args.out_manifest}")


if __name__ == "__main__":
    main()