66 lines
2.8 KiB
Python
66 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Concatenate English prose and Kubernetes text into one pretraining file.
|
|
|
|
Kubernetes records are repeated --repeats times so they are a small but real share of
|
|
the words. The file is not shuffled: kubertrainer's Trainer shuffles each epoch, so
|
|
sharding order is not needed here. The manifest records the word share of each source.
|
|
Held-out eval documents must already be excluded from the English input.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
def copy_lines(source, target, repeats):
|
|
"""Copy records repeats times, returning (records, words) written."""
|
|
records = words = 0
|
|
for _ in range(repeats):
|
|
with source.open(encoding="utf-8") as stream:
|
|
for line in stream:
|
|
target.write(line)
|
|
records += 1
|
|
words += len(json.loads(line)["text"].split())
|
|
return records, words
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--english", required=True, type=Path)
|
|
parser.add_argument("--kubernetes", action="append", required=True, type=Path,
|
|
help="Kubernetes text file; repeat for each source")
|
|
parser.add_argument("--repeats", type=int, default=3,
|
|
help="Times to repeat each Kubernetes record (default 3)")
|
|
parser.add_argument("--output-file", required=True, type=Path)
|
|
parser.add_argument("--manifest-file", required=True, type=Path)
|
|
args = parser.parse_args()
|
|
if args.repeats < 1:
|
|
parser.error("--repeats must be at least 1")
|
|
for path in (args.output_file, args.manifest_file):
|
|
if path.exists():
|
|
parser.error(f"refusing to overwrite: {path}")
|
|
|
|
sources = {}
|
|
with args.output_file.open("x", encoding="utf-8") as target:
|
|
records, words = copy_lines(args.english, target, 1)
|
|
sources["english"] = {"records": records, "words": words}
|
|
for path in args.kubernetes:
|
|
records, words = copy_lines(path, target, args.repeats)
|
|
sources[path.stem] = {"records": records, "words": words, "repeats": args.repeats}
|
|
|
|
total_words = sum(source["words"] for source in sources.values())
|
|
for name, source in sources.items():
|
|
source["share_of_words"] = round(source["words"] / total_words, 4)
|
|
manifest = {
|
|
"output": {"path": str(args.output_file), "words": total_words,
|
|
"records": sum(s["records"] for s in sources.values())},
|
|
"sources": sources,
|
|
"inputs": [str(args.english), *map(str, args.kubernetes)],
|
|
}
|
|
args.manifest_file.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
|
print(json.dumps(manifest["sources"], indent=2))
|
|
print(f"total words: {total_words}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|