Release vimeml-tiny-zh-v1 (step 844730): FP32 bundle, INT8 Core ML packages, source snapshot (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- source/scripts/training/train_v4.py +33 -0
- source/scripts/training/train_v41.py +37 -0
- source/scripts/training/train_v42.py +53 -0
- source/scripts/training/train_v43.py +53 -0
- source/scripts/training/train_v44.py +73 -0
- source/scripts/training/train_v45.py +80 -0
- source/scripts/training/train_v5.py +53 -0
- source/scripts/training/train_wandb.py +107 -0
- source/scripts/training/train_zh13.py +72 -0
- source/src/vimeml/__init__.py +1 -0
- source/src/vimeml/__pycache__/__init__.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__init__.py +1 -0
- source/src/vimeml/benchmarks/__pycache__/__init__.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/ajimee.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/comparison.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/evaluate_ajimee.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/expanded_ime.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/predict_zh.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/__pycache__/zh13_lm_scores.cpython-313.pyc +0 -0
- source/src/vimeml/benchmarks/ajimee.py +119 -0
- source/src/vimeml/benchmarks/comparison.py +74 -0
- source/src/vimeml/benchmarks/development.py +571 -0
- source/src/vimeml/benchmarks/evaluate.py +149 -0
- source/src/vimeml/benchmarks/evaluate_ajimee.py +253 -0
- source/src/vimeml/benchmarks/expanded_ime.py +118 -0
- source/src/vimeml/benchmarks/generate.py +490 -0
- source/src/vimeml/benchmarks/hybrid.py +346 -0
- source/src/vimeml/benchmarks/notation.py +64 -0
- source/src/vimeml/benchmarks/predict_zh.py +315 -0
- source/src/vimeml/benchmarks/readings.py +66 -0
- source/src/vimeml/benchmarks/standard_ime.py +69 -0
- source/src/vimeml/benchmarks/statistics.py +123 -0
- source/src/vimeml/benchmarks/zh13_judge.py +373 -0
- source/src/vimeml/benchmarks/zh13_lm_scores.py +135 -0
- source/src/vimeml/benchmarks/zh_baselines.py +193 -0
- source/src/vimeml/benchmarks/zh_v1_confirm.py +169 -0
- source/src/vimeml/corpus/__init__.py +1 -0
- source/src/vimeml/corpus/build.py +241 -0
- source/src/vimeml/corpus/zh_filter.py +165 -0
- source/src/vimeml/data/__init__.py +1 -0
- source/src/vimeml/data/annotations.py +119 -0
- source/src/vimeml/data/build.py +585 -0
- source/src/vimeml/data/clean.py +60 -0
- source/src/vimeml/data/corpus_export.py +155 -0
- source/src/vimeml/data/corpus_parts.py +200 -0
- source/src/vimeml/data/merge_parts.py +137 -0
- source/src/vimeml/data/merge_parts_fast.py +463 -0
- source/src/vimeml/data/preprocess_part.py +106 -0
- source/src/vimeml/data/readers.py +151 -0
- source/src/vimeml/data/segment.py +240 -0
source/scripts/training/train_v4.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit V4 training entry; importing it never starts training."""
|
| 2 |
+
import sys
|
| 3 |
+
import argparse
|
| 4 |
+
import tomllib
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 8 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 9 |
+
|
| 10 |
+
from vimeml.training.model_factory_v4 import register_v4
|
| 11 |
+
from vimeml.training.train import main as training_main
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main(argv=None):
|
| 15 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 16 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/train-v4-b.toml")
|
| 17 |
+
parser.add_argument("--resume", action="store_true")
|
| 18 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 19 |
+
args = parser.parse_args(argv)
|
| 20 |
+
config = tomllib.loads(args.config.read_text(encoding="utf-8"))
|
| 21 |
+
if config.get("architecture") != "tiny_gpt_v4":
|
| 22 |
+
parser.error("This entry point accepts only tiny_gpt_v4 configurations")
|
| 23 |
+
register_v4()
|
| 24 |
+
# Reuse the established tracking dispatch, including its offline mode.
|
| 25 |
+
forwarded = ["--config", str(args.config.resolve())]
|
| 26 |
+
if args.resume:
|
| 27 |
+
forwarded.append("--resume")
|
| 28 |
+
if args.dry_run:
|
| 29 |
+
forwarded.append("--dry-run")
|
| 30 |
+
return training_main(forwarded)
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
main()
|
source/scripts/training/train_v41.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal V4.1 random-initialized joint pretraining entry point."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import tomllib
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 7 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 12 |
+
parser.add_argument('--config',type=Path,default=ROOT/'configs/train-v41.toml')
|
| 13 |
+
parser.add_argument('--resume',action='store_true')
|
| 14 |
+
args=parser.parse_args()
|
| 15 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 16 |
+
output=ROOT/config['output_dir']
|
| 17 |
+
logs=ROOT/config['log_dir']
|
| 18 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 19 |
+
parser.error('Fresh V4.1 output/log directories must be empty')
|
| 20 |
+
if args.resume and not (output/'last.pt').exists():
|
| 21 |
+
parser.error('No V4.1 checkpoint to resume')
|
| 22 |
+
import wandb
|
| 23 |
+
directory=ROOT/'artifacts/tracking'
|
| 24 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 25 |
+
with wandb.init(project=config['tracking']['project'],name=output.name,group=output.name,
|
| 26 |
+
mode='online',dir=str(directory),sync_tensorboard=True,save_code=False,force=True,
|
| 27 |
+
config=config,settings=wandb.Settings(disable_git=True,init_timeout=30)) as cloud:
|
| 28 |
+
from vimeml.training.data import write_json
|
| 29 |
+
write_json(directory/f'{output.name}-live.json',{'id':cloud.id,'url':cloud.url,'resume':args.resume})
|
| 30 |
+
print(f'W&B run: {cloud.url}',flush=True)
|
| 31 |
+
from vimeml.training.joint_v41 import run
|
| 32 |
+
result=run(config,args.resume)
|
| 33 |
+
cloud.summary.update({'training_result':result})
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__=='__main__':
|
| 37 |
+
main()
|
source/scripts/training/train_v42.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal V4.2 LM+chat pretraining entry point; optional W&B tracking."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import tomllib
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 7 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 12 |
+
parser.add_argument('--config',type=Path,default=ROOT/'configs/train-v42.toml')
|
| 13 |
+
parser.add_argument('--resume',action='store_true')
|
| 14 |
+
parser.add_argument('--dry-run',action='store_true',
|
| 15 |
+
help='Verify configuration, code and data identities, then exit')
|
| 16 |
+
args=parser.parse_args()
|
| 17 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 18 |
+
output=ROOT/config['output_dir']
|
| 19 |
+
logs=ROOT/config['log_dir']
|
| 20 |
+
if args.dry_run:
|
| 21 |
+
from vimeml.training.joint_v42 import build_plan
|
| 22 |
+
plan=build_plan(config,ROOT,verify_files=True)
|
| 23 |
+
print({'stage':plan['stage'],'parameters':plan['parameters'],
|
| 24 |
+
'max_steps':plan['settings']['max_steps'],
|
| 25 |
+
'updates_per_epoch':plan['settings']['updates_per_epoch'][:3]+['...'],
|
| 26 |
+
'required_files':len(plan['required_files'])})
|
| 27 |
+
return
|
| 28 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 29 |
+
parser.error('Fresh V4.2 output/log directories must be empty')
|
| 30 |
+
if args.resume and not (output/'last.pt').exists():
|
| 31 |
+
parser.error('No V4.2 checkpoint to resume')
|
| 32 |
+
from vimeml.training.joint_v42 import run
|
| 33 |
+
tracking=config.get('tracking',{})
|
| 34 |
+
if not tracking.get('enabled'):
|
| 35 |
+
result=run(config,args.resume)
|
| 36 |
+
print(result,flush=True)
|
| 37 |
+
return
|
| 38 |
+
import wandb
|
| 39 |
+
directory=ROOT/'artifacts/tracking'
|
| 40 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 41 |
+
with wandb.init(project=tracking.get('project','vimeml'),name=output.name,group=output.name,
|
| 42 |
+
mode=tracking.get('mode','online'),dir=str(directory),sync_tensorboard=True,
|
| 43 |
+
save_code=False,force=True,config=config,
|
| 44 |
+
settings=wandb.Settings(disable_git=True,init_timeout=30)) as cloud:
|
| 45 |
+
from vimeml.training.data import write_json
|
| 46 |
+
write_json(directory/f'{output.name}-live.json',{'id':cloud.id,'url':cloud.url,'resume':args.resume})
|
| 47 |
+
print(f'W&B run: {cloud.url}',flush=True)
|
| 48 |
+
result=run(config,args.resume)
|
| 49 |
+
cloud.summary.update({'training_result':result})
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__=='__main__':
|
| 53 |
+
main()
|
source/scripts/training/train_v43.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal V4.3 LM+chat pretraining entry point; optional W&B tracking."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import tomllib
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 7 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 12 |
+
parser.add_argument('--config',type=Path,default=ROOT/'configs/train-v43.toml')
|
| 13 |
+
parser.add_argument('--resume',action='store_true')
|
| 14 |
+
parser.add_argument('--dry-run',action='store_true',
|
| 15 |
+
help='Verify configuration, code and data identities, then exit')
|
| 16 |
+
args=parser.parse_args()
|
| 17 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 18 |
+
output=ROOT/config['output_dir']
|
| 19 |
+
logs=ROOT/config['log_dir']
|
| 20 |
+
if args.dry_run:
|
| 21 |
+
from vimeml.training.joint_v43 import build_plan
|
| 22 |
+
plan=build_plan(config,ROOT,verify_files=True)
|
| 23 |
+
print({'stage':plan['stage'],'parameters':plan['parameters'],
|
| 24 |
+
'max_steps':plan['settings']['max_steps'],
|
| 25 |
+
'updates_per_epoch':plan['settings']['updates_per_epoch'][:3]+['...'],
|
| 26 |
+
'required_files':len(plan['required_files'])})
|
| 27 |
+
return
|
| 28 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 29 |
+
parser.error('Fresh V4.3 output/log directories must be empty')
|
| 30 |
+
if args.resume and not (output/'last.pt').exists():
|
| 31 |
+
parser.error('No V4.3 checkpoint to resume')
|
| 32 |
+
from vimeml.training.joint_v43 import run
|
| 33 |
+
tracking=config.get('tracking',{})
|
| 34 |
+
if not tracking.get('enabled'):
|
| 35 |
+
result=run(config,args.resume)
|
| 36 |
+
print(result,flush=True)
|
| 37 |
+
return
|
| 38 |
+
import wandb
|
| 39 |
+
directory=ROOT/'artifacts/tracking'
|
| 40 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 41 |
+
with wandb.init(project=tracking.get('project','vimeml'),name=output.name,group=output.name,
|
| 42 |
+
mode=tracking.get('mode','online'),dir=str(directory),sync_tensorboard=True,
|
| 43 |
+
save_code=False,force=True,config=config,
|
| 44 |
+
settings=wandb.Settings(disable_git=True,init_timeout=30)) as cloud:
|
| 45 |
+
from vimeml.training.data import write_json
|
| 46 |
+
write_json(directory/f'{output.name}-live.json',{'id':cloud.id,'url':cloud.url,'resume':args.resume})
|
| 47 |
+
print(f'W&B run: {cloud.url}',flush=True)
|
| 48 |
+
result=run(config,args.resume)
|
| 49 |
+
cloud.summary.update({'training_result':result})
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__=='__main__':
|
| 53 |
+
main()
|
source/scripts/training/train_v44.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V4.4 ablation-arm pretraining entry point; W&B without any machine-wide login.
|
| 2 |
+
|
| 3 |
+
Credentials come only from the environment (WANDB_API_KEY, optional WANDB_ENTITY),
|
| 4 |
+
as `cluster_v44.sh` sets them from a private file with isolated W&B directories.
|
| 5 |
+
Without a key, or when online initialization fails, the run logs offline under
|
| 6 |
+
artifacts/tracking/<model>/ for a later `wandb sync`; training never waits on W&B.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import sys
|
| 12 |
+
import tomllib
|
| 13 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 14 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 19 |
+
parser.add_argument('--config',type=Path,required=True)
|
| 20 |
+
parser.add_argument('--resume',action='store_true')
|
| 21 |
+
parser.add_argument('--dry-run',action='store_true',
|
| 22 |
+
help='Verify configuration, code and data identities, then exit')
|
| 23 |
+
args=parser.parse_args()
|
| 24 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 25 |
+
output=ROOT/config['output_dir']
|
| 26 |
+
logs=ROOT/config['log_dir']
|
| 27 |
+
if args.dry_run:
|
| 28 |
+
from vimeml.training.joint_v44 import build_plan
|
| 29 |
+
plan=build_plan(config,ROOT,verify_files=True)
|
| 30 |
+
print({'stage':plan['stage'],'arm':config['arm'],'parameters':plan['parameters'],
|
| 31 |
+
'max_steps':plan['settings']['max_steps'],
|
| 32 |
+
'updates_per_epoch':plan['settings']['updates_per_epoch'][:3]+['...'],
|
| 33 |
+
'required_files':len(plan['required_files'])})
|
| 34 |
+
return
|
| 35 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 36 |
+
parser.error('Fresh V4.4 output/log directories must be empty')
|
| 37 |
+
if args.resume and not (output/'last.pt').exists():
|
| 38 |
+
parser.error('No V4.4 checkpoint to resume')
|
| 39 |
+
from vimeml.training.joint_v44 import run
|
| 40 |
+
tracking=config.get('tracking',{})
|
| 41 |
+
if not tracking.get('enabled'):
|
| 42 |
+
result=run(config,args.resume)
|
| 43 |
+
print(result,flush=True)
|
| 44 |
+
return
|
| 45 |
+
import wandb
|
| 46 |
+
from vimeml.training.data import write_json
|
| 47 |
+
directory=ROOT/'artifacts/tracking'/output.name
|
| 48 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 49 |
+
def start(mode):
|
| 50 |
+
return wandb.init(project=tracking.get('project','vimeml'),entity=os.environ.get('WANDB_ENTITY'),
|
| 51 |
+
group=tracking['group'],name=config['arm']+('-resume' if args.resume else ''),
|
| 52 |
+
job_type='pretraining',tags=['v4.4',config['arm']],mode=mode,dir=str(directory),
|
| 53 |
+
sync_tensorboard=True,save_code=False,config=config,
|
| 54 |
+
settings=wandb.Settings(disable_git=True,init_timeout=90))
|
| 55 |
+
mode=tracking.get('mode','online') if os.environ.get('WANDB_API_KEY') else 'offline'
|
| 56 |
+
try:
|
| 57 |
+
cloud=start(mode)
|
| 58 |
+
except Exception as error:
|
| 59 |
+
if mode=='offline':
|
| 60 |
+
raise
|
| 61 |
+
print(f'W&B online initialization failed ({type(error).__name__}: {error}); logging offline',flush=True)
|
| 62 |
+
mode='offline'
|
| 63 |
+
cloud=start(mode)
|
| 64 |
+
with cloud:
|
| 65 |
+
write_json(directory/f'live-{cloud.id}.json',{'id':cloud.id,'url':cloud.url if mode!='offline' else None,
|
| 66 |
+
'mode':mode,'resume':args.resume,'directory':str(directory)})
|
| 67 |
+
print(f'W&B run ({mode}): {cloud.url if mode!="offline" else directory}',flush=True)
|
| 68 |
+
result=run(config,args.resume)
|
| 69 |
+
cloud.summary.update({'training_result':result})
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__=='__main__':
|
| 73 |
+
main()
|
source/scripts/training/train_v45.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V4.5 distillation-student entry point; W&B without any machine-wide login.
|
| 2 |
+
|
| 3 |
+
Credentials come only from the environment (WANDB_API_KEY, optional WANDB_ENTITY),
|
| 4 |
+
as `cluster_v45.sh` sets them from a private file with isolated W&B directories.
|
| 5 |
+
Without a key, or when online initialization fails, the run logs offline under
|
| 6 |
+
artifacts/tracking/<model>/ for a later `wandb sync`; training never waits on W&B.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import sys
|
| 12 |
+
import tomllib
|
| 13 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 14 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 19 |
+
parser.add_argument('--config',type=Path,required=True)
|
| 20 |
+
parser.add_argument('--resume',action='store_true')
|
| 21 |
+
parser.add_argument('--dry-run',action='store_true',
|
| 22 |
+
help='Verify configuration, code, data and teacher identities, then exit')
|
| 23 |
+
parser.add_argument('--smoke',type=int,default=0,
|
| 24 |
+
help='Run N real updates into <output>-smoke without W&B, to check memory and speed')
|
| 25 |
+
args=parser.parse_args()
|
| 26 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 27 |
+
if args.smoke:
|
| 28 |
+
config['training']['smoke_updates']=args.smoke
|
| 29 |
+
config['output_dir']+='-smoke'
|
| 30 |
+
config['log_dir']+='-smoke'
|
| 31 |
+
config['tracking']={'enabled':False}
|
| 32 |
+
output=ROOT/config['output_dir']
|
| 33 |
+
logs=ROOT/config['log_dir']
|
| 34 |
+
if args.dry_run:
|
| 35 |
+
from vimeml.training.joint_v45 import build_plan
|
| 36 |
+
plan=build_plan(config,ROOT,verify_files=True)
|
| 37 |
+
print({'stage':plan['stage'],'arm':config['arm'],'parameters':plan['parameters'],
|
| 38 |
+
'max_steps':plan['settings']['max_steps'],
|
| 39 |
+
'updates_per_epoch':plan['settings']['updates_per_epoch'][:3]+['...'],
|
| 40 |
+
'required_files':len(plan['required_files']),'teachers':plan['signatures']['teachers']})
|
| 41 |
+
return
|
| 42 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 43 |
+
parser.error('Fresh V4.5 output/log directories must be empty')
|
| 44 |
+
if args.resume and not (output/'last.pt').exists():
|
| 45 |
+
parser.error('No V4.5 checkpoint to resume')
|
| 46 |
+
from vimeml.training.joint_v45 import run
|
| 47 |
+
tracking=config.get('tracking',{})
|
| 48 |
+
if not tracking.get('enabled'):
|
| 49 |
+
result=run(config,args.resume)
|
| 50 |
+
print(result,flush=True)
|
| 51 |
+
return
|
| 52 |
+
import wandb
|
| 53 |
+
from vimeml.training.data import write_json
|
| 54 |
+
directory=ROOT/'artifacts/tracking'/output.name
|
| 55 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 56 |
+
def start(mode):
|
| 57 |
+
return wandb.init(project=tracking.get('project','vimeml'),entity=os.environ.get('WANDB_ENTITY'),
|
| 58 |
+
group=tracking['group'],name=config['arm']+('-resume' if args.resume else ''),
|
| 59 |
+
job_type='distillation',tags=['v4.5',config['arm'],config['distillation']['pool']],mode=mode,dir=str(directory),
|
| 60 |
+
sync_tensorboard=True,save_code=False,config=config,
|
| 61 |
+
settings=wandb.Settings(disable_git=True,init_timeout=90))
|
| 62 |
+
mode=tracking.get('mode','online') if os.environ.get('WANDB_API_KEY') else 'offline'
|
| 63 |
+
try:
|
| 64 |
+
cloud=start(mode)
|
| 65 |
+
except Exception as error:
|
| 66 |
+
if mode=='offline':
|
| 67 |
+
raise
|
| 68 |
+
print(f'W&B online initialization failed ({type(error).__name__}: {error}); logging offline',flush=True)
|
| 69 |
+
mode='offline'
|
| 70 |
+
cloud=start(mode)
|
| 71 |
+
with cloud:
|
| 72 |
+
write_json(directory/f'live-{cloud.id}.json',{'id':cloud.id,'url':cloud.url if mode!='offline' else None,
|
| 73 |
+
'mode':mode,'resume':args.resume,'directory':str(directory)})
|
| 74 |
+
print(f'W&B run ({mode}): {cloud.url if mode!="offline" else directory}',flush=True)
|
| 75 |
+
result=run(config,args.resume)
|
| 76 |
+
cloud.summary.update({'training_result':result})
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__=='__main__':
|
| 80 |
+
main()
|
source/scripts/training/train_v5.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal V5 LM+chat pretraining entry point; optional W&B tracking."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import tomllib
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[2]
|
| 7 |
+
sys.path.insert(0,str(ROOT/'src'))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 12 |
+
parser.add_argument('--config',type=Path,default=ROOT/'configs/train-v5.toml')
|
| 13 |
+
parser.add_argument('--resume',action='store_true')
|
| 14 |
+
parser.add_argument('--dry-run',action='store_true',
|
| 15 |
+
help='Verify configuration, code and data identities, then exit')
|
| 16 |
+
args=parser.parse_args()
|
| 17 |
+
config=tomllib.loads(args.config.read_text('utf-8'))
|
| 18 |
+
output=ROOT/config['output_dir']
|
| 19 |
+
logs=ROOT/config['log_dir']
|
| 20 |
+
if args.dry_run:
|
| 21 |
+
from vimeml.training.joint_v5 import build_plan
|
| 22 |
+
plan=build_plan(config,ROOT,verify_files=True)
|
| 23 |
+
print({'stage':plan['stage'],'parameters':plan['parameters'],
|
| 24 |
+
'max_steps':plan['settings']['max_steps'],
|
| 25 |
+
'updates_per_epoch':plan['settings']['updates_per_epoch'][:3]+['...'],
|
| 26 |
+
'required_files':len(plan['required_files'])})
|
| 27 |
+
return
|
| 28 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 29 |
+
parser.error('Fresh V5 output/log directories must be empty')
|
| 30 |
+
if args.resume and not (output/'last.pt').exists():
|
| 31 |
+
parser.error('No V5 checkpoint to resume')
|
| 32 |
+
from vimeml.training.joint_v5 import run
|
| 33 |
+
tracking=config.get('tracking',{})
|
| 34 |
+
if not tracking.get('enabled'):
|
| 35 |
+
result=run(config,args.resume)
|
| 36 |
+
print(result,flush=True)
|
| 37 |
+
return
|
| 38 |
+
import wandb
|
| 39 |
+
directory=ROOT/'artifacts/tracking'
|
| 40 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 41 |
+
with wandb.init(project=tracking.get('project','vimeml'),name=output.name,group=output.name,
|
| 42 |
+
mode=tracking.get('mode','online'),dir=str(directory),sync_tensorboard=True,
|
| 43 |
+
save_code=False,force=True,config=config,
|
| 44 |
+
settings=wandb.Settings(disable_git=True,init_timeout=30)) as cloud:
|
| 45 |
+
from vimeml.training.data import write_json
|
| 46 |
+
write_json(directory/f'{output.name}-live.json',{'id':cloud.id,'url':cloud.url,'resume':args.resume})
|
| 47 |
+
print(f'W&B run: {cloud.url}',flush=True)
|
| 48 |
+
result=run(config,args.resume)
|
| 49 |
+
cloud.summary.update({'training_result':result})
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__=='__main__':
|
| 53 |
+
main()
|
source/scripts/training/train_wandb.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""W&B training entry; synchronizes the trainer's TensorBoard events."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import tomllib
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 10 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main(argv=None):
|
| 14 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 15 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/train-smoke.toml")
|
| 16 |
+
parser.add_argument("--project", help="Defaults to tracking.project in the config, or vimeml.")
|
| 17 |
+
parser.add_argument("--entity", help="W&B account/team; defaults to your logged-in account.")
|
| 18 |
+
parser.add_argument("--name", help="Run display name; defaults to the output folder name.")
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"--offline", action="store_true", help="Local W&B logs only; no live remote view."
|
| 21 |
+
)
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--dry-run", action="store_true", help="Print plan; no login, sync or training."
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"--resume", action="store_true", help="Resume model checkpoint in a new grouped W&B run."
|
| 27 |
+
)
|
| 28 |
+
args = parser.parse_args(argv)
|
| 29 |
+
config = tomllib.loads(args.config.read_text(encoding="utf-8"))
|
| 30 |
+
# This entry runs in a fresh process; V4 registration in its caller is lost.
|
| 31 |
+
if config.get("architecture") == "tiny_gpt_v4":
|
| 32 |
+
from vimeml.training.model_factory_v4 import register_v4
|
| 33 |
+
|
| 34 |
+
register_v4()
|
| 35 |
+
output = ROOT / config["output_dir"]
|
| 36 |
+
tracking_config = config.get("tracking", {})
|
| 37 |
+
tracking = {
|
| 38 |
+
"project": args.project or tracking_config.get("project", "vimeml"),
|
| 39 |
+
"entity": args.entity or tracking_config.get("entity"),
|
| 40 |
+
"name": args.name or output.name,
|
| 41 |
+
"group": output.name,
|
| 42 |
+
"mode": "offline" if args.offline else tracking_config.get("mode", "online"),
|
| 43 |
+
}
|
| 44 |
+
if args.dry_run:
|
| 45 |
+
from vimeml.training.train import run
|
| 46 |
+
|
| 47 |
+
run(config, resume=args.resume, dry_run=True)
|
| 48 |
+
print(json.dumps({"wandb": tracking, "sync_tensorboard": True}, indent=2))
|
| 49 |
+
return
|
| 50 |
+
# Catch invalid output choices before creating a remote experiment.
|
| 51 |
+
if args.resume:
|
| 52 |
+
if not (output / "last.pt").exists():
|
| 53 |
+
parser.error("No last.pt checkpoint to resume.")
|
| 54 |
+
elif output.exists() and any(output.iterdir()):
|
| 55 |
+
parser.error("Output is nonempty; use --resume or a new output/configuration.")
|
| 56 |
+
elif (ROOT / config["log_dir"]).exists() and any((ROOT / config["log_dir"]).iterdir()):
|
| 57 |
+
parser.error("TensorBoard directory is nonempty; use a new configuration.")
|
| 58 |
+
try:
|
| 59 |
+
import wandb
|
| 60 |
+
except ImportError:
|
| 61 |
+
parser.error("Install W&B for this environment and authenticate with wandb login.")
|
| 62 |
+
tracking_dir = ROOT / "artifacts" / "tracking"
|
| 63 |
+
tracking_dir.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
# Initialize before importing/creating SummaryWriter, so the SDK patches it.
|
| 65 |
+
# Fresh run per launch avoids mixing rolled-back checkpoint steps into the
|
| 66 |
+
# monotonic history of a previous cloud run. Runs share a comparison group.
|
| 67 |
+
with wandb.init(
|
| 68 |
+
**tracking,
|
| 69 |
+
dir=str(tracking_dir),
|
| 70 |
+
sync_tensorboard=True,
|
| 71 |
+
save_code=False,
|
| 72 |
+
force=tracking["mode"] == "online",
|
| 73 |
+
config={
|
| 74 |
+
"architecture": config.get("architecture", "tiny_gpt_v1"),
|
| 75 |
+
"model": config["model"],
|
| 76 |
+
"training": config["training"],
|
| 77 |
+
"initialization": config.get("initialization"),
|
| 78 |
+
"runtime": config.get("runtime"),
|
| 79 |
+
"data_mixture": config.get("data_mixture"),
|
| 80 |
+
"checkpoint_resume": args.resume,
|
| 81 |
+
},
|
| 82 |
+
settings=wandb.Settings(disable_git=True, init_timeout=30),
|
| 83 |
+
) as cloud:
|
| 84 |
+
print(
|
| 85 |
+
f"W&B run: {cloud.url}" if cloud.url else "W&B offline mode: logs are saved locally.",
|
| 86 |
+
flush=True,
|
| 87 |
+
)
|
| 88 |
+
record = {
|
| 89 |
+
"id": cloud.id,
|
| 90 |
+
"url": cloud.url,
|
| 91 |
+
**tracking,
|
| 92 |
+
"training_config": str(args.config.resolve()),
|
| 93 |
+
"checkpoint_resume": args.resume,
|
| 94 |
+
}
|
| 95 |
+
(tracking_dir / f"{output.name}-live.json").write_text(
|
| 96 |
+
json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
| 97 |
+
)
|
| 98 |
+
from vimeml.training.train import run
|
| 99 |
+
|
| 100 |
+
summary = run(config, resume=args.resume)
|
| 101 |
+
# Scalars flow from TensorBoard; checkpoints/corpus are not uploaded.
|
| 102 |
+
cloud.summary.update({"training_result": summary})
|
| 103 |
+
return summary
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
source/scripts/training/train_zh13.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""vimeml-tiny-zh-v1 arm pretraining entry point; W&B without any machine-wide login.
|
| 2 |
+
|
| 3 |
+
Credentials come only from the environment (WANDB_API_KEY, optional WANDB_ENTITY),
|
| 4 |
+
as cluster_zh13.sh sets them from a private file with isolated W&B directories.
|
| 5 |
+
Without a key, or when online initialization fails, the run logs offline under
|
| 6 |
+
artifacts/tracking/<model>/ for a later `wandb sync`; training never waits on W&B.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import sys
|
| 12 |
+
import tomllib
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 15 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 20 |
+
parser.add_argument("--config", type=Path, required=True)
|
| 21 |
+
parser.add_argument("--resume", action="store_true")
|
| 22 |
+
parser.add_argument("--dry-run", action="store_true", help="Verify configuration, code and data identities, then exit")
|
| 23 |
+
args = parser.parse_args()
|
| 24 |
+
config = tomllib.loads(args.config.read_text("utf-8"))
|
| 25 |
+
output, logs = ROOT / config["output_dir"], ROOT / config["log_dir"]
|
| 26 |
+
if args.dry_run:
|
| 27 |
+
from vimeml.training.joint_zh13 import build_plan
|
| 28 |
+
plan = build_plan(config, ROOT, verify_files=True)
|
| 29 |
+
s = plan["settings"]
|
| 30 |
+
print({"stage": plan["stage"], "arm": plan["arm"], "parameters": plan["parameters"],
|
| 31 |
+
"max_steps": s["max_steps"], "epochs": s["epochs"], "milestone_steps": s["milestone_steps"][:3] + ["..."],
|
| 32 |
+
"budget": plan["budget"], "required_files": len(plan["required_files"])})
|
| 33 |
+
return
|
| 34 |
+
if not args.resume and ((output.exists() and any(output.iterdir())) or (logs.exists() and any(logs.iterdir()))):
|
| 35 |
+
parser.error("Fresh output/log directories must be empty")
|
| 36 |
+
if args.resume and not (output / "last.pt").exists():
|
| 37 |
+
parser.error("No checkpoint to resume")
|
| 38 |
+
from vimeml.training.joint_zh13 import run
|
| 39 |
+
tracking = config.get("tracking", {})
|
| 40 |
+
if not tracking.get("enabled"):
|
| 41 |
+
print(run(config, args.resume), flush=True)
|
| 42 |
+
return
|
| 43 |
+
import wandb
|
| 44 |
+
from vimeml.training.data import write_json
|
| 45 |
+
directory = ROOT / "artifacts/tracking" / output.name
|
| 46 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
|
| 48 |
+
def start(mode):
|
| 49 |
+
return wandb.init(project=tracking.get("project", "vimeml"), entity=os.environ.get("WANDB_ENTITY"),
|
| 50 |
+
group=tracking["group"], name=config["arm"] + ("-resume" if args.resume else ""),
|
| 51 |
+
job_type="pretraining", tags=["zh-v1.3", config["arm"]], mode=mode, dir=str(directory),
|
| 52 |
+
sync_tensorboard=True, save_code=False, config=config,
|
| 53 |
+
settings=wandb.Settings(disable_git=True, init_timeout=90))
|
| 54 |
+
mode = tracking.get("mode", "online") if os.environ.get("WANDB_API_KEY") else "offline"
|
| 55 |
+
try:
|
| 56 |
+
cloud = start(mode)
|
| 57 |
+
except Exception as error:
|
| 58 |
+
if mode == "offline":
|
| 59 |
+
raise
|
| 60 |
+
print(f"W&B online initialization failed ({type(error).__name__}: {error}); logging offline", flush=True)
|
| 61 |
+
mode = "offline"
|
| 62 |
+
cloud = start(mode)
|
| 63 |
+
with cloud:
|
| 64 |
+
write_json(directory / f"live-{cloud.id}.json", {"id": cloud.id, "url": cloud.url if mode != "offline" else None,
|
| 65 |
+
"mode": mode, "resume": args.resume, "directory": str(directory)})
|
| 66 |
+
print(f"W&B run ({mode}): {cloud.url if mode != 'offline' else directory}", flush=True)
|
| 67 |
+
result = run(config, args.resume)
|
| 68 |
+
cloud.summary.update({"training_result": result})
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
source/src/vimeml/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Compact Japanese language models, data pipelines, and IME evaluation tools."""
|
source/src/vimeml/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (277 Bytes). View file
|
|
|
source/src/vimeml/benchmarks/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic IME evaluation data, kept separate from the training corpus."""
|
source/src/vimeml/benchmarks/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (283 Bytes). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/ajimee.cpython-313.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/comparison.cpython-313.pyc
ADDED
|
Binary file (3.67 kB). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/evaluate_ajimee.cpython-313.pyc
ADDED
|
Binary file (22.2 kB). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/expanded_ime.cpython-313.pyc
ADDED
|
Binary file (7.36 kB). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/predict_zh.cpython-313.pyc
ADDED
|
Binary file (23.5 kB). View file
|
|
|
source/src/vimeml/benchmarks/__pycache__/zh13_lm_scores.cpython-313.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
source/src/vimeml/benchmarks/ajimee.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert a local AJIMEE JSON array to anco input without changing its text."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 8 |
+
FORMAT = "ajimee_anco_input_v1"
|
| 9 |
+
DEVELOPMENT_FORMAT = "ime_development_anco_input_v1"
|
| 10 |
+
SOURCE_URL = "https://github.com/azooKey/AJIMEE-Bench/tree/main/JWTD_v2/v1"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def sha(data):
|
| 14 |
+
return hashlib.sha256(data).hexdigest()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def convert_items(rows):
|
| 18 |
+
if not isinstance(rows, list) or not rows:
|
| 19 |
+
raise ValueError("Expected a nonempty AJIMEE JSON array.")
|
| 20 |
+
converted, mapping, seen = [], [], set()
|
| 21 |
+
for position, row in enumerate(rows):
|
| 22 |
+
if not isinstance(row, dict):
|
| 23 |
+
raise ValueError(f"Row {position}: expected an object.")
|
| 24 |
+
index = row.get("index")
|
| 25 |
+
if type(index) not in (str, int) or (isinstance(index, str) and not index.strip()):
|
| 26 |
+
raise ValueError(f"Row {position}: missing/invalid index.")
|
| 27 |
+
case_id = f"ajimee:{index}"
|
| 28 |
+
if case_id in seen:
|
| 29 |
+
raise ValueError(f"Row {position}: duplicate index {index!r}.")
|
| 30 |
+
seen.add(case_id)
|
| 31 |
+
query, context, answers = row.get("input"), row.get("context_text"), row.get("expected_output")
|
| 32 |
+
if not isinstance(query, str) or not query.strip():
|
| 33 |
+
raise ValueError(f"Row {position}: input must be a nonempty string.")
|
| 34 |
+
if not isinstance(context, str):
|
| 35 |
+
raise ValueError(f"Row {position}: context_text must be a string (empty is allowed).")
|
| 36 |
+
if not isinstance(answers, list) or not answers or any(not isinstance(answer, str) or not answer.strip() for answer in answers):
|
| 37 |
+
raise ValueError(f"Row {position}: expected_output must be a nonempty string array.")
|
| 38 |
+
group = "with-context" if context else "without-context"
|
| 39 |
+
# Preserve kana, width, punctuation, whitespace, answer order and the
|
| 40 |
+
# full input exactly. Neither original_text nor split gold is supplied.
|
| 41 |
+
converted.append({"query": query, "answer": list(answers), "tag": [case_id, group],
|
| 42 |
+
"left_context": context, "right_context": None})
|
| 43 |
+
mapping.append({"position": position, "id": case_id, "source_index": index,
|
| 44 |
+
"query": query, "left_context": context, "answers": list(answers), "group": group})
|
| 45 |
+
stats = {"cases": len(rows), "with_context": sum(bool(row["context_text"]) for row in rows),
|
| 46 |
+
"without_context": sum(not row["context_text"] for row in rows),
|
| 47 |
+
"multiple_acceptable_outputs": sum(len(row["expected_output"]) > 1 for row in rows),
|
| 48 |
+
"has_split_inputs": sum(bool(row.get("splitted_input_for_limited_input_length")) for row in rows)}
|
| 49 |
+
return converted, mapping, stats
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def json_bytes(value):
|
| 53 |
+
return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def prepare(input_path, output):
|
| 57 |
+
input_path, output = Path(input_path).resolve(), Path(output).resolve()
|
| 58 |
+
raw = input_path.read_bytes()
|
| 59 |
+
converted, mapping, stats = convert_items(json.loads(raw.decode("utf-8-sig")))
|
| 60 |
+
manifest_path = output / "manifest.json"
|
| 61 |
+
if manifest_path.exists():
|
| 62 |
+
saved = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 63 |
+
if saved.get("format") != FORMAT or saved.get("source_sha256") != sha(raw):
|
| 64 |
+
raise ValueError("Output belongs to different input/version. Choose a new --output directory.")
|
| 65 |
+
for name, digest in saved["files_sha256"].items():
|
| 66 |
+
if sha((output / name).read_bytes()) != digest:
|
| 67 |
+
raise ValueError(f"Prepared file changed: {name}. Choose a new --output directory.")
|
| 68 |
+
return saved["stats"]
|
| 69 |
+
if output.exists() and any(output.iterdir()):
|
| 70 |
+
raise ValueError("Output is not empty. Choose a new --output directory.")
|
| 71 |
+
notice = (
|
| 72 |
+
"# AJIMEE-Bench provenance\n\n"
|
| 73 |
+
f"Source: {SOURCE_URL}\n\n"
|
| 74 |
+
"Dataset: JWTD_v2/v1, based on Japanese Wikipedia Typo Dataset v2.\n"
|
| 75 |
+
"Upstream dataset license: CC-BY-SA 3.0. Preserve attribution and share-alike terms.\n"
|
| 76 |
+
"License: https://creativecommons.org/licenses/by-sa/3.0/\n\n"
|
| 77 |
+
"evaluation_items.json is the supplied local source, preserved byte for byte.\n"
|
| 78 |
+
"Its exact upstream commit has not been verified; source SHA256 is in manifest.json.\n"
|
| 79 |
+
"ajimee-input.json maps input/context_text/expected_output to query/left_context/answer.\n"
|
| 80 |
+
"No text normalization, splitting, filtering or answer injection into context.\n"
|
| 81 |
+
"original_text remains in the source snapshot and is excluded from anco input.\n"
|
| 82 |
+
"For evaluation only; do not add these files to the training corpus.\n"
|
| 83 |
+
).encode("utf-8")
|
| 84 |
+
files = {"evaluation_items.json": raw, "ajimee-input.json": json_bytes(converted),
|
| 85 |
+
"case-map.json": json_bytes(mapping), "NOTICE.md": notice}
|
| 86 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 87 |
+
for name, content in files.items():
|
| 88 |
+
path = output / name
|
| 89 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 90 |
+
temporary.write_bytes(content)
|
| 91 |
+
temporary.replace(path)
|
| 92 |
+
manifest = {"format": FORMAT, "status": "complete", "source_path": str(input_path),
|
| 93 |
+
"source_url": SOURCE_URL, "source_sha256": sha(raw), "upstream_commit_verified": False,
|
| 94 |
+
"license": "CC-BY-SA-3.0", "stats": stats,
|
| 95 |
+
"files_sha256": {name: sha(content) for name, content in files.items()},
|
| 96 |
+
"policy": "Unmodified full queries and all references; supplied left context only; right context null. Mapping positions are zero-based."}
|
| 97 |
+
temporary = manifest_path.with_suffix(".json.tmp")
|
| 98 |
+
temporary.write_bytes(json_bytes(manifest))
|
| 99 |
+
temporary.replace(manifest_path)
|
| 100 |
+
return stats
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def main(argv=None):
|
| 104 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 105 |
+
parser.add_argument("--input", required=True, type=Path, help="Downloaded evaluation_items.json path.")
|
| 106 |
+
parser.add_argument("--output", type=Path, default=ROOT / "artifacts/benchmarks/ajimee-jwtd-v2-v1",
|
| 107 |
+
help="Directory for anco input, source snapshot, case mapping and manifest.")
|
| 108 |
+
args = parser.parse_args(argv)
|
| 109 |
+
try:
|
| 110 |
+
stats = prepare(args.input, args.output)
|
| 111 |
+
except (OSError, ValueError) as error:
|
| 112 |
+
parser.exit(2, f"Error: {error}\n")
|
| 113 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2))
|
| 114 |
+
print(f"Anco input: {args.output.resolve() / 'ajimee-input.json'}")
|
| 115 |
+
print(f"Case map: {args.output.resolve() / 'case-map.json'}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|
source/src/vimeml/benchmarks/comparison.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen-case alignment and exact paired IME statistics."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from vimeml.benchmarks.evaluate_ajimee import metrics
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def rows(path):
|
| 11 |
+
return [
|
| 12 |
+
json.loads(line)
|
| 13 |
+
for line in Path(path).read_text(encoding="utf-8").splitlines()
|
| 14 |
+
if line.strip()
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def paired(before, after):
|
| 19 |
+
left = {r["id"]: r for r in before}
|
| 20 |
+
right = {r["id"]: r for r in after}
|
| 21 |
+
if left.keys() != right.keys() or len(left) != len(before) or len(right) != len(after):
|
| 22 |
+
raise ValueError("Expected identical unique frozen case IDs.")
|
| 23 |
+
wins = losses = both_correct = both_wrong = 0
|
| 24 |
+
changes = []
|
| 25 |
+
for ident, a in left.items():
|
| 26 |
+
b = right[ident]
|
| 27 |
+
for field in ("answers", "left_context", "query"):
|
| 28 |
+
if a[field] != b[field]:
|
| 29 |
+
raise ValueError(f"Frozen case differs: {ident}/{field}")
|
| 30 |
+
if a["orders"]["azookey"] != b["orders"]["azookey"]:
|
| 31 |
+
raise ValueError("Candidate pool/order differs.")
|
| 32 |
+
av = (
|
| 33 |
+
a["orders"]["lm_context_sum"][0] in a["answers"]
|
| 34 |
+
if a["orders"]["lm_context_sum"]
|
| 35 |
+
else False
|
| 36 |
+
)
|
| 37 |
+
bv = (
|
| 38 |
+
b["orders"]["lm_context_sum"][0] in b["answers"]
|
| 39 |
+
if b["orders"]["lm_context_sum"]
|
| 40 |
+
else False
|
| 41 |
+
)
|
| 42 |
+
wins += bv and not av
|
| 43 |
+
losses += av and not bv
|
| 44 |
+
both_correct += av and bv
|
| 45 |
+
both_wrong += not av and not bv
|
| 46 |
+
if av != bv:
|
| 47 |
+
changes.append(
|
| 48 |
+
{
|
| 49 |
+
"id": ident,
|
| 50 |
+
"change": "improved" if bv else "regressed",
|
| 51 |
+
"context": a["left_context"],
|
| 52 |
+
"reading": a["query"],
|
| 53 |
+
"answers": a["answers"],
|
| 54 |
+
"before": a["orders"]["lm_context_sum"][0],
|
| 55 |
+
"after": b["orders"]["lm_context_sum"][0],
|
| 56 |
+
}
|
| 57 |
+
)
|
| 58 |
+
n = wins + losses
|
| 59 |
+
p = min(1, 2 * sum(math.comb(n, k) for k in range(min(wins, losses) + 1)) / 2**n) if n else 1.0
|
| 60 |
+
return {
|
| 61 |
+
"cases": len(left),
|
| 62 |
+
"v1": metrics(before, "lm_context_sum"),
|
| 63 |
+
"v2": metrics(after, "lm_context_sum"),
|
| 64 |
+
"paired": {
|
| 65 |
+
"v1_wrong_v2_correct": wins,
|
| 66 |
+
"v1_correct_v2_wrong": losses,
|
| 67 |
+
"both_correct": both_correct,
|
| 68 |
+
"both_wrong": both_wrong,
|
| 69 |
+
"net_correct": wins - losses,
|
| 70 |
+
"exact_mcnemar_p_two_sided": p,
|
| 71 |
+
"significant_at_0_05": p < 0.05,
|
| 72 |
+
},
|
| 73 |
+
"changed_cases": changes,
|
| 74 |
+
}
|
source/src/vimeml/benchmarks/development.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate an independent kana-conversion development set and verify it blind."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
import unicodedata
|
| 9 |
+
from collections import Counter
|
| 10 |
+
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from vimeml.benchmarks.ajimee import ROOT, convert_items, sha
|
| 14 |
+
from vimeml.benchmarks.generate import Requests, json_content, normalized
|
| 15 |
+
from vimeml.benchmarks.hybrid import overlap_keys
|
| 16 |
+
from vimeml.review.multi_key import AccountPool, output_lock
|
| 17 |
+
from vimeml.review.prepare import write_json
|
| 18 |
+
from vimeml.review.run import ENDPOINT, digest, send_request, token_reservation
|
| 19 |
+
|
| 20 |
+
VERSION = "ime_development_generation_v1"
|
| 21 |
+
CATEGORIES = {
|
| 22 |
+
"daily": "日常の用事・生活・自然な会話",
|
| 23 |
+
"work": "職場・メール・会議・依頼",
|
| 24 |
+
"technology": "アプリ・機器・サービス・技術用語",
|
| 25 |
+
"food_travel": "食事・交通・旅行・買い物",
|
| 26 |
+
"arts_media": "作品・音楽・番組・メディア",
|
| 27 |
+
"clothing": "衣服・身につける動作・日常の物の扱い",
|
| 28 |
+
"dates_numbers": "予定・日付・数量・時間の表現",
|
| 29 |
+
"names": "読みが明確な人名・地名・店名を含む文。外部知識で正解を決めない",
|
| 30 |
+
"inflection": "動詞の活用・助詞・文中の自然な変換区間",
|
| 31 |
+
"homophones": "同音語の選択。文脈や同じ変換区間内の語句で意味を特定する",
|
| 32 |
+
}
|
| 33 |
+
GENERATION_PROMPT = """日本語IMEのかな漢字変換用に、独立した開発データを作成してください。
|
| 34 |
+
応答はJSON配列だけ。各要素のキーはcontext_text, input, expected_output, reason_zhです。
|
| 35 |
+
context_textとexpected_outputは日本語です。中国語への翻訳や中国語の文章を絶対に入れないでください。
|
| 36 |
+
reason_zhだけは簡潔な中国語で、80文字以内の結論を1文。思考過程、独り言、反復は禁止です。
|
| 37 |
+
形式の例(例文を生成データにコピーしないこと):
|
| 38 |
+
[{"context_text":"駅に着いたら、","input":"キップヲカウ","expected_output":["切符を買う","きっぷを買う"],"reason_zh":"在车站买票,读音与语义一致。"}]
|
| 39 |
+
context_textは既に確定した同じ文内の左側、expected_outputは次の変換区間です。
|
| 40 |
+
両者は隣接し、重複せず、連結すると自然な日本語になります。右文は与えません。
|
| 41 |
+
左文は空文字または5〜50文字、非空なら文末の。!?で終えないこと。
|
| 42 |
+
各表記は2〜60文字、inputは2〜150文字の全角カタカナと元の位置の句読点のみ。
|
| 43 |
+
数字・日付・略語もinputでは実際の読みをカタカナで書き、漢字・数字・英字・ひらがなを混ぜないこと。
|
| 44 |
+
inputはIMEに入力するかな表記であり、発音記号ではありません。助詞は/へ/をはハ/ヘ/ヲ。
|
| 45 |
+
長音、促音、拗音、活用を一字ずつ確認し、読みが違う表記を絶対に混ぜないこと。
|
| 46 |
+
expected_outputは同じ意味・同じ読みの表記ゆれだけを1〜8個、重複なしで列挙します。
|
| 47 |
+
例:頑張る/がんばるは表記ゆれ。期間/機関/帰還は意味が違い、等価な正解ではありません。
|
| 48 |
+
同音異義語では左文や変換区間の他の語から意味が特定できる例を作ってください。
|
| 49 |
+
左文が空なら単独の曖昧な同音語を出さず、意味が明確な短い文・語句にします。
|
| 50 |
+
自然に続けられる文中の語句も可能ですが、単語・活用の途中で切らないこと。
|
| 51 |
+
外部の事実や未提示の背景を正解の根拠にせず、読みの不確かな人名や架空の作品名を避けてください。
|
| 52 |
+
日付と時刻と数量を無関係に並べず、日常で実際に書く自然な表現にしてください。
|
| 53 |
+
語彙と文型を変え、負例・候補リスト・AJIMEE/JWTDの模倣・本地モデルの失敗例の改作を生成しないこと。
|
| 54 |
+
キー、URL、Markdown、追加説明、本文の改行を出力しないでください。
|
| 55 |
+
"""
|
| 56 |
+
VERIFICATION_PROMPT = """日本語IMEのかな漢字変換例を独立に検査してください。
|
| 57 |
+
入力にはid, context_text, inputだけがあります。作者の想定解は知らされていません。
|
| 58 |
+
応答はJSON配列だけ。各idは入力と同じ文字列で、必ず1回ずつ返します。
|
| 59 |
+
形式の例(架空の形式例であり、検査対象の正解ではありません):
|
| 60 |
+
[{"id":"0","status":"clear","confidence":"high","expected_output":["荷物を持つ"],"reason_zh":"语义明确,读音一致。"}]
|
| 61 |
+
expected_outputは日本語のみ。中国語に翻訳しないこと。reason_zhだけは中国語で80文字以内の結論1文。
|
| 62 |
+
思考過程、自己問答、反復、長い説明を出力しないこと。不確かならlowで短く報告してください。
|
| 63 |
+
inputの各文字を確認し、左文に自然に続く、完全に同じ読みの日本語表記を再構成してください。
|
| 64 |
+
inputを訂正したり、存在しない右文を補ったり、外部の事実を推測したりしてはいけません。
|
| 65 |
+
IMEのかな表記なので助詞は/へ/をはハ/ヘ/ヲです。発音のワ/エとは区別します。
|
| 66 |
+
長音・促音・拗音・句読点も一致させ、読みの似ている別の単語を正解にしないこと。
|
| 67 |
+
clear: 与えられた情報だけで意味が明確。同じ意味の漢字/かな・数字の表記ゆれは1〜8個、重複なし。
|
| 68 |
+
ambiguous: 意味が異なる複数の解釈が自然。例:左文なしのキカンは期間/機関/帰還が区別できません。
|
| 69 |
+
invalid: 自然な日本語に戻せない、不自然な構文、誤った読み、単語・活用の途中で切れている。
|
| 70 |
+
statusはclear/ambiguous/invalid、confidenceはhigh/medium/lowのみ。
|
| 71 |
+
ambiguous/invalidではexpected_outputを空配列にして構いません。
|
| 72 |
+
意味と全ての読みを確実に検査できた場合だけhighにしてください。
|
| 73 |
+
文中で続けられる語句には句点は不要ですが、最後の語・活用は完結している必要があります。
|
| 74 |
+
"""
|
| 75 |
+
KANA = re.compile(r"[ァ-ヺー。、!?「」『』()()・::,,.!?\s]+")
|
| 76 |
+
JA = re.compile(r"[\u3040-\u30ff\u3400-\u9fff]")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def text(value, minimum, maximum):
|
| 80 |
+
if not isinstance(value, str) or value != value.strip() or not minimum <= len(value) <= maximum:
|
| 81 |
+
raise ValueError("Invalid text type/length/outer whitespace.")
|
| 82 |
+
if any(unicodedata.category(char).startswith("C") for char in value) or "\ufffd" in value or "http" in value.lower():
|
| 83 |
+
raise ValueError("Control character, replacement character or URL in text.")
|
| 84 |
+
if value and not JA.search(value):
|
| 85 |
+
raise ValueError("Expected Japanese text.")
|
| 86 |
+
return value
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def answers(values, allow_empty=False):
|
| 90 |
+
if not isinstance(values, list) or not (0 if allow_empty else 1) <= len(values) <= 8:
|
| 91 |
+
raise ValueError("Expected 1..8 acceptable forms (or an empty invalid assessment).")
|
| 92 |
+
result = [text(value, 2, 60) for value in values]
|
| 93 |
+
if len(set(result)) != len(result):
|
| 94 |
+
raise ValueError("Duplicate acceptable forms.")
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def make_jobs(config):
|
| 99 |
+
strata = [(category, with_context) for category in CATEGORIES for with_context in (True, False)]
|
| 100 |
+
jobs = []
|
| 101 |
+
for position, (category, with_context) in enumerate(strata):
|
| 102 |
+
total = config["count"] // len(strata) + (position < config["count"] % len(strata))
|
| 103 |
+
for start in range(0, total, config["batch_size"]):
|
| 104 |
+
job = {"category": category, "with_context": with_context, "start": start,
|
| 105 |
+
"count": min(config["batch_size"], total - start)}
|
| 106 |
+
jobs.append({**job, "id": digest({"version": VERSION, "seed": config["seed"], "job": job})})
|
| 107 |
+
return jobs
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def generation_instruction(job, legacy=False):
|
| 111 |
+
if legacy:
|
| 112 |
+
mode = "每条必须有5~50字的句内左文" if job["with_context"] else "每条context_text必须为空,待转换区间自身要足够明确"
|
| 113 |
+
return (f"主题:{CATEGORIES[job['category']]}。恰好生成{job['count']}条。{mode}。\n"
|
| 114 |
+
f"独立批次编号:{job['id'][:16]};此编号仅用于请求区分,不要写进语料。")
|
| 115 |
+
mode = "各例に5〜50文字の句内左文が必要" if job["with_context"] else "全例context_textは空文字。変換区間自体で意味が明確な語句を生成"
|
| 116 |
+
return (f"テーマ:{CATEGORIES[job['category']]}。ちょうど{job['count']}例。{mode}。\n"
|
| 117 |
+
f"バッチID:{job['id'][:16]}(データに含めない)。")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def generation_payload(job, config):
|
| 121 |
+
instruction = generation_instruction(job)
|
| 122 |
+
return {"model": config["model"], "temperature": .9, "max_tokens": config["output_tokens"],
|
| 123 |
+
"messages": [{"role": "system", "content": GENERATION_PROMPT}, {"role": "user", "content": instruction}]}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def parse_generated(body, job):
|
| 127 |
+
rows = json_content(body)
|
| 128 |
+
if len(rows) != job["count"]:
|
| 129 |
+
raise ValueError("Response count differs from fixed job count.")
|
| 130 |
+
result, seen = [], set()
|
| 131 |
+
for position, raw in enumerate(rows):
|
| 132 |
+
if not isinstance(raw, dict):
|
| 133 |
+
raise ValueError("Expected generated object.")
|
| 134 |
+
context = text(raw.get("context_text"), 5 if job["with_context"] else 0, 50 if job["with_context"] else 0)
|
| 135 |
+
if context.endswith(tuple("。!?!?")):
|
| 136 |
+
raise ValueError("Context must remain within the current sentence.")
|
| 137 |
+
query = text(raw.get("input"), 2, 150)
|
| 138 |
+
if not KANA.fullmatch(query) or not re.search(r"[ァ-ヺ]", query):
|
| 139 |
+
raise ValueError("Reading must contain katakana and punctuation only.")
|
| 140 |
+
expected = answers(raw.get("expected_output"))
|
| 141 |
+
reason = raw.get("reason_zh")
|
| 142 |
+
if not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 800:
|
| 143 |
+
raise ValueError("Missing generation rationale.")
|
| 144 |
+
key = (normalized(query), normalized(context))
|
| 145 |
+
if key in seen:
|
| 146 |
+
raise ValueError("Duplicate query/context in generation batch.")
|
| 147 |
+
seen.add(key)
|
| 148 |
+
result.append({"index": f"dev-{job['id'][:16]}-{position:02d}", "context_text": context, "input": query,
|
| 149 |
+
"expected_output": expected, "reason_zh": reason.strip(), "category": job["category"],
|
| 150 |
+
"provenance": {"job_id": job["id"], "kind": "llm_synthetic"}})
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def verification_payload(cases, config):
|
| 155 |
+
# No generator answers/rationale/category/local-model scores on the wire.
|
| 156 |
+
evidence = [{"id": str(i), "context_text": case["context_text"], "input": case["input"]} for i, case in enumerate(cases)]
|
| 157 |
+
return {"model": config["judge_model"], "temperature": 0, "max_tokens": config["output_tokens"],
|
| 158 |
+
"messages": [{"role": "system", "content": VERIFICATION_PROMPT},
|
| 159 |
+
{"role": "user", "content": json.dumps(evidence, ensure_ascii=False)}]}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def parse_verified(body, cases):
|
| 163 |
+
rows = json_content(body)
|
| 164 |
+
if len(rows) != len(cases):
|
| 165 |
+
raise ValueError("Verification response count differs.")
|
| 166 |
+
result = {}
|
| 167 |
+
for row in rows:
|
| 168 |
+
if not isinstance(row, dict) or type(row.get("id")) is not str or not row["id"].isdigit():
|
| 169 |
+
raise ValueError("Invalid verification ID.")
|
| 170 |
+
index = int(row["id"])
|
| 171 |
+
if str(index) != row["id"] or not 0 <= index < len(cases) or index in result:
|
| 172 |
+
raise ValueError("Unexpected/duplicate verification ID.")
|
| 173 |
+
status, confidence = row.get("status"), row.get("confidence")
|
| 174 |
+
if status not in {"clear", "ambiguous", "invalid"} or confidence not in {"high", "medium", "low"}:
|
| 175 |
+
raise ValueError("Invalid verification status/confidence.")
|
| 176 |
+
# A bad label belongs in quarantine, not in a retry of nine good rows.
|
| 177 |
+
# Broken JSON/counts/IDs still fail the request because alignment is lost.
|
| 178 |
+
issues, repairs = [], []
|
| 179 |
+
values = row.get("expected_output")
|
| 180 |
+
if isinstance(values, list) and all(isinstance(value, str) for value in values):
|
| 181 |
+
deduped = list(dict.fromkeys(values))
|
| 182 |
+
if deduped != values:
|
| 183 |
+
repairs.append("duplicate_forms_removed")
|
| 184 |
+
values = deduped
|
| 185 |
+
try:
|
| 186 |
+
expected = answers(values, allow_empty=status != "clear")
|
| 187 |
+
except ValueError as error:
|
| 188 |
+
expected = []
|
| 189 |
+
issues.append(f"invalid_acceptable_forms: {error}")
|
| 190 |
+
# Kana-only forms have an exact spelling check; kanji readings still
|
| 191 |
+
# require the blind verifier and the subsequent manual review.
|
| 192 |
+
for form in expected:
|
| 193 |
+
katakana = ''.join(chr(ord(c)+0x60) if 'ぁ' <= c <= 'ゖ' else c for c in form)
|
| 194 |
+
if KANA.fullmatch(katakana) and katakana != cases[index]["input"]:
|
| 195 |
+
issues.append("kana_form_reading_mismatch")
|
| 196 |
+
reason = row.get("reason_zh")
|
| 197 |
+
if not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 1000:
|
| 198 |
+
issues.append("missing_or_excessive_verification_reason")
|
| 199 |
+
reason = reason[:1000] if isinstance(reason, str) else ""
|
| 200 |
+
if issues:
|
| 201 |
+
status, confidence = "invalid", "low"
|
| 202 |
+
decision = {"status": status, "confidence": confidence, "expected_output": expected, "reason_zh": reason.strip()}
|
| 203 |
+
if issues:
|
| 204 |
+
decision["validation_errors"] = issues
|
| 205 |
+
if repairs:
|
| 206 |
+
decision["repairs"] = repairs
|
| 207 |
+
result[index] = decision
|
| 208 |
+
return [result[i] for i in range(len(cases))]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def unique_cases(jobs, generated, excluded):
|
| 212 |
+
_, excluded_rows, _ = convert_items(excluded)
|
| 213 |
+
exclude_queries, exclude_texts = overlap_keys(excluded_rows)
|
| 214 |
+
seen_queries, seen_texts, kept, removed = set(), set(), [], []
|
| 215 |
+
for job in jobs:
|
| 216 |
+
for case in generated.get(job["id"], []):
|
| 217 |
+
query = (normalized(case["input"]), normalized(case["context_text"]))
|
| 218 |
+
forms = {normalized(case["context_text"] + answer) for answer in case["expected_output"]}
|
| 219 |
+
reason = None
|
| 220 |
+
if query in exclude_queries or forms & exclude_texts:
|
| 221 |
+
reason = "overlap_with_ajimee"
|
| 222 |
+
elif query in seen_queries or forms & seen_texts:
|
| 223 |
+
reason = "duplicate_development_example"
|
| 224 |
+
if reason:
|
| 225 |
+
removed.append({**case, "excluded_reason": reason})
|
| 226 |
+
else:
|
| 227 |
+
seen_queries.add(query)
|
| 228 |
+
seen_texts.update(forms)
|
| 229 |
+
kept.append(case)
|
| 230 |
+
return kept, removed
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def finalize(cases, decisions, excluded):
|
| 234 |
+
if len(cases) != len(decisions):
|
| 235 |
+
raise ValueError("Verification decisions missing.")
|
| 236 |
+
_, excluded_rows, _ = convert_items(excluded)
|
| 237 |
+
exclude_queries, exclude_texts = overlap_keys(excluded_rows)
|
| 238 |
+
accepted, quarantine, seen = [], [], set()
|
| 239 |
+
for case, decision in zip(cases, decisions):
|
| 240 |
+
generated = set(case["expected_output"])
|
| 241 |
+
independently_reconstructed = set(decision["expected_output"])
|
| 242 |
+
reason = None
|
| 243 |
+
if decision["status"] != "clear" or decision["confidence"] != "high":
|
| 244 |
+
reason = "ambiguous_invalid_or_low_confidence"
|
| 245 |
+
elif not generated <= independently_reconstructed:
|
| 246 |
+
reason = "independent_reconstruction_disagrees_with_generated_forms"
|
| 247 |
+
# Only verifier-supported generated forms survive; extra blind forms
|
| 248 |
+
# are retained as explicitly verified alternative spellings.
|
| 249 |
+
forms = list(case["expected_output"]) + [s for s in decision["expected_output"] if s not in generated]
|
| 250 |
+
keys = {normalized(case["context_text"] + form) for form in forms}
|
| 251 |
+
if reason is None and (keys & exclude_texts or (normalized(case["input"]), normalized(case["context_text"])) in exclude_queries):
|
| 252 |
+
reason = "verified_form_overlaps_ajimee"
|
| 253 |
+
if reason is None and keys & seen:
|
| 254 |
+
reason = "verified_form_duplicates_development_example"
|
| 255 |
+
if reason:
|
| 256 |
+
quarantine.append({**case, "quality": decision, "quarantine_reason": reason})
|
| 257 |
+
else:
|
| 258 |
+
seen.update(keys)
|
| 259 |
+
accepted.append({**case, "expected_output": forms, "generator_expected_output": case["expected_output"], "quality": decision})
|
| 260 |
+
return accepted, quarantine
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class DevelopmentRequests(Requests):
|
| 264 |
+
def signature(self, payload):
|
| 265 |
+
return digest({"version": VERSION, "endpoint": self.config["endpoint"], "payload": payload})
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def reuse_generation(source, config, jobs, excluded_sha, require_complete=True):
|
| 269 |
+
"""Import complete generation caches, keeping their actual prompt provenance.
|
| 270 |
+
|
| 271 |
+
Never reuse old verification decisions after changing the verifier prompt.
|
| 272 |
+
This reads the source only; in-progress verification cannot alter these caches.
|
| 273 |
+
"""
|
| 274 |
+
manifest = json.loads((source / "manifest.json").read_text(encoding="utf-8"))
|
| 275 |
+
if manifest.get("format") != VERSION or manifest.get("excluded_source_sha256") != excluded_sha:
|
| 276 |
+
raise ValueError("Generation reuse format/exclusion source differs.")
|
| 277 |
+
original = manifest["config"]
|
| 278 |
+
for key in ("count", "batch_size", "seed", "model", "endpoint"):
|
| 279 |
+
if original.get(key) != config.get(key):
|
| 280 |
+
raise ValueError(f"Generation reuse configuration differs: {key}.")
|
| 281 |
+
found, hashes = {}, {}
|
| 282 |
+
by_instruction = {generation_instruction(j, legacy=legacy): j for j in jobs for legacy in (False, True)}
|
| 283 |
+
for path in sorted((source / "cache").glob('*.json')):
|
| 284 |
+
raw = path.read_bytes()
|
| 285 |
+
cached = json.loads(raw.decode("utf-8"))
|
| 286 |
+
payload = cached.get("request", {})
|
| 287 |
+
messages = payload.get("messages", [])
|
| 288 |
+
if payload.get("model") != original["model"] or len(messages) != 2:
|
| 289 |
+
continue
|
| 290 |
+
instruction = messages[1].get("content")
|
| 291 |
+
job = by_instruction.get(instruction)
|
| 292 |
+
if job is None:
|
| 293 |
+
continue # Verification cache, including same-model verification.
|
| 294 |
+
actual_prompt = messages[0].get("content")
|
| 295 |
+
if digest(actual_prompt) != manifest["generation_prompt_sha256"]:
|
| 296 |
+
continue
|
| 297 |
+
signature = digest({"version": VERSION, "endpoint": original["endpoint"], "payload": payload})
|
| 298 |
+
if cached.get("signature") != signature or path.stem != signature:
|
| 299 |
+
raise ValueError("Generation reuse cache signature differs.")
|
| 300 |
+
expected_payload = {"model": original["model"], "temperature": .9, "max_tokens": original["output_tokens"],
|
| 301 |
+
"messages": [{"role": "system", "content": actual_prompt},
|
| 302 |
+
{"role": "user", "content": instruction}]}
|
| 303 |
+
if payload != expected_payload or job["id"] in found:
|
| 304 |
+
raise ValueError("Unexpected or duplicate generation reuse payload.")
|
| 305 |
+
found[job["id"]] = parse_generated(cached["body"], job)
|
| 306 |
+
hashes[path.name] = sha(raw)
|
| 307 |
+
if require_complete and len(found) != len(jobs):
|
| 308 |
+
raise ValueError(f"Generation reuse requires all {len(jobs)} successful batches; found {len(found)}.")
|
| 309 |
+
origin = {"source": str(source.resolve()), "source_identity": manifest["identity"],
|
| 310 |
+
"generation_prompt_sha256": manifest["generation_prompt_sha256"], "cache_sha256": hashes}
|
| 311 |
+
return found, origin
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def export_cached_drafts(source, output, excluded_path):
|
| 315 |
+
"""Export a frozen partial snapshot for review, without credentials/network.
|
| 316 |
+
|
| 317 |
+
Generation caches are drafts, not verification decisions. Incomplete jobs
|
| 318 |
+
remain explicitly missing; failed raw responses are never silently promoted.
|
| 319 |
+
"""
|
| 320 |
+
if source.resolve() == output.resolve():
|
| 321 |
+
raise ValueError("Use a separate snapshot output directory.")
|
| 322 |
+
if output.exists() and any(p.name != '.review.lock' for p in output.iterdir()):
|
| 323 |
+
raise ValueError("Snapshot output is not empty; use a new directory.")
|
| 324 |
+
manifest = json.loads((source / "manifest.json").read_text(encoding="utf-8"))
|
| 325 |
+
excluded_raw = excluded_path.read_bytes()
|
| 326 |
+
excluded = json.loads(excluded_raw.decode("utf-8-sig"))
|
| 327 |
+
config = manifest["config"]
|
| 328 |
+
jobs = make_jobs(config)
|
| 329 |
+
generated, origin = reuse_generation(source, config, jobs, sha(excluded_raw), require_complete=False)
|
| 330 |
+
cases, removed = unique_cases(jobs, generated, excluded)
|
| 331 |
+
if not cases:
|
| 332 |
+
raise ValueError("No successful unique generation drafts to export.")
|
| 333 |
+
missing = [job for job in jobs if job["id"] not in generated]
|
| 334 |
+
stats = {"requested_draft_cases": config["count"], "cached_generation_batches": len(generated),
|
| 335 |
+
"missing_generation_batches": len(missing), "unique_draft_cases": len(cases),
|
| 336 |
+
"excluded_cases": len(removed), "with_context": sum(bool(c["context_text"]) for c in cases),
|
| 337 |
+
"without_context": sum(not c["context_text"] for c in cases),
|
| 338 |
+
"by_category": dict(Counter(c["category"] for c in cases)),
|
| 339 |
+
"automatically_verified_cases": 0, "manual_review_done": False, "network_requests_sent": 0}
|
| 340 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
data = {"draft.json": cases, "excluded.json": removed, "missing-jobs.json": missing, "stats.json": stats,
|
| 342 |
+
"review-pack.json": {"unverified": cases, "manual_review_done": False}}
|
| 343 |
+
for name, value in data.items():
|
| 344 |
+
write_json(output / name, value)
|
| 345 |
+
write_json(output / "manifest.json", {"format": "ime_development_draft_snapshot_v1",
|
| 346 |
+
"status": "drafts_exported", "config": config, "generation_origin": origin,
|
| 347 |
+
"excluded_source_sha256": sha(excluded_raw), "stats": stats,
|
| 348 |
+
"files_sha256": {name: sha((output / name).read_bytes()) for name in data},
|
| 349 |
+
"note": "Offline generation drafts only; neither API verification nor label review is implied."})
|
| 350 |
+
return stats
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def execute_stage(requests, work, workers, stage, total):
|
| 354 |
+
results, failures = {}, []
|
| 355 |
+
cached_count = total - len(work)
|
| 356 |
+
executor = ThreadPoolExecutor(max_workers=workers)
|
| 357 |
+
futures = {executor.submit(requests.call, payload, parser): key for key, payload, parser in work}
|
| 358 |
+
pending = set(futures)
|
| 359 |
+
print(f"[{stage}] requests {cached_count}/{total}; cached {cached_count}; pending {len(pending)}", flush=True)
|
| 360 |
+
try:
|
| 361 |
+
while pending:
|
| 362 |
+
done, pending = wait(pending, timeout=10, return_when=FIRST_COMPLETED)
|
| 363 |
+
for future in done:
|
| 364 |
+
key = futures[future]
|
| 365 |
+
try:
|
| 366 |
+
results[key] = future.result()
|
| 367 |
+
except Exception as error:
|
| 368 |
+
failures.append({"stage": stage, "id": key, "error": str(error)})
|
| 369 |
+
print(f"[{stage}] requests {cached_count + len(results)}/{total}; pending {len(pending)}; failed {len(failures)}; "
|
| 370 |
+
f"network requests this run {requests.started}", flush=True)
|
| 371 |
+
except KeyboardInterrupt:
|
| 372 |
+
requests.stop.set()
|
| 373 |
+
raise
|
| 374 |
+
finally:
|
| 375 |
+
executor.shutdown(wait=True, cancel_futures=True)
|
| 376 |
+
write_json(requests.output / "pending.json", failures)
|
| 377 |
+
if failures:
|
| 378 |
+
raise RuntimeError(f"{len(failures)} {stage} requests pending. Successful caches retained; rerun the same command.")
|
| 379 |
+
return results
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def run(output, config, excluded_path, api_keys=(), workers_per_key=4, rpm=10, tpm=80000,
|
| 383 |
+
timeout=180, retries=2, stage="all", dry_run=False, account_count=1, transport=send_request, window=60.,
|
| 384 |
+
reuse_generation_from=None):
|
| 385 |
+
exclude_raw = excluded_path.read_bytes()
|
| 386 |
+
excluded = json.loads(exclude_raw.decode("utf-8-sig"))
|
| 387 |
+
convert_items(excluded)
|
| 388 |
+
jobs = make_jobs(config)
|
| 389 |
+
imported, origin = {}, None
|
| 390 |
+
if reuse_generation_from is not None:
|
| 391 |
+
if reuse_generation_from.resolve() == output.resolve():
|
| 392 |
+
raise ValueError("Generation reuse needs a separate new --output directory.")
|
| 393 |
+
imported, origin = reuse_generation(reuse_generation_from, config, jobs, sha(exclude_raw))
|
| 394 |
+
identity_data = {"version": VERSION, "config": config, "generation_prompt": GENERATION_PROMPT,
|
| 395 |
+
"verification_prompt": VERIFICATION_PROMPT, "excluded_source_sha256": sha(exclude_raw)}
|
| 396 |
+
if origin:
|
| 397 |
+
identity_data["generation_reuse"] = origin
|
| 398 |
+
identity = digest(identity_data)
|
| 399 |
+
manifest_path = output / "manifest.json"
|
| 400 |
+
old = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else None
|
| 401 |
+
if old and (old.get("format") != VERSION or old.get("identity") != identity):
|
| 402 |
+
raise ValueError("Configuration/prompts/exclusion set changed; use a new --output.")
|
| 403 |
+
if old and old.get("status") == "complete":
|
| 404 |
+
for name, checksum in old["files_sha256"].items():
|
| 405 |
+
if sha((output / name).read_bytes()) != checksum:
|
| 406 |
+
raise ValueError(f"Frozen generated file changed: {name}. Keep reviewed edits as a new version.")
|
| 407 |
+
if not dry_run:
|
| 408 |
+
stats = {**old["stats"], "network_requests_sent_this_run": 0, "accounts_this_run": []}
|
| 409 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2), flush=True)
|
| 410 |
+
print(f"Reused complete generation: {output.resolve() / 'ime-dev-draft.json'}")
|
| 411 |
+
if not stats["automatically_accepted_cases"]:
|
| 412 |
+
raise ValueError("All drafts quarantined; inspect quarantine.json.")
|
| 413 |
+
return stats
|
| 414 |
+
if not old and output.exists() and any(p.name != '.review.lock' for p in output.iterdir()):
|
| 415 |
+
raise ValueError("Output contains unrelated data; use a new --output.")
|
| 416 |
+
generated, missing = dict(imported), []
|
| 417 |
+
probe = DevelopmentRequests(output, config, None, timeout, retries, transport)
|
| 418 |
+
for job in jobs:
|
| 419 |
+
if job["id"] in generated:
|
| 420 |
+
continue
|
| 421 |
+
payload = generation_payload(job, config)
|
| 422 |
+
parsed = probe.cached(payload, lambda body, job=job: parse_generated(body, job))
|
| 423 |
+
if parsed is None:
|
| 424 |
+
missing.append(job)
|
| 425 |
+
else:
|
| 426 |
+
generated[job["id"]] = parsed
|
| 427 |
+
accounts = max(account_count, len(api_keys), 1)
|
| 428 |
+
verification_upper = math.ceil(config["count"] / config["verify_batch_size"])
|
| 429 |
+
preview = {"target_draft_cases": config["count"], "with_context_target": sum(j["count"] for j in jobs if j["with_context"]),
|
| 430 |
+
"without_context_target": sum(j["count"] for j in jobs if not j["with_context"]),
|
| 431 |
+
"generation_requests": len(jobs), "generation_requests_pending": len(missing),
|
| 432 |
+
"reused_generation_cases": sum(len(rows) for rows in imported.values()),
|
| 433 |
+
"verification_requests_upper_bound": verification_upper, "accounts": accounts,
|
| 434 |
+
"generator": config["model"], "blind_verifier": config["judge_model"],
|
| 435 |
+
"request_quota_lower_bound_minutes_full_run": max(0, len(jobs)+verification_upper-1)/(rpm*accounts),
|
| 436 |
+
"request_quota_lower_bound_minutes_remaining_upper_plan": max(0, len(missing)+verification_upper-1)/(rpm*accounts),
|
| 437 |
+
"network_requests_sent": 0, "note": "No count guarantee after dedup/verification; quota estimate excludes latency, token throttling and retries."}
|
| 438 |
+
print(json.dumps(preview, ensure_ascii=False, indent=2), flush=True)
|
| 439 |
+
if dry_run:
|
| 440 |
+
return preview
|
| 441 |
+
if missing and stage == "verify":
|
| 442 |
+
raise ValueError("Generation incomplete; run --stage all or generate first.")
|
| 443 |
+
if missing and not api_keys:
|
| 444 |
+
raise ValueError("Set SJTU_API_KEY in the local terminal before starting (never put the key in source files).")
|
| 445 |
+
pool = AccountPool(api_keys, workers_per_key=workers_per_key, rpm=rpm, tpm=tpm, window=window) if api_keys else None
|
| 446 |
+
requests = DevelopmentRequests(output, config, pool, timeout, retries, transport)
|
| 447 |
+
workers = max(1, len(api_keys))*workers_per_key
|
| 448 |
+
# Fail before dispatch if any request cannot fit even once in the quota.
|
| 449 |
+
if any(token_reservation(generation_payload(job, config)) > tpm for job in jobs):
|
| 450 |
+
raise ValueError("A generation request exceeds per-account TPM; reduce output tokens/batch size in a new output.")
|
| 451 |
+
for folder in ("cache", "responses", "failures"):
|
| 452 |
+
(output / folder).mkdir(parents=True, exist_ok=True)
|
| 453 |
+
manifest = {"format": VERSION, "identity": identity, "config": config, "status": "generating",
|
| 454 |
+
"excluded_source_sha256": sha(exclude_raw), "generation_prompt_sha256": digest(GENERATION_PROMPT),
|
| 455 |
+
"verification_prompt_sha256": digest(VERIFICATION_PROMPT), "manual_review_done": False,
|
| 456 |
+
"generator_equals_verifier": config["model"] == config["judge_model"],
|
| 457 |
+
"note": "Independent synthetic development draft; blind AI reconstruction is provisional; no local LM filtering, candidate generation or training."}
|
| 458 |
+
if origin:
|
| 459 |
+
manifest.update(generation_reuse=origin, configured_generation_prompt_sha256=digest(GENERATION_PROMPT),
|
| 460 |
+
generation_prompt_sha256=origin["generation_prompt_sha256"])
|
| 461 |
+
write_json(manifest_path, manifest)
|
| 462 |
+
work = [(j["id"], generation_payload(j, config), lambda body, job=j: parse_generated(body, job)) for j in missing]
|
| 463 |
+
if stage in {"all", "generate"}:
|
| 464 |
+
generated.update(execute_stage(requests, work, workers, "generate", len(jobs)))
|
| 465 |
+
cases, removed = unique_cases(jobs, generated, excluded)
|
| 466 |
+
write_json(output / "draft.json", cases)
|
| 467 |
+
write_json(output / "excluded.json", removed)
|
| 468 |
+
if stage == "generate":
|
| 469 |
+
write_json(manifest_path, old if old and old.get("status") == "complete" else {**manifest, "status": "awaiting_verification"})
|
| 470 |
+
return {"status": "awaiting_verification", "unique_draft_cases": len(cases)}
|
| 471 |
+
if not cases:
|
| 472 |
+
raise ValueError("No unique development drafts remain; inspect excluded.json.")
|
| 473 |
+
batches = [cases[i:i+config["verify_batch_size"]] for i in range(0,len(cases),config["verify_batch_size"])]
|
| 474 |
+
verified, work = {}, []
|
| 475 |
+
for index, batch in enumerate(batches):
|
| 476 |
+
payload = verification_payload(batch, config)
|
| 477 |
+
if token_reservation(payload) > tpm:
|
| 478 |
+
raise ValueError("A verification batch exceeds per-account TPM; use a new output with smaller --verify-batch-size.")
|
| 479 |
+
parser = lambda body, batch=batch: parse_verified(body,batch)
|
| 480 |
+
cached = requests.cached(payload, parser)
|
| 481 |
+
if cached is None:
|
| 482 |
+
work.append((str(index), payload, parser))
|
| 483 |
+
else:
|
| 484 |
+
verified[str(index)] = cached
|
| 485 |
+
if work and not api_keys:
|
| 486 |
+
raise ValueError("Verification is pending; set SJTU_API_KEY in your local terminal and rerun.")
|
| 487 |
+
write_json(manifest_path, {**manifest, "status": "verifying", "unique_draft_cases": len(cases)})
|
| 488 |
+
verified.update(execute_stage(requests, work, workers, "verify", len(batches)))
|
| 489 |
+
decisions = [decision for i in range(len(batches)) for decision in verified[str(i)]]
|
| 490 |
+
accepted, quarantine = finalize(cases, decisions, excluded)
|
| 491 |
+
write_json(output / "ime-dev-draft.json", accepted)
|
| 492 |
+
write_json(output / "quarantine.json", quarantine)
|
| 493 |
+
write_json(output / "verification.json", [{"index": case["index"], **decision} for case, decision in zip(cases,decisions)])
|
| 494 |
+
write_json(output / "review-pack.json", {"accepted": accepted, "quarantined": quarantine, "manual_review_done": False})
|
| 495 |
+
stats = {"requested_draft_cases": config["count"], "unique_draft_cases": len(cases), "excluded_cases": len(removed),
|
| 496 |
+
"automatically_accepted_cases": len(accepted), "quarantined_cases": len(quarantine),
|
| 497 |
+
"accepted_with_context": sum(bool(c["context_text"]) for c in accepted),
|
| 498 |
+
"accepted_without_context": sum(not c["context_text"] for c in accepted),
|
| 499 |
+
"accepted_by_category": dict(Counter(c["category"] for c in accepted)),
|
| 500 |
+
"network_requests_sent_this_run": requests.started, "accounts_this_run": pool.snapshot() if pool else [],
|
| 501 |
+
"reused_generation_cases": sum(len(rows) for rows in imported.values()),
|
| 502 |
+
"manual_review_done": False}
|
| 503 |
+
write_json(output / "stats.json", stats)
|
| 504 |
+
outputs = ["draft.json", "excluded.json", "ime-dev-draft.json", "quarantine.json", "verification.json", "review-pack.json", "stats.json"]
|
| 505 |
+
write_json(manifest_path, {**manifest, "status": "complete", "stats": stats,
|
| 506 |
+
"files_sha256": {name: sha((output/name).read_bytes()) for name in outputs}})
|
| 507 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2), flush=True)
|
| 508 |
+
print(f"Draft for review: {output.resolve() / 'ime-dev-draft.json'}")
|
| 509 |
+
print(f"Review pack: {output.resolve() / 'review-pack.json'}")
|
| 510 |
+
if not accepted:
|
| 511 |
+
raise ValueError("All drafts quarantined; inspect replies and quarantine.json. Do not calibrate on them.")
|
| 512 |
+
return stats
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def main(argv=None):
|
| 516 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 517 |
+
parser.add_argument("--output", type=Path, default=ROOT / "artifacts/benchmarks/ime-dev-generation-v2")
|
| 518 |
+
parser.add_argument("--reuse-generation-from", type=Path, help="Reuse all successful generation caches from another directory; verify again with the current prompt.")
|
| 519 |
+
parser.add_argument("--exclude", type=Path, default=ROOT / "artifacts/benchmarks/ajimee-jwtd-v2-v1/evaluation_items.json")
|
| 520 |
+
parser.add_argument("--count", type=int, default=200)
|
| 521 |
+
parser.add_argument("--batch-size", type=int, default=10)
|
| 522 |
+
parser.add_argument("--verify-batch-size", type=int, default=10)
|
| 523 |
+
parser.add_argument("--model", default="deepseek-chat")
|
| 524 |
+
parser.add_argument("--judge-model", default="deepseek-chat")
|
| 525 |
+
parser.add_argument("--key-envs", default="SJTU_API_KEY")
|
| 526 |
+
parser.add_argument("--workers-per-key", type=int, default=4)
|
| 527 |
+
parser.add_argument("--rpm", type=int, default=10)
|
| 528 |
+
parser.add_argument("--tpm", type=int, default=80000)
|
| 529 |
+
parser.add_argument("--output-tokens", type=int, default=6144)
|
| 530 |
+
parser.add_argument("--timeout", type=int, default=180)
|
| 531 |
+
parser.add_argument("--retries", type=int, default=2)
|
| 532 |
+
parser.add_argument("--seed", type=int, default=43)
|
| 533 |
+
parser.add_argument("--stage", choices=("all","generate","verify"), default="all")
|
| 534 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 535 |
+
args = parser.parse_args(argv)
|
| 536 |
+
if not 20 <= args.count <= 10000 or not 1 <= args.batch_size <= 20 or not 1 <= args.verify_batch_size <= 20:
|
| 537 |
+
parser.error("count must be 20..10000; batch sizes 1..20.")
|
| 538 |
+
if not 1 <= args.workers_per_key <= 8 or not 1 <= args.rpm <= 10 or not 10000 <= args.tpm <= 100000:
|
| 539 |
+
parser.error("Invalid concurrency/quotas.")
|
| 540 |
+
if not 512 <= args.output_tokens <= 16000 or args.timeout < 1 or not 0 <= args.retries <= 5:
|
| 541 |
+
parser.error("Invalid output token budget, timeout or retries.")
|
| 542 |
+
envs = [name.strip() for name in args.key_envs.split(',')]
|
| 543 |
+
if not 1 <= len(envs) <= 8 or len(set(envs)) != len(envs) or any(not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', name) for name in envs):
|
| 544 |
+
parser.error("--key-envs requires distinct environment variable names, never actual keys.")
|
| 545 |
+
keys = tuple(os.environ.get(name,'').strip() for name in envs) if not args.dry_run else ()
|
| 546 |
+
if keys and all(not key for key in keys):
|
| 547 |
+
keys = () # A fully cached run can resume without credentials.
|
| 548 |
+
if keys and any(not key for key in keys):
|
| 549 |
+
parser.error("Missing environment variable(s): " + ', '.join(name for name,key in zip(envs,keys) if not key))
|
| 550 |
+
if keys and len(set(keys)) != len(keys):
|
| 551 |
+
parser.error("Duplicate keys do not provide independent account quota.")
|
| 552 |
+
config = {"count": args.count, "batch_size": args.batch_size, "verify_batch_size": args.verify_batch_size,
|
| 553 |
+
"model": args.model, "judge_model": args.judge_model, "output_tokens": args.output_tokens,
|
| 554 |
+
"seed": args.seed, "endpoint": ENDPOINT}
|
| 555 |
+
kwargs = dict(api_keys=keys, workers_per_key=args.workers_per_key, rpm=args.rpm, tpm=args.tpm,
|
| 556 |
+
timeout=args.timeout, retries=args.retries, stage=args.stage, account_count=len(envs),
|
| 557 |
+
reuse_generation_from=args.reuse_generation_from)
|
| 558 |
+
try:
|
| 559 |
+
if args.dry_run:
|
| 560 |
+
run(args.output, config, args.exclude, dry_run=True, **kwargs)
|
| 561 |
+
else:
|
| 562 |
+
with output_lock(args.output):
|
| 563 |
+
run(args.output, config, args.exclude, **kwargs)
|
| 564 |
+
except KeyboardInterrupt:
|
| 565 |
+
parser.exit(130, "Interrupted; successful caches retained. Rerun the same command.\n")
|
| 566 |
+
except (OSError, ValueError, RuntimeError, KeyError) as error:
|
| 567 |
+
parser.exit(2, f"Error: {error}\n")
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
if __name__ == '__main__':
|
| 571 |
+
main()
|
source/src/vimeml/benchmarks/evaluate.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tie-aware accuracy of a frozen synthetic set; local LM, no API calls."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import time
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from vimeml.benchmarks.generate import VERSION, jsonl
|
| 12 |
+
from vimeml.data.build import file_sha
|
| 13 |
+
from vimeml.review.prepare import write_json
|
| 14 |
+
from vimeml.training.evaluate_ime import score_candidates
|
| 15 |
+
from vimeml.training.infer import JapaneseLM, ROOT
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_benchmark(directory):
|
| 19 |
+
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
|
| 20 |
+
if manifest.get("format") != VERSION or manifest.get("status") != "complete":
|
| 21 |
+
raise ValueError("Benchmark generation/verification is not complete.")
|
| 22 |
+
path = directory / "benchmark.jsonl"
|
| 23 |
+
if file_sha(path) != manifest["benchmark_sha256"]:
|
| 24 |
+
raise ValueError("Frozen benchmark changed; retain the original and version edits separately.")
|
| 25 |
+
cases = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
| 26 |
+
ids = set()
|
| 27 |
+
for case in cases:
|
| 28 |
+
if case["id"] in ids or case["task"] not in {"homophone", "phrase_contrast"}:
|
| 29 |
+
raise ValueError("Duplicate ID or unknown task.")
|
| 30 |
+
ids.add(case["id"])
|
| 31 |
+
candidates, gold = case["candidates"], case["acceptable"]
|
| 32 |
+
if len(candidates) < 2 or len(set(candidates)) != len(candidates) or len(gold) != 1 or gold[0] not in candidates:
|
| 33 |
+
raise ValueError("Expected distinct candidates and one accepted gold.")
|
| 34 |
+
quality = case["quality"]
|
| 35 |
+
if quality["status"] != "clear" or quality["confidence"] != "high" or quality["acceptable"] != gold:
|
| 36 |
+
raise ValueError("Unverified or ambiguous case in accepted dataset.")
|
| 37 |
+
if not cases or len(cases) != manifest["stats"]["accepted_cases"]:
|
| 38 |
+
raise ValueError("Empty benchmark or count mismatch.")
|
| 39 |
+
return manifest, cases
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def accuracy(rows, field="contextual", score="log_probability_sum", tolerance=1e-6):
|
| 43 |
+
"""Ties receive expected uniform tie-breaking credit, never array-order wins."""
|
| 44 |
+
top1 = top2 = reciprocal = 0.0
|
| 45 |
+
ties = 0
|
| 46 |
+
for row in rows:
|
| 47 |
+
candidates = row[field]["candidates"]
|
| 48 |
+
values = [candidate[score] for candidate in candidates]
|
| 49 |
+
if not all(math.isfinite(value) for value in values):
|
| 50 |
+
raise ValueError("Nonfinite evaluation score.")
|
| 51 |
+
gold = next(candidate[score] for candidate in candidates if candidate["text"] == row["acceptable"][0])
|
| 52 |
+
higher = sum(value > gold + tolerance for value in values)
|
| 53 |
+
equal = sum(abs(value - gold) <= tolerance for value in values)
|
| 54 |
+
top1 += 1 / equal if higher == 0 else 0
|
| 55 |
+
top2 += max(0, min(equal, 2 - higher)) / equal
|
| 56 |
+
reciprocal += sum(1 / (higher + rank) for rank in range(1, equal + 1)) / equal
|
| 57 |
+
ties += sum(abs(value - max(values)) <= tolerance for value in values) > 1
|
| 58 |
+
count = len(rows)
|
| 59 |
+
return {"cases": count, "top1_credit": top1, "top1_accuracy": top1 / count,
|
| 60 |
+
"top2_accuracy": top2 / count, "mrr": reciprocal / count, "top_score_ties": ties}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def summarize(rows):
|
| 64 |
+
if not rows:
|
| 65 |
+
return {"cases": 0}
|
| 66 |
+
result = {"contextual_sum_primary": accuracy(rows),
|
| 67 |
+
"context_free_sum": accuracy(rows, "context_free"),
|
| 68 |
+
"contextual_mean_secondary": accuracy(rows, score="log_probability_mean"),
|
| 69 |
+
"shorter_token_baseline": accuracy(rows, "length_baseline", "negative_tokens"),
|
| 70 |
+
"random_expected_top1": sum(1 / len(row["candidates"]) for row in rows) / len(rows)}
|
| 71 |
+
matched = [row for row in rows if len({candidate["scored_tokens"] for candidate in row["contextual"]["candidates"]}) == 1]
|
| 72 |
+
result["equal_scored_token_length"] = accuracy(matched) if matched else {"cases": 0}
|
| 73 |
+
result["gold_strictly_shortest_scored_tokens_cases"] = sum(next(candidate["scored_tokens"] for candidate in row["contextual"]["candidates"]
|
| 74 |
+
if candidate["text"] == row["acceptable"][0]) < min(candidate["scored_tokens"] for candidate in row["contextual"]["candidates"]
|
| 75 |
+
if candidate["text"] != row["acceptable"][0]) for row in rows)
|
| 76 |
+
result["boundary_retokenized_cases"] = sum(any(candidate["boundary_retokenized"] for candidate in row["contextual"]["candidates"]) for row in rows)
|
| 77 |
+
return result
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def evaluate(lm, cases):
|
| 81 |
+
rows, priors = [], {}
|
| 82 |
+
for index, case in enumerate(cases):
|
| 83 |
+
key = tuple(case["candidates"])
|
| 84 |
+
if key not in priors:
|
| 85 |
+
priors[key] = score_candidates(lm, "", case["candidates"])
|
| 86 |
+
contextual = score_candidates(lm, case["context"], case["candidates"])
|
| 87 |
+
# Candidate-only token lengths: a crude baseline exposing tokenizer
|
| 88 |
+
# length preference, not a Japanese language or AzooKey baseline.
|
| 89 |
+
lengths = [{"text": text, "negative_tokens": -len(lm.processor.encode(text, out_type=int))}
|
| 90 |
+
for text in case["candidates"]]
|
| 91 |
+
rows.append({**case, "contextual": contextual, "context_free": priors[key],
|
| 92 |
+
"length_baseline": {"candidates": lengths}})
|
| 93 |
+
if (index + 1) % 100 == 0 or index == len(cases) - 1:
|
| 94 |
+
print(f"Evaluated {index + 1}/{len(cases)}", flush=True)
|
| 95 |
+
by_task, by_category = defaultdict(list), defaultdict(list)
|
| 96 |
+
for row in rows:
|
| 97 |
+
by_task[row["task"]].append(row)
|
| 98 |
+
by_category[row["task"] + ":" + row["category"]].append(row)
|
| 99 |
+
metrics = {"all": summarize(rows), "by_task": {task: summarize(items) for task, items in by_task.items()},
|
| 100 |
+
"by_category": {category: summarize(items) for category, items in by_category.items()}}
|
| 101 |
+
return rows, metrics
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def write_summary(path, report):
|
| 105 |
+
lines = ["# 合成输入法评测", "",
|
| 106 |
+
"这是AI生成并经另一请求盲核验的合成集准确率。不是实际AzooKey候选排序准确率,也不是开放式短语联想质量/命中率。",
|
| 107 |
+
"生成前不使用本地LM分数选样;训练文本重叠未知。test split未使用;是否已人工抽检见下方。", "",
|
| 108 |
+
f"人工抽检完成标记:{report['benchmark_manifest'].get('manual_review_done', False)}。未抽检时标签质量仍是暂定。", "",
|
| 109 |
+
"| 任务 | 样本数 | 上下文 sum(主指标) | 无上下文 sum | 上下文 mean(次要) | 短token基线 |", "| --- | --- | --- | --- | --- | --- |"]
|
| 110 |
+
for task, metrics in report["metrics"]["by_task"].items():
|
| 111 |
+
primary = metrics["contextual_sum_primary"]
|
| 112 |
+
lines.append(f"| {task} | {primary['cases']} | {primary['top1_accuracy']:.2%} | {metrics['context_free_sum']['top1_accuracy']:.2%} | {metrics['contextual_mean_secondary']['top1_accuracy']:.2%} | {metrics['shorter_token_baseline']['top1_accuracy']:.2%} |")
|
| 113 |
+
lines += ["", "同音词和短语二选一分开解读。并列最高分按均匀随机打破并列计分,不靠候选顺序赢得分数。",
|
| 114 |
+
"主评分、次要评分及长度基线预先定义;不按本轮结果重选最佳评分方案。等token长度子集、分主题结果见metrics.json。",
|
| 115 |
+
"完整原始分数见scores.jsonl,按固定hash选取的人工检查材料见数据目录中的manual-audit.json(同时含通过/隔离样本)。",
|
| 116 |
+
"其他checkpoint使用同一冻结集、单独输出目录;该集一旦用于调整策略就成为开发集,最终评估另留新样本。", ""]
|
| 117 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main(argv=None):
|
| 121 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 122 |
+
parser.add_argument("--benchmark", type=Path, default=ROOT / "artifacts/benchmarks/ime-synthetic-v1")
|
| 123 |
+
parser.add_argument("--checkpoint", type=Path, default=ROOT / "artifacts/models/tiny-ja-v1/best.pt")
|
| 124 |
+
parser.add_argument("--tokenizer", type=Path, default=ROOT / "artifacts/tokenizers/ja-unigram-16k-v1")
|
| 125 |
+
parser.add_argument("--output", type=Path, default=ROOT / "outputs/ime-eval/tiny-ja-v1-synthetic")
|
| 126 |
+
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
|
| 127 |
+
parser.add_argument("--threads", type=int, default=4)
|
| 128 |
+
args = parser.parse_args(argv)
|
| 129 |
+
if args.threads < 1:
|
| 130 |
+
parser.error("threads must be positive.")
|
| 131 |
+
manifest, cases = load_benchmark(args.benchmark)
|
| 132 |
+
torch.set_num_threads(args.threads)
|
| 133 |
+
started = time.perf_counter()
|
| 134 |
+
lm = JapaneseLM(args.checkpoint, args.tokenizer, args.device)
|
| 135 |
+
rows, metrics = evaluate(lm, cases)
|
| 136 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 137 |
+
jsonl(args.output / "scores.jsonl", rows)
|
| 138 |
+
report = {"format": "synthetic_ime_metrics_v1", "model": lm.metadata,
|
| 139 |
+
"benchmark": str(args.benchmark.resolve()), "benchmark_manifest": manifest,
|
| 140 |
+
"policy": "Joint tokenization; common-prefix suffix logP sum, no EOS; mean diagnostic; tie-aware accuracy",
|
| 141 |
+
"test_split_used": False, "metrics": metrics, "elapsed_seconds": time.perf_counter() - started}
|
| 142 |
+
write_json(args.output / "metrics.json", report)
|
| 143 |
+
write_summary(args.output / "results.md", report)
|
| 144 |
+
print(json.dumps(metrics["by_task"], ensure_ascii=False, indent=2))
|
| 145 |
+
print(f"Report: {args.output / 'results.md'}")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
source/src/vimeml/benchmarks/evaluate_ajimee.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate frozen AzooKey candidates, preserving official references and order."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from vimeml.benchmarks.ajimee import DEVELOPMENT_FORMAT, FORMAT, ROOT, convert_items, json_bytes, sha
|
| 9 |
+
from vimeml.benchmarks.expanded_ime import FORMAT as EXPANDED_FORMAT, load_expanded_export
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def read_json(path):
|
| 13 |
+
return json.loads(path.read_text(encoding="utf-8-sig"))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_export(directory):
|
| 17 |
+
manifest = read_json(directory / "manifest.json")
|
| 18 |
+
if manifest.get("format") == "vimeml_standard_ime_candidates_v1":
|
| 19 |
+
raise ValueError("Use scripts/benchmarks/evaluate_standard_ime.py for the versioned label and blind protocol.")
|
| 20 |
+
if manifest.get("format") == EXPANDED_FORMAT:
|
| 21 |
+
return load_expanded_export(directory, manifest)
|
| 22 |
+
if manifest.get("format") not in (FORMAT, DEVELOPMENT_FORMAT) or manifest.get("status") != "complete":
|
| 23 |
+
raise ValueError("Expected a complete prepared AJIMEE manifest.")
|
| 24 |
+
for name, digest in manifest["files_sha256"].items():
|
| 25 |
+
if sha((directory / name).read_bytes()) != digest:
|
| 26 |
+
raise ValueError(f"Prepared file changed: {name}.")
|
| 27 |
+
source = directory / "evaluation_items.json"
|
| 28 |
+
if sha(source.read_bytes()) != manifest["source_sha256"]:
|
| 29 |
+
raise ValueError("Source snapshot hash mismatch.")
|
| 30 |
+
inputs, mapping, stats = convert_items(read_json(source))
|
| 31 |
+
if inputs != read_json(directory / "ajimee-input.json") or mapping != read_json(directory / "case-map.json") or stats != manifest["stats"]:
|
| 32 |
+
raise ValueError("Prepared input/mapping does not match source snapshot.")
|
| 33 |
+
exported = directory / "ajimee-results"
|
| 34 |
+
if inputs != read_json(exported / "ajimee-input.json"):
|
| 35 |
+
raise ValueError("Mac input differs from frozen local input.")
|
| 36 |
+
raw = read_json(exported / "azookey-candidates.json")
|
| 37 |
+
items, n_best = raw.get("items"), raw.get("n_best")
|
| 38 |
+
if type(n_best) is not int or n_best < 1 or not isinstance(items, list) or len(items) != len(inputs):
|
| 39 |
+
raise ValueError("Invalid n_best or exported sample count.")
|
| 40 |
+
rows = []
|
| 41 |
+
for position, (expected, item, case) in enumerate(zip(inputs, items, mapping)):
|
| 42 |
+
if any(item.get(key) != expected[value] for key, value in
|
| 43 |
+
(("query", "query"), ("answers", "answer"), ("left_context", "left_context"))):
|
| 44 |
+
raise ValueError(f"Row {position}: query/context/references misaligned.")
|
| 45 |
+
if item.get("right_context") not in (None, ""):
|
| 46 |
+
raise ValueError(f"Row {position}: unexpected right context.")
|
| 47 |
+
candidates = item.get("outputs")
|
| 48 |
+
if not isinstance(candidates, list) or len(candidates) > n_best:
|
| 49 |
+
raise ValueError(f"Row {position}: invalid candidate count.")
|
| 50 |
+
texts = []
|
| 51 |
+
for candidate in candidates:
|
| 52 |
+
text, score = candidate.get("text"), candidate.get("score")
|
| 53 |
+
if not isinstance(text, str) or not text or type(score) not in (int, float) or not math.isfinite(score):
|
| 54 |
+
raise ValueError(f"Row {position}: invalid candidate text/score.")
|
| 55 |
+
texts.append(text)
|
| 56 |
+
if len(set(texts)) != len(texts):
|
| 57 |
+
raise ValueError(f"Row {position}: duplicate candidate text.")
|
| 58 |
+
rank = next((i for i, text in enumerate(texts) if text in case["answers"]), -1)
|
| 59 |
+
if item.get("max_rank") != rank:
|
| 60 |
+
raise ValueError(f"Row {position}: CLI rank inconsistent with candidates.")
|
| 61 |
+
rows.append({**case, "candidates": candidates, "orders": {"azookey": texts}, "fallbacks": {}})
|
| 62 |
+
# Preserve provenance verbatim; the CLI output does not embed every flag.
|
| 63 |
+
version_files = ["converter-version.txt", "dictionary-versions.txt", "swift-version.txt"]
|
| 64 |
+
provenance = {name: (exported / name).read_text(encoding="utf-8-sig") for name in version_files}
|
| 65 |
+
for line in provenance["dictionary-versions.txt"].splitlines():
|
| 66 |
+
if not line.startswith(" "):
|
| 67 |
+
raise ValueError("Dictionary submodule is uninitialized, conflicted or differs from its pinned commit.")
|
| 68 |
+
provenance["files_sha256"] = {name: sha((exported / name).read_bytes()) for name in
|
| 69 |
+
["ajimee-input.json", "azookey-candidates.json", *version_files]}
|
| 70 |
+
provenance["n_best"] = n_best
|
| 71 |
+
provenance["cli_execution_seconds"] = raw.get("execution_time")
|
| 72 |
+
provenance["flag_provenance"] = "Export requested with typo mode off and no Zenzai; CLI JSON does not embed these flags."
|
| 73 |
+
return manifest, provenance, rows
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def edit_distance(reference, hypothesis):
|
| 77 |
+
previous = list(range(len(hypothesis) + 1))
|
| 78 |
+
for i, left in enumerate(reference, 1):
|
| 79 |
+
current = [i]
|
| 80 |
+
for j, right in enumerate(hypothesis, 1):
|
| 81 |
+
current.append(min(current[-1] + 1, previous[j] + 1, previous[j - 1] + (left != right)))
|
| 82 |
+
previous = current
|
| 83 |
+
return previous[-1]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def min_cer(answers, hypothesis):
|
| 87 |
+
return min(edit_distance(answer, hypothesis) / len(answer) for answer in answers)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def metrics(rows, method):
|
| 91 |
+
count = len(rows)
|
| 92 |
+
if not count:
|
| 93 |
+
return {"cases": 0}
|
| 94 |
+
top1 = top5 = covered = corrected = regressed = 0
|
| 95 |
+
cer = reciprocal = 0.0
|
| 96 |
+
for row in rows:
|
| 97 |
+
order, answers = row["orders"][method], row["answers"]
|
| 98 |
+
ranks = [i + 1 for i, text in enumerate(order) if text in answers]
|
| 99 |
+
hit = bool(ranks) and min(ranks) == 1
|
| 100 |
+
original = bool(row["orders"]["azookey"]) and row["orders"]["azookey"][0] in answers
|
| 101 |
+
top1 += hit
|
| 102 |
+
top5 += bool(ranks) and min(ranks) <= 5
|
| 103 |
+
covered += bool(ranks)
|
| 104 |
+
reciprocal += 1 / min(ranks) if ranks else 0
|
| 105 |
+
cer += min_cer(answers, order[0] if order else "")
|
| 106 |
+
corrected += hit and not original
|
| 107 |
+
regressed += original and not hit
|
| 108 |
+
return {"cases": count, "top1_correct": top1, "top1_accuracy": top1 / count,
|
| 109 |
+
"top5_correct": top5, "top5_accuracy": top5 / count, "candidate_pool_covered": covered,
|
| 110 |
+
"candidate_pool_recall": covered / count, "covered_top1_accuracy": top1 / covered if covered else None,
|
| 111 |
+
"mean_min_cer": cer / count, "mrr": reciprocal / count,
|
| 112 |
+
"corrected_vs_azookey": corrected, "regressed_vs_azookey": regressed,
|
| 113 |
+
"fallback_cases": sum(method in row["fallbacks"] for row in rows)}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def eligibility(lm, context, texts):
|
| 117 |
+
if not texts:
|
| 118 |
+
return "empty_candidates"
|
| 119 |
+
context_ids = lm.processor.encode(context, out_type=int)
|
| 120 |
+
if lm.processor.decode(context_ids) != context:
|
| 121 |
+
return "context_roundtrip_mismatch"
|
| 122 |
+
if len(context_ids) + 1 > lm.model.config.context_length:
|
| 123 |
+
return "context_length"
|
| 124 |
+
for text in texts:
|
| 125 |
+
ids = lm.processor.encode(context + text, out_type=int)
|
| 126 |
+
if lm.processor.decode(ids) != context + text:
|
| 127 |
+
return "candidate_roundtrip_mismatch"
|
| 128 |
+
if not ids or len(ids) > lm.model.config.context_length:
|
| 129 |
+
return "context_length"
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def rerank(lm, rows):
|
| 134 |
+
from vimeml.training.evaluate_ime import score_candidates
|
| 135 |
+
for position, row in enumerate(rows):
|
| 136 |
+
texts = row["orders"]["azookey"]
|
| 137 |
+
row["lm_scores"] = {}
|
| 138 |
+
for field, context, methods in (
|
| 139 |
+
("contextual", row["left_context"], ("lm_context_sum", "lm_context_mean_secondary")),
|
| 140 |
+
("context_free", "", ("lm_no_context_sum",)),
|
| 141 |
+
):
|
| 142 |
+
reason = eligibility(lm, context, texts)
|
| 143 |
+
if reason:
|
| 144 |
+
for method in methods:
|
| 145 |
+
row["orders"][method] = list(texts)
|
| 146 |
+
row["fallbacks"][method] = reason
|
| 147 |
+
continue
|
| 148 |
+
scored = score_candidates(lm, context, texts)
|
| 149 |
+
if any(not math.isfinite(c[key]) for c in scored["candidates"] for key in
|
| 150 |
+
("log_probability_sum", "log_probability_mean")):
|
| 151 |
+
raise ValueError(f"Nonfinite LM score: {row['id']}.")
|
| 152 |
+
row["lm_scores"][field] = scored
|
| 153 |
+
for method in methods:
|
| 154 |
+
key = "log_probability_mean" if method.endswith("secondary") else "log_probability_sum"
|
| 155 |
+
# Stable sort: ties preserve the actual AzooKey candidate order.
|
| 156 |
+
row["orders"][method] = [c["text"] for c in sorted(scored["candidates"], key=lambda c: c[key], reverse=True)]
|
| 157 |
+
if (position + 1) % 25 == 0 or position == len(rows) - 1:
|
| 158 |
+
print(f"Evaluated {position + 1}/{len(rows)}", flush=True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def summarize(rows):
|
| 162 |
+
groups = {"all": rows, "with_context": [r for r in rows if r["left_context"]],
|
| 163 |
+
"without_context": [r for r in rows if not r["left_context"]]}
|
| 164 |
+
if "lm_context_sum" in rows[0]["orders"]:
|
| 165 |
+
groups["contextually_scorable"] = [r for r in rows if "lm_context_sum" not in r["fallbacks"]]
|
| 166 |
+
return {name: {method: metrics(items, method) for method in rows[0]["orders"]} for name, items in groups.items()}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def write_summary(path, report, rows):
|
| 170 |
+
lines = ["# AJIMEE / AzooKey + Tiny LM", "",
|
| 171 |
+
"完整输入、全部可接受答案、真实候选池;不注入答案,不正规化文字,不加EOS。",
|
| 172 |
+
"上下文使用官方给定左文,可能跨句;联合分词的公共前缀后logP是候选评分代理,不是精确字符串条件概率。",
|
| 173 |
+
"主指标为sum,mean仅作预先声明的次要诊断;没有在本评测集调组合系数。并列保持AzooKey原顺序。",
|
| 174 |
+
"任何候选超出128-token评分窗口时,该策略整条回退原排序;空候选计失败,仍保留完整分母。",
|
| 175 |
+
"正确答案未进入候选池的样本也保留;训练语料与公开评测文本重叠未知,分句DataLoader的test split没有用于本轮评测。", ""]
|
| 176 |
+
if report.get('benchmark_manifest', {}).get('format') == EXPANDED_FORMAT:
|
| 177 |
+
split = report['benchmark_manifest']['split']
|
| 178 |
+
lines = [f'# Expanded IME / {split}', '',
|
| 179 |
+
'真实 AzooKey 导出与冻结候选池;当前双词典检查的参考标签仍为草稿,指标是初步诊断,不是正式母语 gold 结���。',
|
| 180 |
+
'主分数:context+candidate 联合分词,公共 token 前缀后的 full-vocabulary logP sum;不加 EOS、不截断、并列保留原顺序。',
|
| 181 |
+
'保留召回失败与回退的完整分母;mean 仅作预先声明的次要诊断。', '']
|
| 182 |
+
lines.extend([
|
| 183 |
+
"| 样本组 | 策略 | 样本数 | Top-1 | Top-5 | 候选池覆盖 | MinCER | 纠正 / 改坏 | 回退 |",
|
| 184 |
+
"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
|
| 185 |
+
])
|
| 186 |
+
for group, methods in report["metrics"].items():
|
| 187 |
+
for method, item in methods.items():
|
| 188 |
+
if not item["cases"]:
|
| 189 |
+
continue
|
| 190 |
+
lines.append(f"| {group} | {method} | {item['cases']} | {item['top1_correct']} ({item['top1_accuracy']:.1%}) | "
|
| 191 |
+
f"{item['top5_correct']} ({item['top5_accuracy']:.1%}) | {item['candidate_pool_covered']} ({item['candidate_pool_recall']:.1%}) | "
|
| 192 |
+
f"{item['mean_min_cer']:.4f} | {item['corrected_vs_azookey']} / {item['regressed_vs_azookey']} | {item['fallback_cases']} |")
|
| 193 |
+
lines += ["", "候选池覆盖是这次冻结候选下精确命中的上限,不等于理论上能达到的实际模型性能。开发机耗时不是iOS延迟。",
|
| 194 |
+
"候选原分数与全部LM token分数见scores.jsonl;changed-cases.json记录纠正/改坏样本;metrics.json记录输入、候选、版本和模型hash。", ""]
|
| 195 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main(argv=None):
|
| 199 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 200 |
+
parser.add_argument("--benchmark", type=Path, default=ROOT / "artifacts/benchmarks/ajimee-jwtd-v2-v1")
|
| 201 |
+
parser.add_argument("--checkpoint", type=Path, default=ROOT / "artifacts/models/tiny-ja-v1/best.pt")
|
| 202 |
+
parser.add_argument("--tokenizer", type=Path, default=ROOT / "artifacts/tokenizers/ja-unigram-16k-v1")
|
| 203 |
+
parser.add_argument("--output", type=Path, default=ROOT / "outputs/ime-eval/tiny-ja-v1-ajimee")
|
| 204 |
+
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
|
| 205 |
+
parser.add_argument("--threads", type=int, default=4)
|
| 206 |
+
parser.add_argument("--baseline-only", action="store_true")
|
| 207 |
+
args = parser.parse_args(argv)
|
| 208 |
+
if args.threads < 1:
|
| 209 |
+
parser.error("threads must be positive.")
|
| 210 |
+
if args.output.exists() and any(args.output.iterdir()):
|
| 211 |
+
parser.error("Output is not empty; choose a new --output directory to preserve previous results.")
|
| 212 |
+
started = time.perf_counter()
|
| 213 |
+
manifest, provenance, rows = load_export(args.benchmark)
|
| 214 |
+
model = None
|
| 215 |
+
if not args.baseline_only:
|
| 216 |
+
import torch
|
| 217 |
+
from vimeml.training.infer import JapaneseLM
|
| 218 |
+
torch.set_num_threads(args.threads)
|
| 219 |
+
lm = JapaneseLM(args.checkpoint, args.tokenizer, args.device)
|
| 220 |
+
model = lm.metadata
|
| 221 |
+
rerank(lm, rows)
|
| 222 |
+
report = {"format": "ajimee_ime_metrics_v1", "status": "complete", "model": model,
|
| 223 |
+
"benchmark_manifest": manifest, "export_provenance": provenance, "metrics": summarize(rows),
|
| 224 |
+
"policy": "Original queries/references/candidates; supplied context; suffix logP sum primary; mean secondary; stable ties; whole-case fallback; no EOS or truncation.",
|
| 225 |
+
"training_overlap": "Unknown; no corpus overlap audit performed.", "test_split_used": False,
|
| 226 |
+
"empty_candidate_cases": sum(not r["candidates"] for r in rows),
|
| 227 |
+
"elapsed_seconds": time.perf_counter() - started}
|
| 228 |
+
if manifest.get('format') == EXPANDED_FORMAT:
|
| 229 |
+
report.update({'labels_formal_gold':False,'result_role':'provisional_expanded_'+manifest['split'],
|
| 230 |
+
'test_split_used':manifest['source_corpus_split']=='test',
|
| 231 |
+
'training_overlap':'Corpus source groups come from held-out validation/test; near-duplicate overlap not fully audited.'})
|
| 232 |
+
changed = []
|
| 233 |
+
for row in rows:
|
| 234 |
+
original = row["orders"]["azookey"]
|
| 235 |
+
before = bool(original) and original[0] in row["answers"]
|
| 236 |
+
for method, order in row["orders"].items():
|
| 237 |
+
after = bool(order) and order[0] in row["answers"]
|
| 238 |
+
if before != after:
|
| 239 |
+
changed.append({"id": row["id"], "method": method, "change": "corrected" if after else "regressed",
|
| 240 |
+
"query": row["query"], "context": row["left_context"], "answers": row["answers"],
|
| 241 |
+
"before": original[0], "after": order[0]})
|
| 242 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 243 |
+
(args.output / "scores.jsonl").write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
|
| 244 |
+
(args.output / "changed-cases.json").write_bytes(json_bytes(changed))
|
| 245 |
+
report["files_sha256"] = {name: sha((args.output / name).read_bytes()) for name in ("scores.jsonl", "changed-cases.json")}
|
| 246 |
+
(args.output / "metrics.json").write_bytes(json_bytes(report))
|
| 247 |
+
write_summary(args.output / "results.md", report, rows)
|
| 248 |
+
print(json.dumps(report["metrics"]["all"], ensure_ascii=False, indent=2))
|
| 249 |
+
print(f"Report: {args.output.resolve() / 'results.md'}")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
main()
|
source/src/vimeml/benchmarks/expanded_ime.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read an imported expanded IME export without changing references or pools."""
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from vimeml.benchmarks.ajimee import convert_items
|
| 9 |
+
|
| 10 |
+
FORMAT = "ime_expanded_azookey_export_v1"
|
| 11 |
+
CONVERTER = "d59a28e4c7ca049aef04f29a91eae9677a7753f2"
|
| 12 |
+
DICTIONARIES = {
|
| 13 |
+
"Sources/KanaKanjiConverterModuleWithDefaultDictionary/azooKey_dictionary_storage": "4d418525b090cf49c219819d05a7e3cc2a4346eb",
|
| 14 |
+
"Sources/KanaKanjiConverterModuleWithDefaultDictionary/azooKey_emoji_dictionary_storage": "67b822603391b01238d7b80b8b61b63f966cf357",
|
| 15 |
+
}
|
| 16 |
+
FLAGS = ["n_best=20", "typo_mode=off", "Zenzai=disabled (no model)", "stable=off"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def read(path):
|
| 20 |
+
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_expanded_export(directory, manifest=None):
|
| 24 |
+
directory = Path(directory)
|
| 25 |
+
manifest = manifest or read(directory / "manifest.json")
|
| 26 |
+
if manifest.get("format") != FORMAT or manifest.get("status") != "complete":
|
| 27 |
+
raise ValueError("Expected a complete imported expanded export.")
|
| 28 |
+
inputs, mapping, stats = convert_items(read(directory / "evaluation_items.json"))
|
| 29 |
+
if (
|
| 30 |
+
inputs != read(directory / "ajimee-input.json")
|
| 31 |
+
or mapping != read(directory / "case-map.json")
|
| 32 |
+
or stats != manifest["stats"]
|
| 33 |
+
):
|
| 34 |
+
raise ValueError("Expanded source/input/mapping mismatch.")
|
| 35 |
+
n_best = manifest.get("n_best", 20)
|
| 36 |
+
exported = directory / "ajimee-results"
|
| 37 |
+
if inputs != read(exported / "ajimee-input.json") or mapping != read(
|
| 38 |
+
exported / "case-map.json"
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Returned Mac input/mapping differs from prepared source.")
|
| 41 |
+
provenance = {
|
| 42 |
+
name: (exported / name).read_text(encoding="utf-8-sig")
|
| 43 |
+
for name in (
|
| 44 |
+
"converter-version.txt",
|
| 45 |
+
"dictionary-versions.txt",
|
| 46 |
+
"swift-version.txt",
|
| 47 |
+
"export-flags.txt",
|
| 48 |
+
"completed.txt",
|
| 49 |
+
)
|
| 50 |
+
}
|
| 51 |
+
if provenance["converter-version.txt"].strip() != CONVERTER:
|
| 52 |
+
raise ValueError("Unexpected converter revision.")
|
| 53 |
+
actual = {}
|
| 54 |
+
for line in provenance["dictionary-versions.txt"].splitlines():
|
| 55 |
+
if not line.startswith(" "):
|
| 56 |
+
raise ValueError("Dictionary differs from pinned revision or is uninitialized.")
|
| 57 |
+
revision, path, *_ = line.split()
|
| 58 |
+
actual[path] = revision
|
| 59 |
+
if (
|
| 60 |
+
actual != DICTIONARIES
|
| 61 |
+
or provenance["export-flags.txt"].splitlines() != [f"n_best={n_best}", *FLAGS[1:]]
|
| 62 |
+
or provenance["completed.txt"].strip() != "cli_exit=0"
|
| 63 |
+
):
|
| 64 |
+
raise ValueError("Dictionary versions, export flags or completion marker mismatch.")
|
| 65 |
+
raw = read(exported / "azookey-candidates.json")
|
| 66 |
+
items = raw.get("items")
|
| 67 |
+
if raw.get("n_best") != n_best or not isinstance(items, list) or len(items) != len(inputs):
|
| 68 |
+
raise ValueError("Candidate n-best/count mismatch.")
|
| 69 |
+
rows = []
|
| 70 |
+
ranks = collections.Counter()
|
| 71 |
+
for position, (expected, item, case) in enumerate(zip(inputs, items, mapping)):
|
| 72 |
+
if any(
|
| 73 |
+
item.get(key) != expected[value]
|
| 74 |
+
for key, value in (
|
| 75 |
+
("query", "query"),
|
| 76 |
+
("answers", "answer"),
|
| 77 |
+
("left_context", "left_context"),
|
| 78 |
+
)
|
| 79 |
+
):
|
| 80 |
+
raise ValueError(f"Row {position}: exported case mismatch.")
|
| 81 |
+
if item.get("right_context") not in ("", None):
|
| 82 |
+
raise ValueError(f"Row {position}: unexpected right context.")
|
| 83 |
+
candidates = item.get("outputs")
|
| 84 |
+
if not isinstance(candidates, list) or len(candidates) > n_best:
|
| 85 |
+
raise ValueError(f"Row {position}: invalid candidate count.")
|
| 86 |
+
texts = []
|
| 87 |
+
for candidate in candidates:
|
| 88 |
+
text, score = candidate.get("text"), candidate.get("score")
|
| 89 |
+
if (
|
| 90 |
+
not isinstance(text, str)
|
| 91 |
+
or not text
|
| 92 |
+
or type(score) not in (int, float)
|
| 93 |
+
or not math.isfinite(score)
|
| 94 |
+
):
|
| 95 |
+
raise ValueError(f"Row {position}: invalid candidate.")
|
| 96 |
+
texts.append(text)
|
| 97 |
+
if len(texts) != len(set(texts)):
|
| 98 |
+
raise ValueError(f"Row {position}: duplicate candidates.")
|
| 99 |
+
rank = next((i for i, text in enumerate(texts) if text in case["answers"]), -1)
|
| 100 |
+
if item.get("max_rank") != rank:
|
| 101 |
+
raise ValueError(f"Row {position}: CLI reference rank mismatch.")
|
| 102 |
+
ranks[str(rank)] += 1
|
| 103 |
+
rows.append(
|
| 104 |
+
{**case, "candidates": candidates, "orders": {"azookey": texts}, "fallbacks": {}}
|
| 105 |
+
)
|
| 106 |
+
if raw.get("stat", {}).get("query_count") != len(rows) or raw.get("stat", {}).get(
|
| 107 |
+
"ranks"
|
| 108 |
+
) != dict(ranks):
|
| 109 |
+
raise ValueError("CLI aggregate statistics differ from actual rows.")
|
| 110 |
+
provenance.update(
|
| 111 |
+
{
|
| 112 |
+
"n_best": n_best,
|
| 113 |
+
"cli_execution_seconds": raw.get("execution_time"),
|
| 114 |
+
"validation": "Exact decoded JSON identity, versions, flags, candidate shape/rank; no repeated SHA256.",
|
| 115 |
+
"flag_provenance": "Recorded exporter arguments; CLI JSON does not independently embed every flag.",
|
| 116 |
+
}
|
| 117 |
+
)
|
| 118 |
+
return manifest, provenance, rows
|
source/src/vimeml/benchmarks/generate.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resumable DeepSeek generation and label-blind verification of IME cases."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import re
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import unicodedata
|
| 11 |
+
from collections import Counter
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from vimeml.data.build import file_sha
|
| 16 |
+
from vimeml.review.prepare import write_json
|
| 17 |
+
from vimeml.review.run import ENDPOINT, MODEL, digest, redact, retry_after, send_request, token_reservation
|
| 18 |
+
from vimeml.review.multi_key import AccountPool, output_lock
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 21 |
+
VERSION = "synthetic_ime_v1"
|
| 22 |
+
CATEGORIES = {
|
| 23 |
+
"日常": "家族や友人との日常会話", "ビジネス": "メール、会議、職場",
|
| 24 |
+
"テクノロジー": "アプリ、デバイス、サービス", "感情": "気持ちの表現",
|
| 25 |
+
"天気": "季節、気温、予定", "食事": "料理、レストラン、食材",
|
| 26 |
+
"旅行": "交通、観光、宿泊", "挨拶": "お礼、お詫び、依頼"}
|
| 27 |
+
JA = re.compile(r"[\u3040-\u30ff\u3400-\u9fff]")
|
| 28 |
+
PROMPT = """你为日语输入法制作小型合成评测数据,只输出JSON数组,不要Markdown。
|
| 29 |
+
每条是当前一句中尚未输入完的前缀 context,加上后续词/短语。上下文必须提供充分信息,
|
| 30 |
+
使正确候选明确自然,其他候选在这个具体上下文中明显不合适。不要依赖外部事实、
|
| 31 |
+
新闻、品牌特性、地理距离、隐含场景或常识问答;不要仅用生僻字/乱码/语法错误充当负例。
|
| 32 |
+
避免只靠情绪词、天气词和常见套话匹配;同时包含搭配、动作对象、时间、因果、肯否定。
|
| 33 |
+
context为5~50个字符的一句内前缀,不含换行,不以句末标点结束;不重复样例。
|
| 34 |
+
不同条目尽量改变句式、主题和词汇。提供中文reason_zh解释为何其他候选不合上下文。
|
| 35 |
+
数据用于评测而非训练。不要输出指令文字,不要把目标答案或其他候选复制到context中。
|
| 36 |
+
"""
|
| 37 |
+
VERIFY_PROMPT = """你独立审核日语输入法评测样本。只输出JSON数组,每个id恰好一次。
|
| 38 |
+
输入只有当前句内context和随机排序的候选。你不知道预设答案,不要假设一定有唯一正确项。
|
| 39 |
+
判断 context+候选 的语法、搭配、语义和时态。只用给定上下文,不要借外部事实裁定。
|
| 40 |
+
候选可以是可继续的短词/短语;未加句号不等于错误。若多个候选合理,请全部列出。
|
| 41 |
+
phrase_contrast任务的两个候选单独看都须语法通顺、表达自然;若某项仅因语法错误、
|
| 42 |
+
乱码或完全不自然的表达而失败,则status=invalid,不作为有挑战的语义负例。
|
| 43 |
+
若上下文不足以区分、存在合理的其他解释,status=ambiguous;没有自然候选或样本本身
|
| 44 |
+
损坏则status=invalid;只有唯一明确自然的候选且其余明显不合适才status=clear。
|
| 45 |
+
homophone任务额外检查所有候选在此处能否读成给定reading。不一致时status=invalid。
|
| 46 |
+
每条返回 {"id":"原ID","status":"clear|ambiguous|invalid",
|
| 47 |
+
"acceptable_ids":["A"],"confidence":"high|medium|low","reason_zh":"简短中文理由"}。
|
| 48 |
+
即使是clear也要如实评估confidence。不要改写输入,不要参考任何所谓预设答案。
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def json_content(body):
|
| 53 |
+
choice = body["choices"][0]
|
| 54 |
+
if choice.get("finish_reason") == "length":
|
| 55 |
+
raise ValueError("Truncated model response; lower batch size in a new run configuration.")
|
| 56 |
+
text = choice["message"]["content"]
|
| 57 |
+
if not isinstance(text, str):
|
| 58 |
+
raise ValueError("Expected text response.")
|
| 59 |
+
text = text.strip()
|
| 60 |
+
if text.startswith("```") and text.endswith("```"):
|
| 61 |
+
text = "\n".join(text.splitlines()[1:-1])
|
| 62 |
+
rows = json.loads(text)
|
| 63 |
+
if isinstance(rows, dict):
|
| 64 |
+
rows = rows.get("items", rows.get("results"))
|
| 65 |
+
if not isinstance(rows, list):
|
| 66 |
+
raise ValueError("Expected JSON array.")
|
| 67 |
+
return rows
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def clean_text(value, minimum, maximum):
|
| 71 |
+
if not isinstance(value, str) or value != value.strip() or not minimum <= len(value) <= maximum:
|
| 72 |
+
raise ValueError("Invalid text type, whitespace or length.")
|
| 73 |
+
if not JA.search(value) or any(unicodedata.category(char).startswith("C") for char in value):
|
| 74 |
+
raise ValueError("Non-Japanese or control characters in text.")
|
| 75 |
+
if "\ufffd" in value or "http" in value.lower():
|
| 76 |
+
raise ValueError("Replacement character or URL in text.")
|
| 77 |
+
return value
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def make_jobs(config, pools):
|
| 81 |
+
jobs = []
|
| 82 |
+
for category, description in CATEGORIES.items():
|
| 83 |
+
for start in range(0, config["per_category"], config["batch_size"]):
|
| 84 |
+
jobs.append({"task": "phrase_contrast", "category": category, "description": description,
|
| 85 |
+
"count": min(config["batch_size"], config["per_category"] - start), "start": start})
|
| 86 |
+
for group in pools["groups"]:
|
| 87 |
+
for target in group["candidates"]:
|
| 88 |
+
for start in range(0, config["contexts_per_target"], config["batch_size"]):
|
| 89 |
+
jobs.append({"task": "homophone", "group": group["id"], "category": "同音語",
|
| 90 |
+
"reading": group["reading"], "candidates": group["candidates"], "target": target,
|
| 91 |
+
"count": min(config["batch_size"], config["contexts_per_target"] - start), "start": start})
|
| 92 |
+
return [{**job, "id": digest({"version": VERSION, "seed": config["seed"], "job": job})} for job in jobs]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def generation_payload(job, config):
|
| 96 |
+
if job["task"] == "phrase_contrast":
|
| 97 |
+
instruction = (f"类别:{job['category']}({job['description']}),生成恰好{job['count']}条。\n"
|
| 98 |
+
'每条返回 {"context":"...","positive":"...","negative":"...","reason_zh":"..."}。\n'
|
| 99 |
+
"positive/negative均为2~30字符,相差不超过3字符且长度比在0.8~1.25;"
|
| 100 |
+
"两者单独看都语法通顺、表达自然、句式类似,只有positive符合显式上下文。"
|
| 101 |
+
"negative在另一个合理上下文应可成立,是有挑战的近似负例。")
|
| 102 |
+
else:
|
| 103 |
+
instruction = (f"读音:{job['reading']};候选:{json.dumps(job['candidates'], ensure_ascii=False)};"
|
| 104 |
+
f"目标词:{job['target']}。生成恰好{job['count']}个不同context,使目标词唯一合适。\n"
|
| 105 |
+
'每条仅返回 {"context":"...","reason_zh":"..."}。目标词由本地程序加入,'
|
| 106 |
+
"不要改写候选。context中不得出现任何候选原文,其他候选在此上下文必须不合适。")
|
| 107 |
+
return {"model": config["model"], "temperature": .9, "max_tokens": config["output_tokens"],
|
| 108 |
+
"messages": [{"role": "system", "content": PROMPT},
|
| 109 |
+
{"role": "user", "content": instruction + f"\n本批独立编号:{job['id'][:16]},避免沿用之前的套话。"}]}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def parse_generated(body, job):
|
| 113 |
+
rows = json_content(body)
|
| 114 |
+
if len(rows) != job["count"]:
|
| 115 |
+
raise ValueError("Response count differs from fixed job count; retry this slot.")
|
| 116 |
+
items, seen = [], set()
|
| 117 |
+
for raw in rows:
|
| 118 |
+
if not isinstance(raw, dict):
|
| 119 |
+
raise ValueError("Generated item must be an object.")
|
| 120 |
+
context = clean_text(raw.get("context"), 5, 50)
|
| 121 |
+
if context.endswith(tuple("。!?!?")) or normalized(context) in seen:
|
| 122 |
+
raise ValueError("Completed or duplicate context within batch.")
|
| 123 |
+
reason = raw.get("reason_zh")
|
| 124 |
+
if not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 500:
|
| 125 |
+
raise ValueError("Missing generation rationale.")
|
| 126 |
+
seen.add(normalized(context))
|
| 127 |
+
if job["task"] == "phrase_contrast":
|
| 128 |
+
positive = clean_text(raw.get("positive"), 2, 30)
|
| 129 |
+
negative = clean_text(raw.get("negative"), 2, 30)
|
| 130 |
+
if normalized(positive) == normalized(negative):
|
| 131 |
+
raise ValueError("Equal positive and negative.")
|
| 132 |
+
if abs(len(positive) - len(negative)) > 3 or not .8 <= len(negative) / len(positive) <= 1.25:
|
| 133 |
+
raise ValueError("Continuation lengths do not match closely enough.")
|
| 134 |
+
candidates, gold = [positive, negative], positive
|
| 135 |
+
else:
|
| 136 |
+
candidates, gold = job["candidates"], job["target"]
|
| 137 |
+
if any(candidate in context for candidate in candidates):
|
| 138 |
+
raise ValueError("Candidate text leaked into context.")
|
| 139 |
+
items.append({"context": context, "candidates": candidates, "acceptable": [gold],
|
| 140 |
+
"reason_zh": reason.strip()})
|
| 141 |
+
return items
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def normalized(text):
|
| 145 |
+
return "".join(unicodedata.normalize("NFKC", text).split())
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def canonical_cases(jobs, generated, config):
|
| 149 |
+
result, duplicate = [], []
|
| 150 |
+
seen = set()
|
| 151 |
+
for job in jobs:
|
| 152 |
+
for index, item in enumerate(generated.get(job["id"], [])):
|
| 153 |
+
case_id = digest({"job": job["id"], "index": index, "item": item})
|
| 154 |
+
# Catch duplicate prefixes even when labels/candidates were changed.
|
| 155 |
+
key = normalized(item["context"])
|
| 156 |
+
if key in seen:
|
| 157 |
+
duplicate.append({"id": case_id, "context": item["context"], "reason": "duplicate_context_nfkc"})
|
| 158 |
+
continue
|
| 159 |
+
seen.add(key)
|
| 160 |
+
candidates = list(item["candidates"])
|
| 161 |
+
group = job.get("group", case_id)
|
| 162 |
+
# Shared order within a homophone contrast group; independent of
|
| 163 |
+
# correct target. Pair positions are likewise independent of gold.
|
| 164 |
+
random.Random(digest({"seed": config["seed"], "group": group})).shuffle(candidates)
|
| 165 |
+
result.append({"id": case_id, "task": job["task"], "category": job["category"],
|
| 166 |
+
"context": item["context"], "candidates": candidates, "acceptable": item["acceptable"],
|
| 167 |
+
"group": group, "reading": job.get("reading", ""), "generation_reason_zh": item["reason_zh"],
|
| 168 |
+
"provenance": {"kind": "llm_synthetic", "job_id": job["id"], "generator": config["model"]}})
|
| 169 |
+
return result, duplicate
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def verification_payload(cases, config):
|
| 173 |
+
evidence = []
|
| 174 |
+
for index, case in enumerate(cases):
|
| 175 |
+
# No acceptable/gold/positive/negative or generation rationale on wire.
|
| 176 |
+
evidence.append({"id": str(index), "task": case["task"], "context": case["context"],
|
| 177 |
+
"reading": case["reading"], "candidates": [{"id": chr(65 + i), "text": text}
|
| 178 |
+
for i, text in enumerate(case["candidates"])]})
|
| 179 |
+
return {"model": config["judge_model"], "temperature": 0, "max_tokens": config["output_tokens"],
|
| 180 |
+
"messages": [{"role": "system", "content": VERIFY_PROMPT},
|
| 181 |
+
{"role": "user", "content": json.dumps(evidence, ensure_ascii=False)}]}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def parse_verified(body, cases):
|
| 185 |
+
rows = json_content(body)
|
| 186 |
+
if len(rows) != len(cases):
|
| 187 |
+
raise ValueError("Missing verification IDs.")
|
| 188 |
+
result = {}
|
| 189 |
+
for row in rows:
|
| 190 |
+
if not isinstance(row, dict) or type(row.get("id")) is not str or not row["id"].isdigit():
|
| 191 |
+
raise ValueError("Invalid verification ID.")
|
| 192 |
+
index = int(row["id"])
|
| 193 |
+
if str(index) != row["id"] or not 0 <= index < len(cases) or index in result:
|
| 194 |
+
raise ValueError("Unexpected or duplicated verification ID.")
|
| 195 |
+
status, confidence, accepted = row.get("status"), row.get("confidence"), row.get("acceptable_ids")
|
| 196 |
+
if status not in {"clear", "ambiguous", "invalid"} or confidence not in {"high", "medium", "low"}:
|
| 197 |
+
raise ValueError("Invalid verification assessment.")
|
| 198 |
+
allowed = {chr(65 + i): candidate for i, candidate in enumerate(cases[index]["candidates"])}
|
| 199 |
+
if not isinstance(accepted, list) or any(not isinstance(v, str) or v not in allowed for v in accepted) or len(set(accepted)) != len(accepted):
|
| 200 |
+
raise ValueError("Invalid verified candidate IDs.")
|
| 201 |
+
if status == "clear" and len(accepted) != 1:
|
| 202 |
+
raise ValueError("Clear assessment requires exactly one accepted candidate.")
|
| 203 |
+
reason = row.get("reason_zh")
|
| 204 |
+
if not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 1000:
|
| 205 |
+
raise ValueError("Missing verification reason.")
|
| 206 |
+
result[index] = {"status": status, "confidence": confidence,
|
| 207 |
+
"acceptable": [allowed[value] for value in accepted], "reason_zh": reason.strip()}
|
| 208 |
+
return [result[index] for index in range(len(cases))]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class Requests:
|
| 212 |
+
"""One quota pool for generation, verification and retries; cache by request."""
|
| 213 |
+
def __init__(self, output, config, pool, timeout, retries, transport=send_request):
|
| 214 |
+
self.output, self.config, self.pool = output, config, pool
|
| 215 |
+
self.timeout, self.retries, self.transport = timeout, retries, transport
|
| 216 |
+
self.stop = threading.Event()
|
| 217 |
+
self.started = 0
|
| 218 |
+
self.lock = threading.Lock()
|
| 219 |
+
|
| 220 |
+
def signature(self, payload):
|
| 221 |
+
return digest({"version": VERSION, "endpoint": self.config["endpoint"], "payload": payload})
|
| 222 |
+
|
| 223 |
+
def cached(self, payload, parser):
|
| 224 |
+
path = self.output / "cache" / f"{self.signature(payload)}.json"
|
| 225 |
+
if not path.exists():
|
| 226 |
+
return None
|
| 227 |
+
saved = json.loads(path.read_text(encoding="utf-8"))
|
| 228 |
+
if saved.get("signature") != self.signature(payload) or saved.get("request") != payload:
|
| 229 |
+
raise ValueError("Cache signature or payload mismatch.")
|
| 230 |
+
return parser(saved["body"])
|
| 231 |
+
|
| 232 |
+
def call(self, payload, parser):
|
| 233 |
+
cached = self.cached(payload, parser)
|
| 234 |
+
if cached is not None:
|
| 235 |
+
return cached
|
| 236 |
+
if self.pool is None:
|
| 237 |
+
raise ValueError("Set SJTU_API_KEY in your local shell; do not paste the key into chat or files.")
|
| 238 |
+
signature = self.signature(payload)
|
| 239 |
+
last = None
|
| 240 |
+
for attempt in range(self.retries + 1):
|
| 241 |
+
ticket = self.pool.acquire(token_reservation(payload), self.stop)
|
| 242 |
+
if ticket is None:
|
| 243 |
+
raise RuntimeError("Requests stopped or all accounts disabled.")
|
| 244 |
+
status = None
|
| 245 |
+
raw = ""
|
| 246 |
+
try:
|
| 247 |
+
with self.lock:
|
| 248 |
+
self.started += 1
|
| 249 |
+
status, headers, raw = self.transport(self.config["endpoint"], payload, self.pool.key(ticket), self.timeout)
|
| 250 |
+
# Every reply, including malformed JSON/429, is retained. No
|
| 251 |
+
# authorization headers; redact all configured keys everywhere.
|
| 252 |
+
write_json(self.output / "responses" / f"{signature}-{time.time_ns()}.json", redact({
|
| 253 |
+
"signature": signature, "attempt": attempt + 1, "request": payload,
|
| 254 |
+
"status": status, "raw_response": raw, "account": self.pool.label(ticket)}, self.pool.secrets))
|
| 255 |
+
if status == 429:
|
| 256 |
+
self.pool.pause(ticket, retry_after(headers, min(60 * (attempt + 1), 180)))
|
| 257 |
+
if status in {401, 403}:
|
| 258 |
+
self.pool.disable(ticket, status)
|
| 259 |
+
if not 200 <= status < 300:
|
| 260 |
+
raise ValueError(f"HTTP {status}")
|
| 261 |
+
body = json.loads(raw)
|
| 262 |
+
self.pool.finish(ticket, body.get("usage"))
|
| 263 |
+
# Live derived records must use the same redacted content as
|
| 264 |
+
# cache replay, including an accidentally echoed secret.
|
| 265 |
+
body = redact(body, self.pool.secrets)
|
| 266 |
+
parsed = parser(body)
|
| 267 |
+
write_json(self.output / "cache" / f"{signature}.json", redact({
|
| 268 |
+
"signature": signature, "request": payload, "body": body}, self.pool.secrets))
|
| 269 |
+
self.pool.success(ticket)
|
| 270 |
+
return parsed
|
| 271 |
+
except Exception as error:
|
| 272 |
+
last = redact(f"{type(error).__name__}: {error}", self.pool.secrets)
|
| 273 |
+
write_json(self.output / "failures" / f"{signature}-{time.time_ns()}.json", {
|
| 274 |
+
"signature": signature, "attempt": attempt + 1, "error": last})
|
| 275 |
+
if status is not None and 400 <= status < 500 and status not in {401, 403, 408, 429}:
|
| 276 |
+
break
|
| 277 |
+
finally:
|
| 278 |
+
self.pool.release(ticket)
|
| 279 |
+
if attempt < self.retries:
|
| 280 |
+
self.stop.wait(min(2 ** (attempt + 1), 15))
|
| 281 |
+
raise RuntimeError(last or "Request failed.")
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def execute(requests, work, workers):
|
| 285 |
+
results, failures = {}, []
|
| 286 |
+
executor = ThreadPoolExecutor(max_workers=workers)
|
| 287 |
+
try:
|
| 288 |
+
futures = {executor.submit(requests.call, payload, parser): key for key, payload, parser in work}
|
| 289 |
+
done = 0
|
| 290 |
+
for future in as_completed(futures):
|
| 291 |
+
key = futures[future]
|
| 292 |
+
try:
|
| 293 |
+
results[key] = future.result()
|
| 294 |
+
except Exception as error:
|
| 295 |
+
failures.append({"id": key, "error": str(error)})
|
| 296 |
+
done += 1
|
| 297 |
+
print(f"Requests completed {done}/{len(work)}; failed {len(failures)}", flush=True)
|
| 298 |
+
except KeyboardInterrupt:
|
| 299 |
+
requests.stop.set()
|
| 300 |
+
raise
|
| 301 |
+
finally:
|
| 302 |
+
executor.shutdown(wait=True, cancel_futures=True)
|
| 303 |
+
if failures:
|
| 304 |
+
write_json(requests.output / "pending.json", failures)
|
| 305 |
+
raise RuntimeError(f"{len(failures)} requests pending; successful caches retained. Rerun the same command.")
|
| 306 |
+
write_json(requests.output / "pending.json", [])
|
| 307 |
+
return results
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def jsonl(path, rows):
|
| 311 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 312 |
+
with temporary.open("w", encoding="utf-8", newline="\n") as handle:
|
| 313 |
+
for row in rows:
|
| 314 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 315 |
+
temporary.replace(path)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def finalize(cases, decisions):
|
| 319 |
+
if len(cases) != len(decisions):
|
| 320 |
+
raise ValueError("Verification count differs from draft count.")
|
| 321 |
+
accepted, rejected = [], []
|
| 322 |
+
for case, decision in zip(cases, decisions):
|
| 323 |
+
if decision["status"] == "clear" and decision["confidence"] == "high" and set(decision["acceptable"]) == set(case["acceptable"]):
|
| 324 |
+
accepted.append({**case, "quality": decision})
|
| 325 |
+
else:
|
| 326 |
+
rejected.append({**case, "quality": decision, "quarantine_reason": "ambiguous_invalid_low_confidence_or_label_disagreement"})
|
| 327 |
+
return accepted, rejected
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def audit_sample(accepted, rejected):
|
| 331 |
+
strata = {}
|
| 332 |
+
for case in accepted:
|
| 333 |
+
key = case["task"] + ":" + (case["group"] if case["task"] == "homophone" else case["category"])
|
| 334 |
+
strata.setdefault(key, []).append(case)
|
| 335 |
+
chosen = []
|
| 336 |
+
for key, cases in sorted(strata.items()):
|
| 337 |
+
count = 2 if key.startswith("homophone:") else 5
|
| 338 |
+
chosen.extend(sorted(cases, key=lambda case: digest({"audit": case["id"]}))[:count])
|
| 339 |
+
return {"selection": "Fixed hash per task/category or homophone group, independent of local LM scores",
|
| 340 |
+
"accepted": chosen, "quarantined": sorted(rejected, key=lambda case: digest({"audit": case["id"]}))[:20]}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def run(output, config, pools, stage="all", api_keys=(), workers_per_key=3, rpm=8, tpm=80000,
|
| 344 |
+
timeout=180, retries=2, dry_run=False, transport=send_request, window=60, account_count=None):
|
| 345 |
+
output = Path(output).resolve()
|
| 346 |
+
jobs = make_jobs(config, pools)
|
| 347 |
+
identity = digest({"version": VERSION, "config": config, "generation_prompt": PROMPT, "verification_prompt": VERIFY_PROMPT})
|
| 348 |
+
manifest_path = output / "manifest.json"
|
| 349 |
+
old = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else None
|
| 350 |
+
if old and old["identity"] != identity:
|
| 351 |
+
raise ValueError("Benchmark configuration/prompts changed. Use a new output directory.")
|
| 352 |
+
probe = Requests(output, config, None, timeout, retries, transport)
|
| 353 |
+
generated, missing = {}, []
|
| 354 |
+
for job in jobs:
|
| 355 |
+
payload = generation_payload(job, config)
|
| 356 |
+
cached = probe.cached(payload, lambda body, job=job: parse_generated(body, job))
|
| 357 |
+
if cached is None:
|
| 358 |
+
missing.append(job)
|
| 359 |
+
else:
|
| 360 |
+
generated[job["id"]] = cached
|
| 361 |
+
target = sum(job["count"] for job in jobs)
|
| 362 |
+
verification_upper = math.ceil(target / config["verify_batch_size"])
|
| 363 |
+
# Dry-run does not touch filesystem or need credentials.
|
| 364 |
+
accounts = account_count or max(1, len(api_keys))
|
| 365 |
+
preview = {"target_generated_cases": target, "phrase_pairs": config["per_category"] * len(CATEGORIES),
|
| 366 |
+
"homophone_cases": target - config["per_category"] * len(CATEGORIES), "generation_requests_total": len(jobs),
|
| 367 |
+
"generation_requests_pending": len(missing), "verification_requests_upper_bound": verification_upper,
|
| 368 |
+
"generator": config["model"], "verifier": config["judge_model"], "accounts": accounts,
|
| 369 |
+
"rpm_per_account": rpm, "network_requests_sent": 0,
|
| 370 |
+
"request_quota_estimate_minutes_full_run": max(0, len(jobs) + verification_upper - 1) / (rpm * accounts),
|
| 371 |
+
"note": "Quota-based estimate excludes latency/retries; accepted count can shrink after dedup/verification."}
|
| 372 |
+
print(json.dumps(preview, ensure_ascii=False, indent=2), flush=True)
|
| 373 |
+
if dry_run:
|
| 374 |
+
return preview
|
| 375 |
+
if missing and stage == "verify":
|
| 376 |
+
raise ValueError("Generation incomplete; run --stage generate or --stage all first.")
|
| 377 |
+
if missing and not api_keys:
|
| 378 |
+
raise ValueError("SJTU_API_KEY unavailable in this process. Set it in your local shell and rerun.")
|
| 379 |
+
pool = AccountPool(api_keys, workers_per_key=workers_per_key, rpm=rpm, tpm=tpm, window=window) if api_keys else None
|
| 380 |
+
request_runner = Requests(output, config, pool, timeout, retries, transport)
|
| 381 |
+
workers = max(1, len(api_keys)) * workers_per_key
|
| 382 |
+
for folder in ("cache", "responses", "failures"):
|
| 383 |
+
(output / folder).mkdir(parents=True, exist_ok=True)
|
| 384 |
+
manifest = {"format": VERSION, "identity": identity, "config": config, "status": "generating",
|
| 385 |
+
"generation_prompt_sha256": digest(PROMPT), "verification_prompt_sha256": digest(VERIFY_PROMPT),
|
| 386 |
+
"note": "Synthetic AI-generated/verified evaluation only; training overlap unknown; not AzooKey outputs or open-ended suggestion accuracy."}
|
| 387 |
+
write_json(output / "manifest.json", manifest)
|
| 388 |
+
if stage in {"all", "generate"}:
|
| 389 |
+
work = [(job["id"], generation_payload(job, config), lambda body, job=job: parse_generated(body, job)) for job in missing]
|
| 390 |
+
generated.update(execute(request_runner, work, workers))
|
| 391 |
+
cases, duplicates = canonical_cases(jobs, generated, config)
|
| 392 |
+
jsonl(output / "draft.jsonl", cases)
|
| 393 |
+
write_json(output / "duplicates.json", duplicates)
|
| 394 |
+
if stage == "generate":
|
| 395 |
+
# Do not downgrade an already completed benchmark on a cached rerun.
|
| 396 |
+
if old and old.get("status") == "complete":
|
| 397 |
+
write_json(manifest_path, old)
|
| 398 |
+
else:
|
| 399 |
+
write_json(manifest_path, {**manifest, "status": "awaiting_verification", "draft_cases": len(cases)})
|
| 400 |
+
return {"draft_cases": len(cases), "status": "awaiting_verification"}
|
| 401 |
+
batches = [cases[i:i + config["verify_batch_size"]] for i in range(0, len(cases), config["verify_batch_size"])]
|
| 402 |
+
write_json(manifest_path, {**manifest, "status": "verifying", "draft_cases": len(cases)})
|
| 403 |
+
checked = execute(request_runner, [(str(i), verification_payload(batch, config),
|
| 404 |
+
lambda body, batch=batch: parse_verified(body, batch)) for i, batch in enumerate(batches)], workers)
|
| 405 |
+
decisions = [decision for i in range(len(batches)) for decision in checked[str(i)]]
|
| 406 |
+
accepted, rejected = finalize(cases, decisions)
|
| 407 |
+
jsonl(output / "quarantine.jsonl", rejected)
|
| 408 |
+
jsonl(output / "benchmark.jsonl", accepted)
|
| 409 |
+
write_json(output / "verification.json", decisions)
|
| 410 |
+
write_json(output / "manual-audit.json", audit_sample(accepted, rejected))
|
| 411 |
+
stats = {"target_generated_cases": target, "unique_draft_cases": len(cases), "duplicate_contexts": len(duplicates),
|
| 412 |
+
"accepted_cases": len(accepted), "quarantined_cases": len(rejected),
|
| 413 |
+
"accepted_by_task": dict(Counter(case["task"] for case in accepted)),
|
| 414 |
+
"accepted_by_category": dict(Counter(case["category"] for case in accepted)),
|
| 415 |
+
"gold_position_counts": dict(Counter(str(case["candidates"].index(case["acceptable"][0])) for case in accepted)),
|
| 416 |
+
"network_requests_sent_this_run": request_runner.started,
|
| 417 |
+
"accounts_this_run": pool.snapshot() if pool else [],
|
| 418 |
+
"generator_equals_verifier": config["model"] == config["judge_model"]}
|
| 419 |
+
write_json(output / "stats.json", stats)
|
| 420 |
+
write_json(manifest_path, {**manifest, "status": "complete", "benchmark_sha256": file_sha(output / "benchmark.jsonl"),
|
| 421 |
+
"stats": stats, "manual_review_done": False})
|
| 422 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2), flush=True)
|
| 423 |
+
return stats
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def load_pools(path):
|
| 427 |
+
pools = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 428 |
+
seen = set()
|
| 429 |
+
for group in pools["groups"]:
|
| 430 |
+
if group["id"] in seen or not re.fullmatch(r"[ぁ-ゖー]+", group["reading"]):
|
| 431 |
+
raise ValueError("Invalid homophone group or reading.")
|
| 432 |
+
seen.add(group["id"])
|
| 433 |
+
if not 2 <= len(group["candidates"]) <= 8 or len(set(group["candidates"])) != len(group["candidates"]):
|
| 434 |
+
raise ValueError("Invalid homophone pool.")
|
| 435 |
+
for text in group["candidates"]:
|
| 436 |
+
clean_text(text, 1, 15)
|
| 437 |
+
return pools
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def main(argv=None):
|
| 441 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 442 |
+
parser.add_argument("--output", type=Path, default=ROOT / "artifacts/benchmarks/ime-synthetic-v1")
|
| 443 |
+
parser.add_argument("--pools", type=Path, default=ROOT / "configs/ime-homophones.json")
|
| 444 |
+
parser.add_argument("--per-category", type=int, default=50)
|
| 445 |
+
parser.add_argument("--contexts-per-target", type=int, default=5)
|
| 446 |
+
parser.add_argument("--batch-size", type=int, default=10)
|
| 447 |
+
parser.add_argument("--verify-batch-size", type=int, default=20)
|
| 448 |
+
parser.add_argument("--model", default=MODEL)
|
| 449 |
+
parser.add_argument("--judge-model", default="qwen", help="Blind verifier; separate model by default.")
|
| 450 |
+
parser.add_argument("--key-envs", default="SJTU_API_KEY", help="Comma-separated env names for independent accounts.")
|
| 451 |
+
parser.add_argument("--workers-per-key", type=int, default=3)
|
| 452 |
+
parser.add_argument("--rpm", type=int, default=8)
|
| 453 |
+
parser.add_argument("--tpm", type=int, default=80000)
|
| 454 |
+
parser.add_argument("--output-tokens", type=int, default=4096)
|
| 455 |
+
parser.add_argument("--timeout", type=int, default=180)
|
| 456 |
+
parser.add_argument("--retries", type=int, default=2)
|
| 457 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 458 |
+
parser.add_argument("--stage", choices=("all", "generate", "verify"), default="all")
|
| 459 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 460 |
+
args = parser.parse_args(argv)
|
| 461 |
+
if min(args.per_category, args.contexts_per_target) < 0 or args.per_category + args.contexts_per_target == 0:
|
| 462 |
+
parser.error("Enable at least one task with a positive target.")
|
| 463 |
+
if not 1 <= args.batch_size <= 20 or not 1 <= args.verify_batch_size <= 30 or not 1 <= args.workers_per_key <= 8:
|
| 464 |
+
parser.error("Invalid batch/concurrency settings.")
|
| 465 |
+
if not 1 <= args.rpm <= 10 or not 10000 <= args.tpm <= 100000 or not 1 <= args.output_tokens <= 16000 or args.timeout < 1 or not 0 <= args.retries <= 5:
|
| 466 |
+
parser.error("Invalid quota/output/timeout/retry settings.")
|
| 467 |
+
envs = [name.strip() for name in args.key_envs.split(",")]
|
| 468 |
+
if not 1 <= len(envs) <= 8 or len(set(envs)) != len(envs) or any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) for name in envs):
|
| 469 |
+
parser.error("Invalid key environment variable names.")
|
| 470 |
+
# Dry-run accepts account labels without reading/printing secret values.
|
| 471 |
+
keys = tuple(os.environ.get(name, "").strip() for name in envs) if not args.dry_run else ()
|
| 472 |
+
if keys and any(not key for key in keys):
|
| 473 |
+
keys = ()
|
| 474 |
+
if keys and len(set(keys)) != len(keys):
|
| 475 |
+
parser.error("Duplicate keys do not increase quota.")
|
| 476 |
+
config = {"per_category": args.per_category, "contexts_per_target": args.contexts_per_target,
|
| 477 |
+
"batch_size": args.batch_size, "verify_batch_size": args.verify_batch_size,
|
| 478 |
+
"model": args.model, "judge_model": args.judge_model, "output_tokens": args.output_tokens,
|
| 479 |
+
"seed": args.seed, "endpoint": ENDPOINT, "pools_sha256": file_sha(args.pools)}
|
| 480 |
+
pools = load_pools(args.pools)
|
| 481 |
+
if args.dry_run:
|
| 482 |
+
run(args.output, config, pools, dry_run=True, rpm=args.rpm, stage=args.stage, account_count=len(envs))
|
| 483 |
+
return
|
| 484 |
+
with output_lock(args.output):
|
| 485 |
+
run(args.output, config, pools, args.stage, keys, args.workers_per_key, args.rpm,
|
| 486 |
+
args.tpm, args.timeout, args.retries)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
if __name__ == "__main__":
|
| 490 |
+
main()
|
source/src/vimeml/benchmarks/hybrid.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cache local LM scores, calibrate on independent development data, evaluate a fixed policy."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
import unicodedata
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from vimeml.benchmarks.ajimee import DEVELOPMENT_FORMAT, ROOT, convert_items, json_bytes, sha
|
| 11 |
+
from vimeml.benchmarks.evaluate_ajimee import load_export, metrics, read_json, rerank, summarize
|
| 12 |
+
|
| 13 |
+
CACHE_FORMAT = "ime_hybrid_score_cache_v1"
|
| 14 |
+
POLICY_FORMAT = "ime_hybrid_policy_v1"
|
| 15 |
+
FORMULA = "azookey_score + lambda * contextual_log_probability_sum"
|
| 16 |
+
GRID = [0., .05, .1, .2, .3, .5, .75, 1., 1.5, 2., 3.]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def output_directory(path):
|
| 20 |
+
if path.exists() and any(path.iterdir()):
|
| 21 |
+
raise ValueError("Output is not empty; use a new --output to preserve previous results.")
|
| 22 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def canonical(text):
|
| 26 |
+
return "".join(unicodedata.normalize("NFKC", text).split())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def overlap_keys(rows):
|
| 30 |
+
return ({(canonical(row["query"]), canonical(row["left_context"])) for row in rows},
|
| 31 |
+
{canonical(row["left_context"] + answer) for row in rows for answer in row["answers"]})
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def check_independence(development, excluded):
|
| 35 |
+
dev_queries, dev_texts = overlap_keys(development)
|
| 36 |
+
queries, texts = overlap_keys(excluded)
|
| 37 |
+
if dev_queries & queries or dev_texts & texts:
|
| 38 |
+
raise ValueError("Development examples overlap the excluded AJIMEE set (normalized query/context or context+answer).")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def prepare_development(input_path, output, excluded, labels_reviewed=False):
|
| 42 |
+
raw = input_path.read_bytes()
|
| 43 |
+
converted, mapping, stats = convert_items(json.loads(raw.decode("utf-8-sig")))
|
| 44 |
+
keys, _ = overlap_keys(mapping)
|
| 45 |
+
if len(keys) != len(mapping):
|
| 46 |
+
raise ValueError("Duplicate development query/context pair.")
|
| 47 |
+
if not excluded.exists():
|
| 48 |
+
raise ValueError("Excluded AJIMEE source is missing; specify --exclude.")
|
| 49 |
+
exclude_raw = excluded.read_bytes()
|
| 50 |
+
_, exclude_mapping, _ = convert_items(json.loads(exclude_raw.decode("utf-8-sig")))
|
| 51 |
+
check_independence(mapping, exclude_mapping)
|
| 52 |
+
output_directory(output)
|
| 53 |
+
files = {"evaluation_items.json": raw, "ajimee-input.json": json_bytes(converted), "case-map.json": json_bytes(mapping)}
|
| 54 |
+
for name, content in files.items():
|
| 55 |
+
(output / name).write_bytes(content)
|
| 56 |
+
manifest = {"format": DEVELOPMENT_FORMAT, "status": "complete", "role": "development",
|
| 57 |
+
"source_path": str(input_path.resolve()), "source_sha256": sha(raw), "stats": stats,
|
| 58 |
+
"labels_reviewed": labels_reviewed,
|
| 59 |
+
"label_status": "reviewed_by_user_assertion" if labels_reviewed else "provisional_synthetic_labels",
|
| 60 |
+
"excluded_source_sha256": sha(exclude_raw),
|
| 61 |
+
"files_sha256": {name: sha(content) for name, content in files.items()},
|
| 62 |
+
"policy": "Synthetic development only; all text/references preserved. No candidate/model-score filtering. Reading and label quality require review."}
|
| 63 |
+
(output / "manifest.json").write_bytes(json_bytes(manifest))
|
| 64 |
+
return manifest
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def fingerprint(metadata, provenance):
|
| 68 |
+
dictionaries = []
|
| 69 |
+
for line in provenance["dictionary-versions.txt"].splitlines():
|
| 70 |
+
match = re.match(r"^ ([0-9a-f]{40}) (\S+)", line)
|
| 71 |
+
if not match:
|
| 72 |
+
raise ValueError("Invalid/unpinned dictionary version record.")
|
| 73 |
+
dictionaries.append({"commit": match[1], "path": match[2]})
|
| 74 |
+
converter = provenance["converter-version.txt"].strip()
|
| 75 |
+
if not re.fullmatch(r"[0-9a-f]{40}", converter) or not dictionaries:
|
| 76 |
+
raise ValueError("Missing converter/dictionary commit.")
|
| 77 |
+
return {"checkpoint_sha256": metadata["checkpoint_sha256"], "tokenizer_sha256": metadata["tokenizer_sha256"],
|
| 78 |
+
"model_config": metadata["model"], "precision": metadata["precision"],
|
| 79 |
+
"converter_commit": converter, "dictionaries": sorted(dictionaries, key=lambda row: row["path"]),
|
| 80 |
+
"n_best": provenance["n_best"]}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def save_cache(benchmark, output, checkpoint, tokenizer, device, threads):
|
| 84 |
+
if output.exists() and any(output.iterdir()):
|
| 85 |
+
raise ValueError("Cache output is not empty; choose a new --output.")
|
| 86 |
+
manifest, provenance, rows = load_export(benchmark)
|
| 87 |
+
import torch
|
| 88 |
+
from vimeml.training.infer import JapaneseLM
|
| 89 |
+
torch.set_num_threads(threads)
|
| 90 |
+
start = time.perf_counter()
|
| 91 |
+
lm = JapaneseLM(checkpoint, tokenizer, device)
|
| 92 |
+
rerank(lm, rows)
|
| 93 |
+
output_directory(output)
|
| 94 |
+
content = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows).encode("utf-8")
|
| 95 |
+
(output / "scores.jsonl").write_bytes(content)
|
| 96 |
+
cache = {"format": CACHE_FORMAT, "status": "complete", "model": lm.metadata,
|
| 97 |
+
"benchmark_manifest": manifest, "export_provenance": provenance,
|
| 98 |
+
"files_sha256": {"scores.jsonl": sha(content)}, "fingerprint": fingerprint(lm.metadata, provenance),
|
| 99 |
+
"elapsed_seconds": time.perf_counter() - start}
|
| 100 |
+
(output / "manifest.json").write_bytes(json_bytes(cache))
|
| 101 |
+
return cache
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def load_cache(directory):
|
| 105 |
+
# Reuse the existing frozen AJIMEE evaluation without another LM forward pass.
|
| 106 |
+
path = directory / "manifest.json"
|
| 107 |
+
if path.exists():
|
| 108 |
+
cache = read_json(path)
|
| 109 |
+
if cache.get("format") != CACHE_FORMAT:
|
| 110 |
+
raise ValueError("Unknown score cache format.")
|
| 111 |
+
else:
|
| 112 |
+
cache = read_json(directory / "metrics.json")
|
| 113 |
+
if cache.get("format") != "ajimee_ime_metrics_v1":
|
| 114 |
+
raise ValueError("Unknown evaluation cache format.")
|
| 115 |
+
if cache.get("status") != "complete" or not cache.get("model"):
|
| 116 |
+
raise ValueError("Expected complete model scores.")
|
| 117 |
+
raw = (directory / "scores.jsonl").read_bytes()
|
| 118 |
+
if sha(raw) != cache["files_sha256"]["scores.jsonl"]:
|
| 119 |
+
raise ValueError("Cached scores changed.")
|
| 120 |
+
rows = [json.loads(line) for line in raw.decode("utf-8").splitlines() if line.strip()]
|
| 121 |
+
if not rows or len(rows) != cache["benchmark_manifest"]["stats"]["cases"] or len({r["id"] for r in rows}) != len(rows):
|
| 122 |
+
raise ValueError("Invalid score cache sample count/IDs.")
|
| 123 |
+
for row in rows:
|
| 124 |
+
texts = [c["text"] for c in row["candidates"]]
|
| 125 |
+
if texts != row["orders"]["azookey"] or len(set(texts)) != len(texts):
|
| 126 |
+
raise ValueError("Cached original candidate order changed.")
|
| 127 |
+
if any(not math.isfinite(c["score"]) for c in row["candidates"]):
|
| 128 |
+
raise ValueError("Nonfinite AzooKey score.")
|
| 129 |
+
scores = row.get("lm_scores", {}).get("contextual")
|
| 130 |
+
if "lm_context_sum" in row["fallbacks"]:
|
| 131 |
+
if row["orders"]["lm_context_sum"] != texts:
|
| 132 |
+
raise ValueError("Invalid whole-case fallback.")
|
| 133 |
+
elif not scores or [c["text"] for c in scores["candidates"]] != texts:
|
| 134 |
+
raise ValueError("Cached contextual scores do not align with original candidates.")
|
| 135 |
+
else:
|
| 136 |
+
for candidate in scores["candidates"]:
|
| 137 |
+
probabilities = candidate["token_log_probabilities"]
|
| 138 |
+
if not probabilities or len(probabilities) != candidate["scored_tokens"] or len(candidate["token_ids"]) != len(probabilities):
|
| 139 |
+
raise ValueError("Invalid cached token trace.")
|
| 140 |
+
if not all(math.isfinite(v) for v in probabilities) or not math.isclose(sum(probabilities), candidate["log_probability_sum"], abs_tol=1e-6):
|
| 141 |
+
raise ValueError("Cached LM total differs from token trace.")
|
| 142 |
+
cache["fingerprint"] = fingerprint(cache["model"], cache["export_provenance"])
|
| 143 |
+
cache["cache_directory"] = str(directory.resolve())
|
| 144 |
+
return cache, rows
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def valid_weight(value):
|
| 148 |
+
if not math.isfinite(value) or value < 0:
|
| 149 |
+
raise ValueError("lambda must be finite and nonnegative.")
|
| 150 |
+
return value
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def hybrid_order(candidates, scores, weight):
|
| 154 |
+
"""No labels, normalization, length bonus or candidate filtering on this path."""
|
| 155 |
+
valid_weight(weight)
|
| 156 |
+
if weight == 0:
|
| 157 |
+
return [c["text"] for c in candidates], [c["score"] for c in candidates]
|
| 158 |
+
if [c["text"] for c in candidates] != [c["text"] for c in scores]:
|
| 159 |
+
raise ValueError("Hybrid score alignment mismatch.")
|
| 160 |
+
values = [c["score"] + weight * s["log_probability_sum"] for c, s in zip(candidates, scores)]
|
| 161 |
+
if not all(math.isfinite(v) for v in values):
|
| 162 |
+
raise ValueError("Nonfinite combined score.")
|
| 163 |
+
indices = sorted(range(len(candidates)), key=lambda i: values[i], reverse=True)
|
| 164 |
+
return [candidates[i]["text"] for i in indices], values
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def add_hybrid(rows, weight, details=True):
|
| 168 |
+
valid_weight(weight)
|
| 169 |
+
for row in rows:
|
| 170 |
+
if "lm_context_sum" in row["fallbacks"] and weight > 0:
|
| 171 |
+
row["orders"]["hybrid"] = list(row["orders"]["azookey"])
|
| 172 |
+
row["fallbacks"]["hybrid"] = row["fallbacks"]["lm_context_sum"]
|
| 173 |
+
values = None
|
| 174 |
+
else:
|
| 175 |
+
scored = row.get("lm_scores", {}).get("contextual", {}).get("candidates", [])
|
| 176 |
+
row["orders"]["hybrid"], values = hybrid_order(row["candidates"], scored, weight)
|
| 177 |
+
row["fallbacks"].pop("hybrid", None)
|
| 178 |
+
if details:
|
| 179 |
+
row["hybrid_scores_original_order"] = values
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def script_profile(text):
|
| 183 |
+
return {"kanji": sum('\u3400' <= c <= '\u9fff' for c in text),
|
| 184 |
+
"hiragana": sum('\u3040' <= c <= '\u309f' for c in text),
|
| 185 |
+
"katakana": sum('\u30a0' <= c <= '\u30ff' for c in text),
|
| 186 |
+
"latin": sum(c.isascii() and c.isalpha() for c in text), "digits": sum(c.isdecimal() for c in text)}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def diagnostics(row):
|
| 190 |
+
scored = row.get("lm_scores", {}).get("contextual", {}).get("candidates", [])
|
| 191 |
+
prefixes, fallback = [], []
|
| 192 |
+
for i, candidate in enumerate(scored):
|
| 193 |
+
byte_count = sum(piece.startswith("<0x") for piece in candidate["pieces"])
|
| 194 |
+
if byte_count:
|
| 195 |
+
fallback.append({"text": candidate["text"], "byte_tokens": byte_count})
|
| 196 |
+
for other in scored[i + 1:]:
|
| 197 |
+
a, b = candidate, other
|
| 198 |
+
if len(a["token_ids"]) > len(b["token_ids"]):
|
| 199 |
+
a, b = b, a
|
| 200 |
+
if len(a["token_ids"]) < len(b["token_ids"]) and b["token_ids"][:len(a["token_ids"])] == a["token_ids"]:
|
| 201 |
+
prefixes.append({"shorter": a["text"], "longer": b["text"]})
|
| 202 |
+
original, selected = row["orders"]["azookey"], row["orders"]["hybrid"]
|
| 203 |
+
before, after = original[0] if original else "", selected[0] if selected else ""
|
| 204 |
+
return {"strict_token_prefix_pairs": prefixes, "byte_fallback_candidates": fallback,
|
| 205 |
+
"boundary_retokenized_candidates": sum(c["boundary_retokenized"] for c in scored),
|
| 206 |
+
"top1_changed": before != after, "before_script_profile": script_profile(before),
|
| 207 |
+
"after_script_profile": script_profile(after),
|
| 208 |
+
"script_profile_changed": script_profile(before) != script_profile(after)}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def calibrate(cache, rows, grid):
|
| 212 |
+
if cache["benchmark_manifest"].get("role") != "development" or cache["benchmark_manifest"]["format"] != DEVELOPMENT_FORMAT:
|
| 213 |
+
raise ValueError("Automatic lambda selection requires an independent development cache; AJIMEE cannot be tuned.")
|
| 214 |
+
if not cache["benchmark_manifest"].get("labels_reviewed"):
|
| 215 |
+
raise ValueError("Development readings/references need review before calibration; prepare a reviewed version with --labels-reviewed.")
|
| 216 |
+
if not grid or len(set(grid)) != len(grid):
|
| 217 |
+
raise ValueError("Expected a nonempty grid of distinct lambda values.")
|
| 218 |
+
records = []
|
| 219 |
+
for weight in grid:
|
| 220 |
+
valid_weight(weight)
|
| 221 |
+
add_hybrid(rows, weight, details=False)
|
| 222 |
+
records.append({"lambda": weight, "metrics": metrics(rows, "hybrid")})
|
| 223 |
+
chosen = min(records, key=lambda record: (-record["metrics"]["top1_correct"],
|
| 224 |
+
record["metrics"]["regressed_vs_azookey"], record["lambda"]))
|
| 225 |
+
return {"format": POLICY_FORMAT, "status": "development_selected", "formula": FORMULA,
|
| 226 |
+
"lambda": chosen["lambda"], "fingerprint": cache["fingerprint"],
|
| 227 |
+
"selection_rule": "Highest development Top-1; ties prefer fewer regressions; remaining ties prefer smaller lambda.",
|
| 228 |
+
"development_source_sha256": cache["benchmark_manifest"]["source_sha256"],
|
| 229 |
+
"development_scores_sha256": cache["files_sha256"]["scores.jsonl"],
|
| 230 |
+
"excluded_source_sha256": cache["benchmark_manifest"]["excluded_source_sha256"],
|
| 231 |
+
"development_overlap_keys": {"queries": sorted([list(key) for key in overlap_keys(rows)[0]]),
|
| 232 |
+
"texts": sorted(overlap_keys(rows)[1])},
|
| 233 |
+
"grid": records}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def validate_policy(policy, cache, rows):
|
| 237 |
+
if policy.get("format") != POLICY_FORMAT or policy.get("status") != "development_selected" or policy.get("formula") != FORMULA:
|
| 238 |
+
raise ValueError("Invalid selected policy.")
|
| 239 |
+
valid_weight(policy["lambda"])
|
| 240 |
+
if policy["fingerprint"] != cache["fingerprint"]:
|
| 241 |
+
raise ValueError("Policy model/tokenizer/converter/dictionary/precision/n_best differs from this cache.")
|
| 242 |
+
if policy["development_source_sha256"] == cache["benchmark_manifest"]["source_sha256"]:
|
| 243 |
+
raise ValueError("Selected-policy evaluation must use different data from calibration.")
|
| 244 |
+
queries, texts = overlap_keys(rows)
|
| 245 |
+
dev = policy["development_overlap_keys"]
|
| 246 |
+
if queries & {tuple(key) for key in dev["queries"]} or texts & set(dev["texts"]):
|
| 247 |
+
raise ValueError("Evaluation examples overlap calibration data.")
|
| 248 |
+
return policy["lambda"]
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def evaluate(cache, rows, weight, output, policy=None):
|
| 252 |
+
valid_weight(weight)
|
| 253 |
+
if output.exists() and any(output.iterdir()):
|
| 254 |
+
raise ValueError("Output is not empty; choose a new --output.")
|
| 255 |
+
add_hybrid(rows, weight)
|
| 256 |
+
changed = []
|
| 257 |
+
for row in rows:
|
| 258 |
+
row["hybrid_diagnostics"] = diagnostics(row)
|
| 259 |
+
if row["hybrid_diagnostics"]["top1_changed"]:
|
| 260 |
+
before, after = row["orders"]["azookey"][0], row["orders"]["hybrid"][0]
|
| 261 |
+
changed.append({"id": row["id"], "context": row["left_context"], "query": row["query"],
|
| 262 |
+
"answers": row["answers"], "before": before, "after": after,
|
| 263 |
+
"before_correct": before in row["answers"], "after_correct": after in row["answers"],
|
| 264 |
+
"diagnostics": row["hybrid_diagnostics"]})
|
| 265 |
+
report = {"format": "ime_hybrid_evaluation_v1", "status": "complete", "formula": FORMULA, "lambda": weight,
|
| 266 |
+
"coefficient_source": "independent_development_policy" if policy else "user_specified_not_calibrated",
|
| 267 |
+
"policy": policy, "score_cache": cache, "metrics": summarize(rows),
|
| 268 |
+
"diagnostics": {"strict_prefix_cases": sum(bool(r["hybrid_diagnostics"]["strict_token_prefix_pairs"]) for r in rows),
|
| 269 |
+
"byte_fallback_cases": sum(bool(r["hybrid_diagnostics"]["byte_fallback_candidates"]) for r in rows),
|
| 270 |
+
"top1_changed_cases": len(changed),
|
| 271 |
+
"script_profile_changed_cases": sum(r["hybrid_diagnostics"]["script_profile_changed"] for r in rows)},
|
| 272 |
+
"policy_notes": "Same real candidate pool; stable ties; raw scores, no EOS/length normalization/extra filters. Whole-case LM fallback. Diagnostics never alter ranking. Strict reference matching; training overlap unknown."}
|
| 273 |
+
output_directory(output)
|
| 274 |
+
(output / "scores.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8")
|
| 275 |
+
(output / "changed-cases.json").write_bytes(json_bytes(changed))
|
| 276 |
+
report["files_sha256"] = {name: sha((output / name).read_bytes()) for name in ("scores.jsonl", "changed-cases.json")}
|
| 277 |
+
(output / "metrics.json").write_bytes(json_bytes(report))
|
| 278 |
+
lines = ["# AzooKey + LM组合评分", "", f"λ = {weight:g};系数来源:{report['coefficient_source']}。", "",
|
| 279 |
+
"同一冻结候选池;并列保持原顺序;超长/无法完整计分时整条回退。表记诊断不是自动语义判分。", "",
|
| 280 |
+
"| 策略 | 样本数 | Top-1 | Top-5 | MinCER | 纠正 / 改坏 | 回退 |",
|
| 281 |
+
"| --- | ---: | ---: | ---: | ---: | ---: | ---: |"]
|
| 282 |
+
for method in ("azookey", "lm_context_sum", "lm_no_context_sum", "hybrid"):
|
| 283 |
+
m = report["metrics"]["all"][method]
|
| 284 |
+
lines.append(f"| {method} | {m['cases']} | {m['top1_correct']} ({m['top1_accuracy']:.1%}) | {m['top5_correct']} ({m['top5_accuracy']:.1%}) | "
|
| 285 |
+
f"{m['mean_min_cer']:.5f} | {m['corrected_vs_azookey']} / {m['regressed_vs_azookey']} | {m['fallback_cases']} |")
|
| 286 |
+
lines += ["", "完整分组、版本与hash见metrics.json,逐候选组合分数与诊断见scores.jsonl,所有首选变化见changed-cases.json。", ""]
|
| 287 |
+
(output / "results.md").write_text("\n".join(lines), encoding="utf-8")
|
| 288 |
+
return report
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def main(argv=None):
|
| 292 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 293 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 294 |
+
prepare = sub.add_parser("prepare-dev", help="Prepare reviewed DeepSeek JSON for the same Mac export command.")
|
| 295 |
+
prepare.add_argument("--input", type=Path, required=True)
|
| 296 |
+
prepare.add_argument("--output", type=Path, default=ROOT / "artifacts/benchmarks/ime-dev-v1")
|
| 297 |
+
prepare.add_argument("--exclude", type=Path, default=ROOT / "artifacts/benchmarks/ajimee-jwtd-v2-v1/evaluation_items.json")
|
| 298 |
+
prepare.add_argument("--labels-reviewed", action="store_true", help="Assert readings and acceptable references have been independently reviewed.")
|
| 299 |
+
score = sub.add_parser("score", help="Compute local LM once for a real candidate export.")
|
| 300 |
+
score.add_argument("--benchmark", type=Path, required=True)
|
| 301 |
+
score.add_argument("--output", type=Path, required=True)
|
| 302 |
+
score.add_argument("--checkpoint", type=Path, default=ROOT / "artifacts/models/tiny-ja-v1/best.pt")
|
| 303 |
+
score.add_argument("--tokenizer", type=Path, default=ROOT / "artifacts/tokenizers/ja-unigram-16k-v1")
|
| 304 |
+
score.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
|
| 305 |
+
score.add_argument("--threads", type=int, default=4)
|
| 306 |
+
tune = sub.add_parser("tune", help="Select lambda only on reviewed independent development data.")
|
| 307 |
+
tune.add_argument("--scores", type=Path, required=True)
|
| 308 |
+
tune.add_argument("--grid", type=float, nargs="+", default=GRID)
|
| 309 |
+
tune.add_argument("--output", type=Path, required=True)
|
| 310 |
+
run = sub.add_parser("evaluate", help="Evaluate one fixed lambda or a saved development policy.")
|
| 311 |
+
run.add_argument("--scores", type=Path, default=ROOT / "outputs/ime-eval/tiny-ja-v1-ajimee")
|
| 312 |
+
option = run.add_mutually_exclusive_group(required=True)
|
| 313 |
+
option.add_argument("--lambda", type=float, dest="weight")
|
| 314 |
+
option.add_argument("--policy", type=Path)
|
| 315 |
+
run.add_argument("--output", type=Path, required=True)
|
| 316 |
+
args = parser.parse_args(argv)
|
| 317 |
+
try:
|
| 318 |
+
if args.command == "prepare-dev":
|
| 319 |
+
result = prepare_development(args.input, args.output, args.exclude, args.labels_reviewed)
|
| 320 |
+
print(json.dumps(result["stats"], indent=2))
|
| 321 |
+
print(f"Mac input: {args.output.resolve() / 'ajimee-input.json'}")
|
| 322 |
+
elif args.command == "score":
|
| 323 |
+
if args.threads < 1:
|
| 324 |
+
raise ValueError("threads must be positive.")
|
| 325 |
+
save_cache(args.benchmark, args.output, args.checkpoint, args.tokenizer, args.device, args.threads)
|
| 326 |
+
print(f"Score cache: {args.output.resolve()}")
|
| 327 |
+
else:
|
| 328 |
+
cache, rows = load_cache(args.scores)
|
| 329 |
+
if args.command == "tune":
|
| 330 |
+
result = calibrate(cache, rows, args.grid)
|
| 331 |
+
output_directory(args.output)
|
| 332 |
+
(args.output / "policy.json").write_bytes(json_bytes(result))
|
| 333 |
+
print(f"Development-selected lambda: {result['lambda']:g}")
|
| 334 |
+
print(f"Policy: {args.output.resolve() / 'policy.json'}")
|
| 335 |
+
else:
|
| 336 |
+
policy = read_json(args.policy) if args.policy else None
|
| 337 |
+
weight = validate_policy(policy, cache, rows) if policy else args.weight
|
| 338 |
+
report = evaluate(cache, rows, weight, args.output, policy)
|
| 339 |
+
print(json.dumps(report["metrics"]["all"]["hybrid"], indent=2))
|
| 340 |
+
print(f"Report: {args.output.resolve() / 'results.md'}")
|
| 341 |
+
except (ValueError, OSError, KeyError, TypeError) as error:
|
| 342 |
+
parser.exit(2, f"Error: {error}\n")
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
if __name__ == "__main__":
|
| 346 |
+
main()
|
source/src/vimeml/benchmarks/notation.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Notation-aware error classes for same-reading kana-kanji conversions.
|
| 2 |
+
|
| 3 |
+
All candidates in a pool convert the same kana input, so a wrong choice either spells
|
| 4 |
+
the same words differently (notation, A) or picks different words (semantic, S).
|
| 5 |
+
Conservative A: equal UniDic lemma sequences AND nested kanji sets. Against 210 earlier
|
| 6 |
+
hand-tagged V2.1/V4.2 flips this never labels a semantic flip as A (72/72) and recovers
|
| 7 |
+
118/138 notation flips; satisfying only one rule is reported as an upper bound ('a').
|
| 8 |
+
Requires `fugashi` and `unidic-lite` (requirements/evaluation.txt).
|
| 9 |
+
"""
|
| 10 |
+
import unicodedata
|
| 11 |
+
|
| 12 |
+
import fugashi
|
| 13 |
+
|
| 14 |
+
_TAGGER = None
|
| 15 |
+
_SKIP = ('補助記号', '空白')
|
| 16 |
+
ERROR_CLASSES = ('correct', 'pool_miss', 'notation', 'notation_upper', 'semantic')
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _tagger():
|
| 20 |
+
global _TAGGER
|
| 21 |
+
if _TAGGER is None:
|
| 22 |
+
_TAGGER = fugashi.Tagger()
|
| 23 |
+
return _TAGGER
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def nfkc(text):
|
| 27 |
+
return unicodedata.normalize('NFKC', text)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def kanji(text):
|
| 31 |
+
return {c for c in text if '一' <= c <= '鿿' or c in '々〆ヶ'}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def kana_share(text):
|
| 35 |
+
letters = [c for c in text if c.isalpha()]
|
| 36 |
+
return sum('ぁ' <= c <= 'ヿ' for c in letters) / len(letters) if letters else 0.0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def lemmas(text):
|
| 40 |
+
return [w.feature.lemma or w.surface for w in _tagger()(nfkc(text)) if w.feature.pos1 not in _SKIP]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def relation(choice, answer):
|
| 44 |
+
"""'=' exact, 'A' notation (conservative), 'a' notation by one rule only, 'S' semantic."""
|
| 45 |
+
if choice == answer:
|
| 46 |
+
return '='
|
| 47 |
+
same_lemmas = lemmas(choice) == lemmas(answer)
|
| 48 |
+
nested = kanji(choice) <= kanji(answer) or kanji(answer) <= kanji(choice)
|
| 49 |
+
if same_lemmas and nested:
|
| 50 |
+
return 'A'
|
| 51 |
+
return 'a' if same_lemmas or nested else 'S'
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def error_class(row, choice):
|
| 55 |
+
"""Class of a Top-1 choice and the closest reachable reference ('answer' is None if unreachable)."""
|
| 56 |
+
answers = row['answers']
|
| 57 |
+
if choice in answers:
|
| 58 |
+
return 'correct', choice
|
| 59 |
+
pool = {c['text'] for c in row['candidates']}
|
| 60 |
+
reachable = [a for a in answers if a in pool]
|
| 61 |
+
if not reachable:
|
| 62 |
+
return 'pool_miss', None
|
| 63 |
+
rank, answer = min(('=AaS'.index(relation(choice, a)), a) for a in reachable)
|
| 64 |
+
return {1: 'notation', 2: 'notation_upper', 3: 'semantic'}[rank], answer
|
source/src/vimeml/benchmarks/predict_zh.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Decoder, simulation and metrics of the Chinese prediction benchmark ime-predict-zh-v1.
|
| 2 |
+
|
| 3 |
+
Protocol: docs/zh-CN/benchmarks/predict-zh-plan.md; implementation details fixed before any
|
| 4 |
+
score: docs/zh-CN/benchmarks/predict-ime-zh.md (解码与模拟的实现细节).
|
| 5 |
+
|
| 6 |
+
Every language model goes through the same decoder; only the adapter differs (how turns are
|
| 7 |
+
joined into token ids, and next-token log-probabilities):
|
| 8 |
+
|
| 9 |
+
- context: the adapter joins earlier turns and the typed prefix in its own training format
|
| 10 |
+
and drops the oldest whole turns that do not fit, keeping RESERVE tokens for decoding;
|
| 11 |
+
- token healing: when the prefix ends in Chinese and its last token is pure Chinese, that
|
| 12 |
+
token is taken back and every hypothesis must start by re-spelling it;
|
| 13 |
+
- beam search, width 16, one token per step, only tokens whose text is entirely Chinese
|
| 14 |
+
characters, at most 6 new characters; every hypothesis ending on a token boundary with
|
| 15 |
+
2-6 new characters is a candidate, scored by the sum of its token log-probabilities
|
| 16 |
+
(the best path when several spell the same string);
|
| 17 |
+
- the top 5 candidates by score that are not prefixes of one another;
|
| 18 |
+
- track C keeps only hypotheses compatible with the typed keys (rime-ice single-character
|
| 19 |
+
readings).
|
| 20 |
+
"""
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
import re
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
|
| 29 |
+
HAN = re.compile("[〇㐀-䶿一-鿿豈-]")
|
| 30 |
+
HAN_RUN = re.compile("[〇㐀-䶿一-鿿豈-]+")
|
| 31 |
+
BEAM = 16
|
| 32 |
+
MAX_CHARS = 6
|
| 33 |
+
MIN_CHARS = 2
|
| 34 |
+
TOP = 5
|
| 35 |
+
SHOW = 3
|
| 36 |
+
RESERVE = 12
|
| 37 |
+
NEG = float("-inf")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def all_han(text):
|
| 41 |
+
return bool(text) and all(HAN.fullmatch(c) for c in text)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def read_jsonl(path):
|
| 45 |
+
with open(path, encoding="utf-8") as stream:
|
| 46 |
+
return [json.loads(line) for line in stream if line.strip()]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_readings(dict_dir):
|
| 50 |
+
"""Character -> set of syllables (ü as v) from the rime-ice single-character tables."""
|
| 51 |
+
readings = {}
|
| 52 |
+
for name in ("8105.dict.yaml", "41448.dict.yaml"):
|
| 53 |
+
body = False
|
| 54 |
+
with open(Path(dict_dir) / name, encoding="utf-8") as stream:
|
| 55 |
+
for line in stream:
|
| 56 |
+
line = line.rstrip("\n")
|
| 57 |
+
if line == "...":
|
| 58 |
+
body = True
|
| 59 |
+
continue
|
| 60 |
+
if not body or not line or line.startswith("#"):
|
| 61 |
+
continue
|
| 62 |
+
parts = line.split("\t")
|
| 63 |
+
if len(parts) >= 2 and len(parts[0]) == 1 and parts[1].isalpha():
|
| 64 |
+
readings.setdefault(parts[0], set()).add(parts[1])
|
| 65 |
+
return readings
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass(frozen=True)
|
| 69 |
+
class Constraint:
|
| 70 |
+
"""kind 'syllable': keys is the full first syllable; kind 'initials': one letter per character."""
|
| 71 |
+
kind: str
|
| 72 |
+
keys: str
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def max_chars(self):
|
| 76 |
+
return len(self.keys) if self.kind == "initials" else MAX_CHARS
|
| 77 |
+
|
| 78 |
+
def candidate_length_ok(self, n):
|
| 79 |
+
return n == len(self.keys) if self.kind == "initials" else MIN_CHARS <= n <= MAX_CHARS
|
| 80 |
+
|
| 81 |
+
def chars_ok(self, readings, chars, done):
|
| 82 |
+
"""Can `chars` follow `done` already generated characters?"""
|
| 83 |
+
if self.kind == "syllable":
|
| 84 |
+
return done > 0 or not chars or self.keys in readings.get(chars[0], ())
|
| 85 |
+
if done + len(chars) > len(self.keys):
|
| 86 |
+
return False
|
| 87 |
+
return all(any(r.startswith(self.keys[done + i]) for r in readings.get(c, ())) for i, c in enumerate(chars))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Vocabulary:
|
| 91 |
+
"""Per-token facts the decoder needs, built once per adapter."""
|
| 92 |
+
|
| 93 |
+
def __init__(self, texts, device):
|
| 94 |
+
self.texts = texts
|
| 95 |
+
self.device = device
|
| 96 |
+
han = [t is not None and all_han(t) for t in texts]
|
| 97 |
+
self.han = torch.tensor(han, device=device)
|
| 98 |
+
self.chars = torch.tensor([len(t) if h else 0 for t, h in zip(texts, han)], device=device)
|
| 99 |
+
self.han_ids = [i for i, h in enumerate(han) if h]
|
| 100 |
+
self.by_first = {}
|
| 101 |
+
for i in self.han_ids:
|
| 102 |
+
self.by_first.setdefault(texts[i][0], []).append(i)
|
| 103 |
+
self._length = {}
|
| 104 |
+
self._constraint = {}
|
| 105 |
+
|
| 106 |
+
def length_mask(self, room):
|
| 107 |
+
if room not in self._length:
|
| 108 |
+
self._length[room] = self.han & (self.chars <= room)
|
| 109 |
+
return self._length[room]
|
| 110 |
+
|
| 111 |
+
def constraint_mask(self, constraint, readings, done):
|
| 112 |
+
key = (constraint.kind, constraint.keys[done:] if constraint.kind == "initials" else constraint.keys,
|
| 113 |
+
done if constraint.kind == "syllable" else None)
|
| 114 |
+
if key not in self._constraint:
|
| 115 |
+
if constraint.kind == "syllable" and done > 0:
|
| 116 |
+
mask = self.han
|
| 117 |
+
else:
|
| 118 |
+
ok = [i for i in self.han_ids if constraint.chars_ok(readings, self.texts[i], done)]
|
| 119 |
+
mask = torch.zeros_like(self.han)
|
| 120 |
+
mask[ok] = True
|
| 121 |
+
self._constraint[key] = mask
|
| 122 |
+
return self._constraint[key]
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def healing(lm, ids, prefix):
|
| 126 |
+
"""Take back the last context token when it is a pure-Chinese spelling of the prefix's end."""
|
| 127 |
+
if prefix and HAN.fullmatch(prefix[-1]) and len(ids) > 1:
|
| 128 |
+
text = lm.vocabulary.texts[ids[-1]]
|
| 129 |
+
if text is not None and all_han(text) and prefix.endswith(text):
|
| 130 |
+
return ids[:-1], text
|
| 131 |
+
return ids, ""
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def select(scored, top=TOP):
|
| 135 |
+
"""Highest scores first; skip a candidate that is a prefix of a chosen one or has one as prefix."""
|
| 136 |
+
chosen = []
|
| 137 |
+
for text, score in sorted(scored.items(), key=lambda x: (-x[1], x[0])):
|
| 138 |
+
if any(text.startswith(c) or c.startswith(text) for c, _ in chosen):
|
| 139 |
+
continue
|
| 140 |
+
chosen.append((text, score))
|
| 141 |
+
if len(chosen) == top:
|
| 142 |
+
break
|
| 143 |
+
return chosen
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def predict(lm, turns, prefix, constraint=None, readings=None, beam=BEAM, top=TOP):
|
| 147 |
+
"""Top candidates [(text, score)] after `prefix`, with earlier `turns` as context."""
|
| 148 |
+
vocabulary = lm.vocabulary
|
| 149 |
+
ids, required = healing(lm, lm.context(turns, prefix), prefix)
|
| 150 |
+
max_chars = constraint.max_chars if constraint else MAX_CHARS
|
| 151 |
+
if len(ids) + len(required) + max_chars > lm.context_length:
|
| 152 |
+
raise ValueError("Context leaves no room for decoding")
|
| 153 |
+
candidates = {}
|
| 154 |
+
states = [((), "", 0.0)]
|
| 155 |
+
while states:
|
| 156 |
+
logprobs = lm.logprobs([ids + list(suffix) for suffix, _, _ in states])
|
| 157 |
+
expansions = []
|
| 158 |
+
for row, (suffix, text, score) in enumerate(states):
|
| 159 |
+
pending = required[len(text):]
|
| 160 |
+
if pending:
|
| 161 |
+
for token in vocabulary.by_first.get(pending[0], ()):
|
| 162 |
+
piece = vocabulary.texts[token]
|
| 163 |
+
if piece.startswith(pending):
|
| 164 |
+
extra = piece[len(pending):]
|
| 165 |
+
if len(extra) > max_chars or (constraint and not constraint.chars_ok(readings, extra, 0)):
|
| 166 |
+
continue
|
| 167 |
+
elif not pending.startswith(piece):
|
| 168 |
+
continue
|
| 169 |
+
expansions.append((score + float(logprobs[row, token]), suffix + (token,), text + piece))
|
| 170 |
+
continue
|
| 171 |
+
done = len(text) - len(required)
|
| 172 |
+
mask = vocabulary.length_mask(max_chars - done)
|
| 173 |
+
if constraint:
|
| 174 |
+
mask = mask & vocabulary.constraint_mask(constraint, readings, done)
|
| 175 |
+
allowed = int(mask.sum())
|
| 176 |
+
if not allowed:
|
| 177 |
+
continue
|
| 178 |
+
values, tokens = logprobs[row].masked_fill(~mask, NEG).topk(min(beam, allowed))
|
| 179 |
+
for value, token in zip(values.tolist(), tokens.tolist()):
|
| 180 |
+
expansions.append((score + value, suffix + (token,), text + vocabulary.texts[token]))
|
| 181 |
+
expansions.sort(key=lambda x: (-x[0], x[2]))
|
| 182 |
+
states = []
|
| 183 |
+
for score, suffix, text in expansions[:beam]:
|
| 184 |
+
if len(text) < len(required):
|
| 185 |
+
states.append((suffix, text, score))
|
| 186 |
+
continue
|
| 187 |
+
new = text[len(required):]
|
| 188 |
+
ok = constraint.candidate_length_ok(len(new)) if constraint else MIN_CHARS <= len(new) <= MAX_CHARS
|
| 189 |
+
if ok and score > candidates.get(new, NEG):
|
| 190 |
+
candidates[new] = score
|
| 191 |
+
if len(new) < max_chars:
|
| 192 |
+
states.append((suffix, text, score))
|
| 193 |
+
return select(candidates, top)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class VimeLM:
|
| 197 |
+
"""vimeml-tiny-zh models: each turn is its own BOS ... EOS sequence, as in training."""
|
| 198 |
+
|
| 199 |
+
def __init__(self, model, processor, device, special):
|
| 200 |
+
self.model, self.processor, self.device, self.special = model, processor, device, special
|
| 201 |
+
self.context_length = model.config.context_length
|
| 202 |
+
texts = []
|
| 203 |
+
for i in range(processor.get_piece_size()):
|
| 204 |
+
plain = not (processor.is_control(i) or processor.is_unknown(i) or processor.is_byte(i))
|
| 205 |
+
texts.append(processor.id_to_piece(i) if plain else None)
|
| 206 |
+
self.vocabulary = Vocabulary(texts, "cpu")
|
| 207 |
+
|
| 208 |
+
def context(self, turns, prefix):
|
| 209 |
+
bos, eos = self.special["bos"], self.special["eos"]
|
| 210 |
+
limit = self.context_length - RESERVE
|
| 211 |
+
tail = self.processor.encode(prefix) if prefix else []
|
| 212 |
+
ids = [bos, *tail[-(limit - 1):]] if tail else [bos]
|
| 213 |
+
for turn in reversed(turns):
|
| 214 |
+
if not turn:
|
| 215 |
+
continue
|
| 216 |
+
piece = [bos, *self.processor.encode(turn), eos]
|
| 217 |
+
if len(ids) + len(piece) > limit:
|
| 218 |
+
break
|
| 219 |
+
ids = piece + ids
|
| 220 |
+
return ids
|
| 221 |
+
|
| 222 |
+
@torch.inference_mode()
|
| 223 |
+
def logprobs(self, sequences):
|
| 224 |
+
inputs = torch.tensor(sequences, dtype=torch.long, device=self.device)
|
| 225 |
+
return self.model(inputs)[:, -1].float().log_softmax(-1).cpu()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# Track B ------------------------------------------------------------------------------------
|
| 229 |
+
|
| 230 |
+
def keystrokes(message, pinyin):
|
| 231 |
+
"""Per-character full-pinyin key count: letters of the reading for Chinese, 1 otherwise."""
|
| 232 |
+
costs = [1] * len(message)
|
| 233 |
+
for run in HAN_RUN.finditer(message):
|
| 234 |
+
readings = pinyin(run.group())
|
| 235 |
+
if len(readings) != len(run.group()):
|
| 236 |
+
raise ValueError("Reading count differs from character count")
|
| 237 |
+
for k, reading in enumerate(readings):
|
| 238 |
+
costs[run.start() + k] = len(reading)
|
| 239 |
+
return costs
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def boundaries(message, cut):
|
| 243 |
+
out, position = [], 0
|
| 244 |
+
for word in cut(message):
|
| 245 |
+
position += len(word)
|
| 246 |
+
out.append(position)
|
| 247 |
+
if position != len(message):
|
| 248 |
+
raise ValueError("Segmentation does not cover the message")
|
| 249 |
+
return out
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def simulate(message, costs, ends, predictions, threshold, show=SHOW):
|
| 253 |
+
"""Type `message`; after every commit (not before the first one) up to `show` predictions
|
| 254 |
+
with score >= threshold are offered, and the longest one that is a prefix of the rest is
|
| 255 |
+
taken (one key). Otherwise the next segment (to the next word end) is typed in full pinyin.
|
| 256 |
+
predictions(p) -> [(text, score)]."""
|
| 257 |
+
position = keys = shows = clicks = 0
|
| 258 |
+
while position < len(message):
|
| 259 |
+
offered = []
|
| 260 |
+
if position:
|
| 261 |
+
offered = [text for text, score in predictions(position)[:show] if score >= threshold]
|
| 262 |
+
shows += bool(offered)
|
| 263 |
+
hits = [text for text in offered if message.startswith(text, position)]
|
| 264 |
+
if hits:
|
| 265 |
+
position += len(max(hits, key=len))
|
| 266 |
+
keys += 1
|
| 267 |
+
clicks += 1
|
| 268 |
+
continue
|
| 269 |
+
end = next(e for e in ends if e > position)
|
| 270 |
+
keys += sum(costs[position:end])
|
| 271 |
+
position = end
|
| 272 |
+
return {"keys": keys, "baseline_keys": sum(costs), "shows": shows, "clicks": clicks}
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# Metrics ------------------------------------------------------------------------------------
|
| 276 |
+
|
| 277 |
+
def rank_of_hit(candidates, continuation):
|
| 278 |
+
for rank, (text, _) in enumerate(candidates, 1):
|
| 279 |
+
if continuation.startswith(text):
|
| 280 |
+
return rank, len(text)
|
| 281 |
+
return None, 0
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def rank_exact(candidates, target):
|
| 285 |
+
for rank, (text, _) in enumerate(candidates, 1):
|
| 286 |
+
if text == target:
|
| 287 |
+
return rank
|
| 288 |
+
return None
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def rates(rows, key, ks=(1, 3, 5)):
|
| 292 |
+
"""rows: dicts with 'source' and key -> rank or None. Micro and macro over sources."""
|
| 293 |
+
sources = sorted({r["source"] for r in rows})
|
| 294 |
+
out = {}
|
| 295 |
+
for k in ks:
|
| 296 |
+
per = {s: sum(1 for r in rows if r["source"] == s and r[key] and r[key] <= k) /
|
| 297 |
+
max(1, sum(1 for r in rows if r["source"] == s)) for s in sources}
|
| 298 |
+
hits = sum(1 for r in rows if r[key] and r[key] <= k)
|
| 299 |
+
out[f"top{k}"] = {"micro": hits / max(1, len(rows)), "hits": hits, "items": len(rows),
|
| 300 |
+
"macro": sum(per.values()) / max(1, len(per)), "by_source": per}
|
| 301 |
+
return out
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def coverage_curve(rows, points=(0.2, 0.5)):
|
| 305 |
+
"""Track D: Top-1 hit rate among the most confident fraction of track A items."""
|
| 306 |
+
ordered = sorted(rows, key=lambda r: (-(r["confidence"] if r["confidence"] is not None else NEG), r["id"]))
|
| 307 |
+
out = {}
|
| 308 |
+
for c in points:
|
| 309 |
+
n = max(1, round(c * len(ordered)))
|
| 310 |
+
out[f"{int(c * 100)}%"] = {"items": n, "top1": sum(1 for r in ordered[:n] if r["rank"] == 1) / n}
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def finite(x):
|
| 315 |
+
return x if x is not None and math.isfinite(x) else None
|
source/src/vimeml/benchmarks/readings.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Two-dictionary orthographic kana checks for evaluation preparation only."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from importlib.metadata import version
|
| 5 |
+
|
| 6 |
+
KANA = re.compile(r"[ァ-ヺー。、!?「」『』()・:,,.!?]+")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def katakana(text):
|
| 10 |
+
return "".join(chr(ord(c) + 0x60) if "ぁ" <= c <= "ゖ" else c for c in text)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class DualReading:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
import fugashi
|
| 16 |
+
from sudachipy import Dictionary, SplitMode
|
| 17 |
+
|
| 18 |
+
self.mecab = fugashi.Tagger()
|
| 19 |
+
self.sudachi = Dictionary().create()
|
| 20 |
+
self.mode = SplitMode.C
|
| 21 |
+
self.versions = {
|
| 22 |
+
n: version(n) for n in ("fugashi", "unidic-lite", "sudachipy", "sudachidict-core")
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
def analyse(self, text, start=0):
|
| 26 |
+
"""Read a suffix in its sentence, rejecting boundaries inside words."""
|
| 27 |
+
left, right, unknown = [], [], []
|
| 28 |
+
offset = 0
|
| 29 |
+
for word in self.mecab(text):
|
| 30 |
+
surface = word.surface
|
| 31 |
+
end = offset + len(surface)
|
| 32 |
+
if offset < start < end:
|
| 33 |
+
unknown.append("boundary_inside_unidic_word")
|
| 34 |
+
if offset < start:
|
| 35 |
+
offset = end
|
| 36 |
+
continue
|
| 37 |
+
offset = end
|
| 38 |
+
if word.is_unk:
|
| 39 |
+
unknown.append(surface)
|
| 40 |
+
if KANA.fullmatch(katakana(surface)):
|
| 41 |
+
left.append(katakana(surface))
|
| 42 |
+
elif word.feature.kana:
|
| 43 |
+
left.append(word.feature.kana)
|
| 44 |
+
else:
|
| 45 |
+
left.append(surface)
|
| 46 |
+
unknown.append(surface)
|
| 47 |
+
for word in self.sudachi.tokenize(text, self.mode):
|
| 48 |
+
surface = word.surface()
|
| 49 |
+
if word.begin() < start < word.end():
|
| 50 |
+
unknown.append("boundary_inside_sudachi_word")
|
| 51 |
+
if word.begin() < start:
|
| 52 |
+
continue
|
| 53 |
+
if KANA.fullmatch(katakana(surface)):
|
| 54 |
+
right.append(katakana(surface))
|
| 55 |
+
else:
|
| 56 |
+
right.append(word.reading_form())
|
| 57 |
+
if word.is_oov():
|
| 58 |
+
unknown.append(surface)
|
| 59 |
+
a, b = "".join(left), "".join(right)
|
| 60 |
+
return {
|
| 61 |
+
"unidic": a,
|
| 62 |
+
"sudachi": b,
|
| 63 |
+
"agreement": a == b,
|
| 64 |
+
"unknown": sorted(set(unknown)),
|
| 65 |
+
"kana_only": bool(KANA.fullmatch(a) and KANA.fullmatch(b)),
|
| 66 |
+
}
|
source/src/vimeml/benchmarks/standard_ime.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned IME benchmark protocol; labels and blind access are explicit."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from vimeml.benchmarks.expanded_ime import FORMAT as LEGACY_FORMAT, load_expanded_export
|
| 6 |
+
|
| 7 |
+
FORMAT = "vimeml_standard_ime_candidates_v1"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def reviewed_and_frozen(manifest):
|
| 11 |
+
"""AI expert references are usable, with their quality class kept explicit."""
|
| 12 |
+
return bool(manifest.get("labels_formal_gold") or (
|
| 13 |
+
manifest.get("labels_frozen") and manifest.get("review_completed") and
|
| 14 |
+
manifest.get("label_quality") in {"ai_expert_reviewed", "human_native_reviewed"}))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def read(path):
|
| 18 |
+
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_standard_export(directory):
|
| 22 |
+
directory = Path(directory)
|
| 23 |
+
manifest = read(directory / "manifest.json")
|
| 24 |
+
if manifest.get("format") != FORMAT or manifest.get("status") != "complete":
|
| 25 |
+
raise ValueError("Expected a completed standard IME candidate import.")
|
| 26 |
+
# Reuse the existing real-candidate identity/version/rank checks.
|
| 27 |
+
adapted = {**manifest, "format": LEGACY_FORMAT}
|
| 28 |
+
_, provenance, rows = load_expanded_export(directory, adapted)
|
| 29 |
+
originals = read(directory / "evaluation_items.json")
|
| 30 |
+
by_id = {f"ajimee:{r['index']}": r for r in originals}
|
| 31 |
+
for row in rows:
|
| 32 |
+
row["source"] = by_id[row["id"]]["provenance"]["source"]
|
| 33 |
+
row["provenance"] = by_id[row["id"]]["provenance"]
|
| 34 |
+
return manifest, provenance, rows
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def allow_evaluation(manifest, *, allow_draft=False, plan=None, checkpoint=None):
|
| 38 |
+
role = manifest["split"]
|
| 39 |
+
if role not in {"development", "blind", "regression"}:
|
| 40 |
+
raise ValueError("Unknown benchmark role.")
|
| 41 |
+
if role == "regression":
|
| 42 |
+
return # Historical draft references remain a separately named diagnostic.
|
| 43 |
+
if not reviewed_and_frozen(manifest) and not (role == "development" and allow_draft):
|
| 44 |
+
raise ValueError("External labels need review and freezing; only development permits explicit draft diagnostics.")
|
| 45 |
+
if role == "blind":
|
| 46 |
+
if plan is None or checkpoint is None:
|
| 47 |
+
raise ValueError("Blind evaluation requires a precommitted model plan and checkpoint.")
|
| 48 |
+
if plan.get("benchmark_release_id") != manifest["release_id"]:
|
| 49 |
+
raise ValueError("Blind plan belongs to a different benchmark release.")
|
| 50 |
+
identity = str(Path(checkpoint).resolve())
|
| 51 |
+
matching = [m for m in plan["models"] if m["checkpoint"] == identity]
|
| 52 |
+
if (len(matching) != 1 or Path(identity).stat().st_size != matching[0]["bytes"] or
|
| 53 |
+
Path(identity).stat().st_mtime_ns != matching[0]["mtime_ns"]):
|
| 54 |
+
raise ValueError("Checkpoint is not one of the precommitted model snapshots.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def source_metrics(rows, metric_function):
|
| 58 |
+
groups = {source: [r for r in rows if r["source"] == source] for source in sorted({r["source"] for r in rows})}
|
| 59 |
+
metrics = {source: metric_function(items, "lm_context_sum") for source, items in groups.items()}
|
| 60 |
+
result = {"by_source": metrics}
|
| 61 |
+
if all(source in metrics for source in ("wrime", "jmultiwoz")):
|
| 62 |
+
independent = [r for r in rows if r["source"] in ("wrime", "jmultiwoz")]
|
| 63 |
+
result["independent_micro"] = metric_function(independent, "lm_context_sum")
|
| 64 |
+
result["independent_equal_source_macro_top1"] = sum(metrics[s]["top1_accuracy"] for s in ("wrime", "jmultiwoz")) / 2
|
| 65 |
+
if len(independent) != len(rows):
|
| 66 |
+
result["all_source_micro_secondary"] = metric_function(rows, "lm_context_sum")
|
| 67 |
+
else:
|
| 68 |
+
result["role"] = "legacy_regression_diagnostic"
|
| 69 |
+
return result
|
source/src/vimeml/benchmarks/statistics.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cluster-aware paired statistics for frozen IME tracks.
|
| 2 |
+
|
| 3 |
+
Items written by the same author, or built from the same sentence template, tend to
|
| 4 |
+
flip together, so the effective sample is smaller than the item count and per-item
|
| 5 |
+
McNemar p-values are optimistic. Clusters join items that share an author/document
|
| 6 |
+
group (the homophone group on the challenge track) or whose NFKC targets (digits masked) have character-trigram Jaccard >= TEMPLATE.
|
| 7 |
+
Paired tests then resample or sign-flip whole clusters.
|
| 8 |
+
"""
|
| 9 |
+
import random
|
| 10 |
+
import re
|
| 11 |
+
import unicodedata
|
| 12 |
+
from math import comb
|
| 13 |
+
|
| 14 |
+
TEMPLATE = 0.5
|
| 15 |
+
_DIGITS = re.compile(r'[0-90-9]+')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def exact_mcnemar(gain, loss):
|
| 19 |
+
n, k = gain + loss, min(gain, loss)
|
| 20 |
+
return min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / 2 ** n) if n else 1.0
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _trigrams(text):
|
| 24 |
+
text = _DIGITS.sub('0', unicodedata.normalize('NFKC', text))
|
| 25 |
+
return {text[i:i + 3] for i in range(max(1, len(text) - 2))}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _group(row):
|
| 29 |
+
p = row.get('provenance') or {}
|
| 30 |
+
if str(p.get('group_id', '')).startswith('homophone:'):
|
| 31 |
+
return p['group_id'] # paired items of one homophone group
|
| 32 |
+
for key in ('author_id', 'source_doc_id'):
|
| 33 |
+
if p.get(key) is not None:
|
| 34 |
+
return f"{row.get('source', '')}:{key}:{p[key]}"
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def clusters(rows, template=TEMPLATE):
|
| 39 |
+
"""Cluster label per row: union of shared author/document group and template similarity."""
|
| 40 |
+
parent = list(range(len(rows)))
|
| 41 |
+
|
| 42 |
+
def find(i):
|
| 43 |
+
while parent[i] != i:
|
| 44 |
+
parent[i] = parent[parent[i]]
|
| 45 |
+
i = parent[i]
|
| 46 |
+
return i
|
| 47 |
+
|
| 48 |
+
def union(i, j):
|
| 49 |
+
parent[find(i)] = find(j)
|
| 50 |
+
|
| 51 |
+
first = {}
|
| 52 |
+
for i, row in enumerate(rows):
|
| 53 |
+
group = _group(row)
|
| 54 |
+
if group is not None:
|
| 55 |
+
union(i, first.setdefault(group, i))
|
| 56 |
+
if template is not None:
|
| 57 |
+
grams = [_trigrams(r['answers'][0]) for r in rows]
|
| 58 |
+
for i in range(len(rows)):
|
| 59 |
+
for j in range(i):
|
| 60 |
+
if len(grams[i] & grams[j]) >= template * len(grams[i] | grams[j]):
|
| 61 |
+
union(i, j)
|
| 62 |
+
return [find(i) for i in range(len(rows))]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _cluster_sums(diff, labels):
|
| 66 |
+
sums = {}
|
| 67 |
+
for d, c in zip(diff, labels):
|
| 68 |
+
sums[c] = sums.get(c, 0) + d
|
| 69 |
+
return list(sums.values())
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def sign_flip_p(diff, labels, draws=20000, seed=0):
|
| 73 |
+
"""Two-sided paired permutation p-value flipping the sign of whole clusters."""
|
| 74 |
+
sums = [s for s in _cluster_sums(diff, labels) if s]
|
| 75 |
+
observed = abs(sum(sums))
|
| 76 |
+
if not sums:
|
| 77 |
+
return 1.0
|
| 78 |
+
if len(sums) <= 20:
|
| 79 |
+
hits = sum(abs(sum(s if mask >> i & 1 else -s for i, s in enumerate(sums))) >= observed
|
| 80 |
+
for mask in range(2 ** len(sums)))
|
| 81 |
+
return hits / 2 ** len(sums)
|
| 82 |
+
rng = random.Random(seed)
|
| 83 |
+
hits = sum(abs(sum(s if rng.random() < .5 else -s for s in sums)) >= observed for _ in range(draws))
|
| 84 |
+
return (hits + 1) / (draws + 1)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def bootstrap_interval(diff, labels, draws=10000, seed=0, level=.95):
|
| 88 |
+
"""Percentile interval of the net paired difference, resampling clusters with replacement."""
|
| 89 |
+
sums = _cluster_sums(diff, labels)
|
| 90 |
+
rng = random.Random(seed)
|
| 91 |
+
totals = sorted(sum(rng.choice(sums) for _ in sums) for _ in range(draws))
|
| 92 |
+
tail = (1 - level) / 2
|
| 93 |
+
return totals[int(tail * draws)], totals[min(draws - 1, int((1 - tail) * draws))]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _cluster_sizes(labels):
|
| 97 |
+
sizes = {}
|
| 98 |
+
for c in labels:
|
| 99 |
+
sizes[c] = sizes.get(c, 0) + 1
|
| 100 |
+
return sizes
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def design_effect(diff, labels):
|
| 104 |
+
"""Variance of the paired total under clustering relative to independent items."""
|
| 105 |
+
mean = sum(diff) / len(diff)
|
| 106 |
+
iid = sum((d - mean) ** 2 for d in diff)
|
| 107 |
+
sums, sizes = {}, _cluster_sizes(labels)
|
| 108 |
+
for d, c in zip(diff, labels):
|
| 109 |
+
sums[c] = sums.get(c, 0) + d
|
| 110 |
+
clustered = sum((s - mean * sizes[c]) ** 2 for c, s in sums.items())
|
| 111 |
+
return clustered / iid if iid else 1.0
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def paired(before, after, labels, seed=0):
|
| 115 |
+
"""Paired comparison of two boolean outcome lists on the same frozen cases."""
|
| 116 |
+
gain = sum(b and not a for a, b in zip(before, after))
|
| 117 |
+
loss = sum(a and not b for a, b in zip(before, after))
|
| 118 |
+
diff = [int(b) - int(a) for a, b in zip(before, after)]
|
| 119 |
+
low, high = bootstrap_interval(diff, labels, seed=seed)
|
| 120 |
+
return {'gain': gain, 'loss': loss, 'net': gain - loss, 'exact_mcnemar_p': exact_mcnemar(gain, loss),
|
| 121 |
+
'clusters': len(set(labels)), 'discordant_clusters': sum(1 for s in _cluster_sums(diff, labels) if s),
|
| 122 |
+
'cluster_sign_flip_p': sign_flip_p(diff, labels, seed=seed),
|
| 123 |
+
'cluster_bootstrap_95': [low, high], 'design_effect': design_effect(diff, labels)}
|
source/src/vimeml/benchmarks/zh13_judge.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Judge the vimeml-tiny-zh-v1 arms by the rules fixed in docs/zh-CN/training-zh-v1-plan.md.
|
| 2 |
+
|
| 3 |
+
Inputs per arm, under RUNS/<arm>/:
|
| 4 |
+
full.jsonl, full.meta.json score_zh13_lm.py output on the full-pinyin track (required)
|
| 5 |
+
abbrev.jsonl, abbrev.meta.json the same on the abbreviated track (optional, descriptive)
|
| 6 |
+
and the arm's training directory (output_dir in configs/train-zh13-<arm>.toml, or MODELS/<arm>)
|
| 7 |
+
holding final.pt, summary.json and milestones.json.
|
| 8 |
+
|
| 9 |
+
Checks before any statistic: every arm is present; each scores file matches the SHA256 in its meta;
|
| 10 |
+
the meta names the arm, the development split and the right track; it was scored from that arm's
|
| 11 |
+
final.pt (SHA256 compared with the file on disk); training finished with status "complete" and all
|
| 12 |
+
20 milestones; arms of one vocabulary share one tokenizer and the two vocabularies differ.
|
| 13 |
+
|
| 14 |
+
Each scores file is ranked with score_standard_ime_zh.py score (the same code as every other zh
|
| 15 |
+
result), into OUT/scores/<arm>-<track>/; the Rime pool order is scored too, as the baseline.
|
| 16 |
+
|
| 17 |
+
Decision (full track, exact Top-1, development, 1,456 items):
|
| 18 |
+
noise band = the three 12k-fresh seeds: mean, range (max - min), SD (n - 1)
|
| 19 |
+
contrasts = the five in CONTRASTS; one family, Holm step-down on exact McNemar p, alpha 0.05
|
| 20 |
+
effective = |Top-1 difference| > seed range AND Holm-adjusted p < 0.05
|
| 21 |
+
Everything else (ep5 contrasts, BPC, memorization gap, abbreviated track, Top-3, pool-conditional
|
| 22 |
+
Top-1, sources, learning curves) is description and never enters the decision.
|
| 23 |
+
"""
|
| 24 |
+
import hashlib
|
| 25 |
+
import json
|
| 26 |
+
import statistics
|
| 27 |
+
import subprocess
|
| 28 |
+
import sys
|
| 29 |
+
import tomllib
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
from vimeml.benchmarks.statistics import paired
|
| 33 |
+
|
| 34 |
+
VERSION = "ime-standard-zh-v1-r1"
|
| 35 |
+
ITEMS = 1456
|
| 36 |
+
RIME_BASELINE_TOP1 = 1001
|
| 37 |
+
ALPHA = 0.05
|
| 38 |
+
MILESTONES = 20
|
| 39 |
+
ARMS = { # arm: (vocabulary, web pool, web epochs) as in the plan's arm table
|
| 40 |
+
"12k-fresh-s1": (12288, "P1", 1), "12k-fresh-s2": (12288, "P1", 1), "12k-fresh-s3": (12288, "P1", 1),
|
| 41 |
+
"12k-ep5": (12288, "P5", 5), "12k-ep20": (12288, "P20", 20),
|
| 42 |
+
"8k-fresh": (8192, "P1", 1), "8k-ep5": (8192, "P5", 5), "8k-ep20": (8192, "P20", 20),
|
| 43 |
+
}
|
| 44 |
+
SEEDS = ("12k-fresh-s1", "12k-fresh-s2", "12k-fresh-s3")
|
| 45 |
+
CONTRASTS = ( # (name, A, B, question); difference is B - A
|
| 46 |
+
("data-12k", "12k-fresh-s1", "12k-ep20", "12K 下新数据与 20 轮"),
|
| 47 |
+
("data-8k", "8k-fresh", "8k-ep20", "8K 下新数据与 20 轮"),
|
| 48 |
+
("vocab-fresh", "8k-fresh", "12k-fresh-s1", "新数据下的词表"),
|
| 49 |
+
("vocab-ep5", "8k-ep5", "12k-ep5", "5 轮下的词表"),
|
| 50 |
+
("vocab-ep20", "8k-ep20", "12k-ep20", "20 轮下的词表"),
|
| 51 |
+
)
|
| 52 |
+
DESCRIPTIVE = ( # dose-response, reported only
|
| 53 |
+
("12k-fresh-s1", "12k-ep5"), ("12k-ep5", "12k-ep20"), ("8k-fresh", "8k-ep5"), ("8k-ep5", "8k-ep20"),
|
| 54 |
+
)
|
| 55 |
+
VALIDATIONS = ("web", "chat", "probe")
|
| 56 |
+
SCORER = Path(__file__).resolve().parents[3] / "scripts" / "benchmarks" / "score_standard_ime_zh.py"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def sha256(path):
|
| 60 |
+
digest = hashlib.sha256()
|
| 61 |
+
with open(path, "rb") as stream:
|
| 62 |
+
while block := stream.read(1 << 24):
|
| 63 |
+
digest.update(block)
|
| 64 |
+
return digest.hexdigest()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read_json(path):
|
| 68 |
+
return json.loads(Path(path).read_text(encoding="utf-8"))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read_jsonl(path):
|
| 72 |
+
with open(path, encoding="utf-8") as stream:
|
| 73 |
+
return [json.loads(line) for line in stream if line.strip()]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def holm(pvalues):
|
| 77 |
+
"""Holm step-down adjusted p-values, same order as the input."""
|
| 78 |
+
m = len(pvalues)
|
| 79 |
+
order = sorted(range(m), key=lambda i: pvalues[i])
|
| 80 |
+
adjusted, running = [0.0] * m, 0.0
|
| 81 |
+
for rank, i in enumerate(order):
|
| 82 |
+
running = max(running, min(1.0, (m - rank) * pvalues[i]))
|
| 83 |
+
adjusted[i] = running
|
| 84 |
+
return adjusted
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def spread(values):
|
| 88 |
+
values = [v for v in values if v is not None]
|
| 89 |
+
if len(values) < 2:
|
| 90 |
+
return None
|
| 91 |
+
return {"values": values, "mean": statistics.mean(values), "range": max(values) - min(values),
|
| 92 |
+
"sd": statistics.stdev(values)}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def model_dir(root, arm, models):
|
| 96 |
+
if models:
|
| 97 |
+
return Path(models) / arm
|
| 98 |
+
config = tomllib.loads((root / "configs" / f"train-zh13-{arm}.toml").read_text(encoding="utf-8"))
|
| 99 |
+
if config["arm"] != arm or config["model"]["vocab_size"] != ARMS[arm][0]:
|
| 100 |
+
raise ValueError(f"configs/train-zh13-{arm}.toml does not describe {arm}")
|
| 101 |
+
return root / config["output_dir"]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def check_arm(arm, runs, directory, track, problems):
|
| 105 |
+
"""Return (scores path, meta) after checking the scores against the meta and final.pt."""
|
| 106 |
+
scores, meta_path = runs / arm / f"{track}.jsonl", runs / arm / f"{track}.meta.json"
|
| 107 |
+
if not scores.exists() or not meta_path.exists():
|
| 108 |
+
problems.append(f"{arm}: {track}.jsonl or {track}.meta.json is missing")
|
| 109 |
+
return None, None
|
| 110 |
+
meta = read_json(meta_path)
|
| 111 |
+
expected = {"arm": arm, "version": VERSION, "track": track, "split": "development"}
|
| 112 |
+
for key, value in expected.items():
|
| 113 |
+
if meta.get(key) != value:
|
| 114 |
+
problems.append(f"{arm}/{track}: meta {key} is {meta.get(key)!r}, expected {value!r}")
|
| 115 |
+
if sha256(scores) != meta.get("scores_sha256"):
|
| 116 |
+
problems.append(f"{arm}/{track}: scores file differs from scores_sha256 in its meta")
|
| 117 |
+
if Path(str(meta.get("checkpoint", "")).replace("\\", "/")).name != "final.pt":
|
| 118 |
+
problems.append(f"{arm}/{track}: scored from {meta.get('checkpoint')}, not final.pt")
|
| 119 |
+
final = directory / "final.pt"
|
| 120 |
+
if not final.exists():
|
| 121 |
+
problems.append(f"{arm}: {final} is missing")
|
| 122 |
+
elif sha256(final) != meta.get("checkpoint_sha256"):
|
| 123 |
+
problems.append(f"{arm}/{track}: checkpoint_sha256 differs from {final}")
|
| 124 |
+
return scores, meta
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def training_record(arm, directory, problems, smoke):
|
| 128 |
+
summary_path, milestones_path = directory / "summary.json", directory / "milestones.json"
|
| 129 |
+
if not summary_path.exists() or not milestones_path.exists():
|
| 130 |
+
problems.append(f"{arm}: summary.json or milestones.json is missing in {directory}")
|
| 131 |
+
return None
|
| 132 |
+
summary, milestones = read_json(summary_path), read_json(milestones_path)
|
| 133 |
+
allowed = ("complete", "smoke_complete") if smoke else ("complete",)
|
| 134 |
+
if summary.get("status") not in allowed:
|
| 135 |
+
problems.append(f"{arm}: training status is {summary.get('status')!r}")
|
| 136 |
+
if len(milestones) != MILESTONES or [m["milestone"] for m in milestones] != list(range(1, MILESTONES + 1)):
|
| 137 |
+
problems.append(f"{arm}: milestones.json does not hold milestones 1-{MILESTONES}")
|
| 138 |
+
elif milestones[-1]["step"] != summary.get("step"):
|
| 139 |
+
problems.append(f"{arm}: milestone {MILESTONES} is at step {milestones[-1]['step']}, final at {summary.get('step')}")
|
| 140 |
+
return {"status": summary.get("status"), "step": summary.get("step"), "milestones": milestones}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def run_scorer(frozen, out, track, scores=None, name=None):
|
| 144 |
+
command = [sys.executable, "-I", "-X", "utf8", str(SCORER), "score", str(frozen), str(out), "--track", track]
|
| 145 |
+
if scores:
|
| 146 |
+
command += ["--scores", str(scores)]
|
| 147 |
+
if name:
|
| 148 |
+
command += ["--name", name]
|
| 149 |
+
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8")
|
| 150 |
+
if done.returncode:
|
| 151 |
+
raise RuntimeError(f"score_standard_ime_zh.py failed for {out.name}:\n{done.stderr}")
|
| 152 |
+
return read_json(out / "summary.json"), {r["id"]: r for r in read_jsonl(out / "items.jsonl")}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def hits(rows, ids, k=1):
|
| 156 |
+
return [rows[i]["rank"] is not None and rows[i]["rank"] <= k for i in ids]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def compare(rows_a, rows_b, ids):
|
| 160 |
+
labels = [rows_a[i]["dialogue"] for i in ids] # one item per dialogue in this benchmark
|
| 161 |
+
return {f"top{k}": paired(hits(rows_a, ids, k), hits(rows_b, ids, k), labels) for k in (1, 3)}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def winner(entry):
|
| 165 |
+
if not entry["effective"]:
|
| 166 |
+
return None
|
| 167 |
+
return entry["b"] if entry["difference"] > 0 else entry["a"]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def decide(contrasts):
|
| 171 |
+
"""Apply the plan's "结论如何使用" rules.
|
| 172 |
+
|
| 173 |
+
Data: no effective contrast -> fresh; effective ones agree -> that; 12K and 8K effective in
|
| 174 |
+
opposite directions -> the 12K result. Vocabulary: none effective -> 12K; agree -> that;
|
| 175 |
+
disagree -> the fresh-data contrast if effective, otherwise 12K.
|
| 176 |
+
"""
|
| 177 |
+
by_name = {c["name"]: c for c in contrasts}
|
| 178 |
+
data_votes = {}
|
| 179 |
+
for name in ("data-12k", "data-8k"):
|
| 180 |
+
w = winner(by_name[name])
|
| 181 |
+
if w is not None:
|
| 182 |
+
data_votes[name] = "repeat-20" if w.endswith("ep20") else "fresh"
|
| 183 |
+
if not data_votes:
|
| 184 |
+
data = {"choice": "fresh", "basis": "两个数据对比都不有效,按计划默认新数据"}
|
| 185 |
+
elif len(set(data_votes.values())) == 1:
|
| 186 |
+
data = {"choice": next(iter(data_votes.values())), "basis": f"有效对比:{', '.join(sorted(data_votes))}"}
|
| 187 |
+
else:
|
| 188 |
+
data = {"choice": data_votes["data-12k"], "basis": "12K 与 8K 的数据对比都有效但方向相反,按计划以 12K 下的结果为准"}
|
| 189 |
+
vocab_votes = {}
|
| 190 |
+
for name in ("vocab-fresh", "vocab-ep5", "vocab-ep20"):
|
| 191 |
+
w = winner(by_name[name])
|
| 192 |
+
if w is not None:
|
| 193 |
+
vocab_votes[name] = "12k" if w.startswith("12k") else "8k"
|
| 194 |
+
if not vocab_votes:
|
| 195 |
+
vocab = {"choice": "12k", "basis": "三个词表对比都不有效,按计划默认 12K"}
|
| 196 |
+
elif len(set(vocab_votes.values())) == 1:
|
| 197 |
+
vocab = {"choice": next(iter(vocab_votes.values())), "basis": f"有效对比:{', '.join(sorted(vocab_votes))}"}
|
| 198 |
+
elif "vocab-fresh" in vocab_votes:
|
| 199 |
+
vocab = {"choice": vocab_votes["vocab-fresh"], "basis": "有效对比方向不一致,按计划以新数据下的结果为准"}
|
| 200 |
+
else:
|
| 201 |
+
vocab = {"choice": "12k", "basis": "5 轮与 20 轮下的词表结果相反、新数据下不有效,按计划默认 12K"}
|
| 202 |
+
return {"data": data, "vocabulary": vocab}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def bpc(milestone, name):
|
| 206 |
+
return (milestone.get(name) or {}).get("bpc")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def judge(runs, frozen, out, models=None, smoke=False, root=None):
|
| 210 |
+
root = Path(root or Path(__file__).resolve().parents[3])
|
| 211 |
+
runs, frozen, out = Path(runs), Path(frozen), Path(out)
|
| 212 |
+
if out.exists():
|
| 213 |
+
raise SystemExit(f"output exists, choose a new directory: {out}")
|
| 214 |
+
if read_json(frozen / "manifest.json")["version"] != VERSION:
|
| 215 |
+
raise SystemExit(f"{frozen} is not {VERSION}")
|
| 216 |
+
problems, arms = [], {}
|
| 217 |
+
for arm in ARMS:
|
| 218 |
+
directory = model_dir(root, arm, models)
|
| 219 |
+
full_scores, full_meta = check_arm(arm, runs, directory, "full", problems)
|
| 220 |
+
abbrev_scores, abbrev_meta = (None, None)
|
| 221 |
+
if (runs / arm / "abbrev.jsonl").exists():
|
| 222 |
+
abbrev_scores, abbrev_meta = check_arm(arm, runs, directory, "abbrev", problems)
|
| 223 |
+
arms[arm] = {"directory": directory, "full": full_scores, "full_meta": full_meta,
|
| 224 |
+
"abbrev": abbrev_scores, "abbrev_meta": abbrev_meta,
|
| 225 |
+
"training": training_record(arm, directory, problems, smoke)}
|
| 226 |
+
tokenizers = {}
|
| 227 |
+
for arm, record in arms.items():
|
| 228 |
+
if record["full_meta"]:
|
| 229 |
+
tokenizers.setdefault(ARMS[arm][0], set()).add(record["full_meta"].get("tokenizer_model_sha256"))
|
| 230 |
+
if any(len(v) != 1 for v in tokenizers.values()) or len(set().union(*tokenizers.values())) != len(tokenizers):
|
| 231 |
+
problems.append(f"tokenizer SHA256 per vocabulary is not one-to-one: {tokenizers}")
|
| 232 |
+
abbrev_present = [a for a in ARMS if arms[a]["abbrev"]]
|
| 233 |
+
if abbrev_present and len(abbrev_present) != len(ARMS):
|
| 234 |
+
problems.append(f"abbreviated track scored for only {len(abbrev_present)} of {len(ARMS)} arms")
|
| 235 |
+
if problems:
|
| 236 |
+
raise SystemExit("judgement refused:\n " + "\n ".join(problems))
|
| 237 |
+
|
| 238 |
+
out.mkdir(parents=True)
|
| 239 |
+
(out / "scores").mkdir()
|
| 240 |
+
tracks = ("full", "abbrev") if abbrev_present else ("full",)
|
| 241 |
+
ranked = {}
|
| 242 |
+
for track in tracks:
|
| 243 |
+
ranked[("rime", track)] = run_scorer(frozen, out / "scores" / f"rime-{track}", track, name="rime-pool-order")
|
| 244 |
+
for arm in ARMS:
|
| 245 |
+
ranked[(arm, track)] = run_scorer(frozen, out / "scores" / f"{arm}-{track}", track, arms[arm][track], name=arm)
|
| 246 |
+
ids = sorted(ranked[("rime", "full")][1])
|
| 247 |
+
for (arm, track), (summary, rows) in ranked.items():
|
| 248 |
+
if track == "full" and sorted(rows) != ids:
|
| 249 |
+
raise SystemExit(f"{arm} covers different full-track items")
|
| 250 |
+
if summary["fallbacks"]:
|
| 251 |
+
raise SystemExit(f"{arm}/{track} has {summary['fallbacks']} items without scores")
|
| 252 |
+
if len(ids) != ITEMS:
|
| 253 |
+
raise SystemExit(f"expected {ITEMS} development items, found {len(ids)}")
|
| 254 |
+
rime_top1 = ranked[("rime", "full")][0]["all"]["top1"]
|
| 255 |
+
if rime_top1 != RIME_BASELINE_TOP1:
|
| 256 |
+
raise SystemExit(f"Rime pool order gives {rime_top1}, the plan records {RIME_BASELINE_TOP1}")
|
| 257 |
+
|
| 258 |
+
full = {arm: ranked[(arm, "full")] for arm in ARMS}
|
| 259 |
+
top1 = {arm: full[arm][0]["all"]["top1"] for arm in ARMS}
|
| 260 |
+
final = {arm: arms[arm]["training"]["milestones"][-1] for arm in ARMS}
|
| 261 |
+
noise = {"top1": spread([top1[a] for a in SEEDS]),
|
| 262 |
+
**{f"{n}_bpc": spread([bpc(final[a], n) for a in SEEDS]) for n in VALIDATIONS},
|
| 263 |
+
"pairs": {f"{a} vs {b}": compare(full[a][1], full[b][1], ids)["top1"]
|
| 264 |
+
for i, a in enumerate(SEEDS) for b in SEEDS[i + 1:]}}
|
| 265 |
+
seed_range = noise["top1"]["range"]
|
| 266 |
+
|
| 267 |
+
contrasts = []
|
| 268 |
+
for name, a, b, question in CONTRASTS:
|
| 269 |
+
result = compare(full[a][1], full[b][1], ids)
|
| 270 |
+
contrasts.append({"name": name, "a": a, "b": b, "question": question, "top1_a": top1[a], "top1_b": top1[b],
|
| 271 |
+
"difference": top1[b] - top1[a], "mcnemar_p": result["top1"]["exact_mcnemar_p"],
|
| 272 |
+
"top1": result["top1"], "top3": result["top3"]})
|
| 273 |
+
for entry, adjusted in zip(contrasts, holm([c["mcnemar_p"] for c in contrasts])):
|
| 274 |
+
entry["holm_p"] = adjusted
|
| 275 |
+
entry["beyond_seed_range"] = abs(entry["difference"]) > seed_range
|
| 276 |
+
entry["holm_significant"] = adjusted < ALPHA
|
| 277 |
+
entry["effective"] = entry["beyond_seed_range"] and entry["holm_significant"]
|
| 278 |
+
decision = decide(contrasts)
|
| 279 |
+
|
| 280 |
+
descriptive = {
|
| 281 |
+
"dose_response": [{"a": a, "b": b, "difference": top1[b] - top1[a],
|
| 282 |
+
**compare(full[a][1], full[b][1], ids)} for a, b in DESCRIPTIVE],
|
| 283 |
+
"arms": {arm: {"vocabulary": ARMS[arm][0], "pool": ARMS[arm][1], "epochs": ARMS[arm][2],
|
| 284 |
+
"final_step": arms[arm]["training"]["step"],
|
| 285 |
+
"checkpoint_sha256": arms[arm]["full_meta"]["checkpoint_sha256"],
|
| 286 |
+
"full": {k: full[arm][0]["all"][k] for k in ("top1", "top1_rate", "top3", "pool_conditional_top1", "mrr")},
|
| 287 |
+
"full_by_source": {s: v["top1"] for s, v in full[arm][0]["by_source"].items()},
|
| 288 |
+
"full_without_overlap_top1": full[arm][0]["sensitivity_without_overlap"]["top1"],
|
| 289 |
+
"abbrev_top1": ranked[(arm, "abbrev")][0]["all"]["top1"] if "abbrev" in tracks else None,
|
| 290 |
+
"bpc": {n: bpc(final[arm], n) for n in VALIDATIONS},
|
| 291 |
+
"memorization_gap": (bpc(final[arm], "web") - bpc(final[arm], "probe")
|
| 292 |
+
if bpc(final[arm], "web") is not None and bpc(final[arm], "probe") is not None else None),
|
| 293 |
+
"boundary_retokenized_items": arms[arm]["full_meta"].get("boundary_retokenized_items"),
|
| 294 |
+
"empty_pools": arms[arm]["full_meta"].get("empty_pools")}
|
| 295 |
+
for arm in ARMS},
|
| 296 |
+
"learning_curves": {arm: [{"milestone": m["milestone"], "step": m["step"],
|
| 297 |
+
"supervised_tokens": m.get("supervised_tokens"),
|
| 298 |
+
**{n: bpc(m, n) for n in VALIDATIONS}}
|
| 299 |
+
for m in arms[arm]["training"]["milestones"]] for arm in ARMS},
|
| 300 |
+
}
|
| 301 |
+
if "abbrev" in tracks:
|
| 302 |
+
descriptive["abbrev_contrasts"] = [
|
| 303 |
+
{"name": name, "a": a, "b": b,
|
| 304 |
+
**compare(ranked[(a, "abbrev")][1], ranked[(b, "abbrev")][1], sorted(ranked[(a, "abbrev")][1]))["top1"]}
|
| 305 |
+
for name, a, b, _ in CONTRASTS]
|
| 306 |
+
result = {"format": "vimeml_zh13_judgement_v1", "plan": "docs/zh-CN/training-zh-v1-plan.md",
|
| 307 |
+
"version": VERSION, "split": "development", "track": "full", "items": ITEMS,
|
| 308 |
+
"smoke": smoke, "rime_baseline_top1": rime_top1, "alpha": ALPHA,
|
| 309 |
+
"rule": "effective = |Top-1 difference| > range of the three 12k-fresh seeds and Holm-adjusted exact McNemar p < 0.05",
|
| 310 |
+
"noise_band": noise, "contrasts": contrasts, "decision": decision, "descriptive": descriptive,
|
| 311 |
+
"inputs": {arm: {"full_scores": str(arms[arm]["full"]), "abbrev_scores": str(arms[arm]["abbrev"]) if arms[arm]["abbrev"] else None,
|
| 312 |
+
"model_dir": str(arms[arm]["directory"])} for arm in ARMS}}
|
| 313 |
+
(out / "judgement.json").write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8", newline="\n")
|
| 314 |
+
(out / "report.md").write_text(report(result), encoding="utf-8", newline="\n")
|
| 315 |
+
return result
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _p(value):
|
| 319 |
+
return f"{value:.3g}" if value is not None else "—"
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _f(value, digits=4):
|
| 323 |
+
return f"{value:.{digits}f}" if value is not None else "—"
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def report(result):
|
| 327 |
+
noise, arms = result["noise_band"], result["descriptive"]["arms"]
|
| 328 |
+
lines = [f"# vimeml-tiny-zh-v1 判定{'(冒烟,不是正式结果)' if result['smoke'] else ''}", "",
|
| 329 |
+
f"按 `{result['plan']}` 预注册的规则,由 `scripts/benchmarks/judge_zh13.py` 生成。"
|
| 330 |
+
f"{result['version']} development 全拼轨道 {result['items']} 条,精确 Top-1;Rime 第一候选 {result['rime_baseline_top1']}。", "",
|
| 331 |
+
"## 结论", "",
|
| 332 |
+
f"- 数据:**{result['decision']['data']['choice'] or '未定'}**。{result['decision']['data']['basis']}。",
|
| 333 |
+
f"- 词表:**{result['decision']['vocabulary']['choice'] or '未定'}**。{result['decision']['vocabulary']['basis']}。", "",
|
| 334 |
+
"## 噪声带(三个 12k-fresh seed)", "",
|
| 335 |
+
f"Top-1:{', '.join(map(str, noise['top1']['values']))};均值 {noise['top1']['mean']:.1f},"
|
| 336 |
+
f"极差 **{noise['top1']['range']}**,标准差 {noise['top1']['sd']:.2f}。", ""]
|
| 337 |
+
for name in VALIDATIONS:
|
| 338 |
+
s = noise[f"{name}_bpc"]
|
| 339 |
+
if s:
|
| 340 |
+
lines.append(f"- {name} BPC:均值 {s['mean']:.4f},极差 {s['range']:.4f},标准差 {s['sd']:.4f}")
|
| 341 |
+
lines += ["", "| seed 对 | +/− | McNemar p | sign-flip p |", "| --- | ---: | ---: | ---: |"]
|
| 342 |
+
for pair, t in noise["pairs"].items():
|
| 343 |
+
lines.append(f"| {pair} | +{t['gain']}/−{t['loss']} | {_p(t['exact_mcnemar_p'])} | {_p(t['cluster_sign_flip_p'])} |")
|
| 344 |
+
lines += ["", "## 五个判定对比(Holm,族 α = 0.05)", "",
|
| 345 |
+
"| 对比 | A | B | Top-1 A | Top-1 B | B − A | +/− | McNemar p | Holm p | sign-flip p | 超过极差 | 有效 |",
|
| 346 |
+
"| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: | :---: |"]
|
| 347 |
+
for c in result["contrasts"]:
|
| 348 |
+
t = c["top1"]
|
| 349 |
+
lines.append(f"| {c['question']} | `{c['a']}` | `{c['b']}` | {c['top1_a']} | {c['top1_b']} | {c['difference']:+d} | "
|
| 350 |
+
f"+{t['gain']}/−{t['loss']} | {_p(c['mcnemar_p'])} | {_p(c['holm_p'])} | {_p(t['cluster_sign_flip_p'])} | "
|
| 351 |
+
f"{'是' if c['beyond_seed_range'] else '否'} | **{'是' if c['effective'] else '否'}** |")
|
| 352 |
+
lines += ["", "以下全部只描述,不参与判定。", "", "## 各臂", "",
|
| 353 |
+
"| 臂 | 词表 | 池 | 轮 | Top-1 | Top-3 | 池条件 Top-1 | 简拼 Top-1 | web BPC | chat BPC | probe BPC | 记忆差 |",
|
| 354 |
+
"| --- | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"]
|
| 355 |
+
for arm, a in arms.items():
|
| 356 |
+
lines.append(f"| `{arm}` | {a['vocabulary'] // 1024}K | {a['pool']} | {a['epochs']} | {a['full']['top1']} | {a['full']['top3']} | "
|
| 357 |
+
f"{_f(a['full']['pool_conditional_top1'], 3)} | {a['abbrev_top1'] if a['abbrev_top1'] is not None else '—'} | "
|
| 358 |
+
f"{_f(a['bpc']['web'])} | {_f(a['bpc']['chat'])} | {_f(a['bpc']['probe'])} | {_f(a['memorization_gap'])} |")
|
| 359 |
+
lines += ["", "记忆差 = validation 网页 BPC − P20 记忆抽样 BPC,越大说明训练文档比没见过的文档容易得越多。", "",
|
| 360 |
+
"## 剂量-反应(ep5)", "", "| A | B | B − A | +/− | McNemar p |", "| --- | --- | ---: | ---: | ---: |"]
|
| 361 |
+
for d in result["descriptive"]["dose_response"]:
|
| 362 |
+
t = d["top1"]
|
| 363 |
+
lines.append(f"| `{d['a']}` | `{d['b']}` | {d['difference']:+d} | +{t['gain']}/−{t['loss']} | {_p(t['exact_mcnemar_p'])} |")
|
| 364 |
+
if "abbrev_contrasts" in result["descriptive"]:
|
| 365 |
+
lines += ["", "## 简拼轨道的同五个对比", "", "| A | B | 净差 | +/− | McNemar p |", "| --- | --- | ---: | ---: | ---: |"]
|
| 366 |
+
for c in result["descriptive"]["abbrev_contrasts"]:
|
| 367 |
+
lines.append(f"| `{c['a']}` | `{c['b']}` | {c['net']:+d} | +{c['gain']}/−{c['loss']} | {_p(c['exact_mcnemar_p'])} |")
|
| 368 |
+
lines += ["", "## 各来源 Top-1", "", "| 臂 | crosswoz | risawoz | kdconv | 去重叠后 Top-1 |", "| --- | ---: | ---: | ---: | ---: |"]
|
| 369 |
+
for arm, a in arms.items():
|
| 370 |
+
s = a["full_by_source"]
|
| 371 |
+
lines.append(f"| `{arm}` | {s['crosswoz']} | {s['risawoz']} | {s['kdconv']} | {a['full_without_overlap_top1']} |")
|
| 372 |
+
lines += ["", "学习曲线(每 1/20 的 web/chat/probe BPC)见 `judgement.json` 的 `descriptive.learning_curves`。", ""]
|
| 373 |
+
return "\n".join(lines)
|
source/src/vimeml/benchmarks/zh13_lm_scores.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LM rerank scores of the Standard Chinese IME benchmark for vimeml-tiny-zh-v1 checkpoints.
|
| 2 |
+
|
| 3 |
+
Scoring is V4.2's (evaluate_ime.score_candidates): BOS + left context + candidate
|
| 4 |
+
is tokenized jointly; the scored region starts at the common token prefix of the
|
| 5 |
+
context alone and every candidate sequence, so when the last context piece merges
|
| 6 |
+
with a candidate's first characters, that piece is rescored for every candidate
|
| 7 |
+
from the first divergence; no candidate-final EOS. The score is the sum of
|
| 8 |
+
full-vocabulary FP32 log-probabilities over the region. Only split=='development'
|
| 9 |
+
items are read unless run() is given split='blind' and a verified committed plan.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from vimeml.training.data import file_sha
|
| 18 |
+
from vimeml.training.joint_zh13 import ARCHITECTURE, FORMAT, SPECIAL
|
| 19 |
+
from vimeml.training.model_zh13 import GPTZh13Config, TinyGPTZh13
|
| 20 |
+
|
| 21 |
+
VERSION = "ime-standard-zh-v1-r1"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def read_jsonl(path):
|
| 25 |
+
with open(path, encoding="utf-8") as stream:
|
| 26 |
+
return [json.loads(line) for line in stream if line.strip()]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load(checkpoint, tokenizer, device="cpu"):
|
| 30 |
+
import sentencepiece as spm
|
| 31 |
+
saved = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
| 32 |
+
if saved.get("format") != FORMAT or saved.get("architecture") != ARCHITECTURE:
|
| 33 |
+
raise ValueError("Not a vimeml-tiny-zh-v1 checkpoint")
|
| 34 |
+
identity = saved["tokenizer_identity"]
|
| 35 |
+
if file_sha(tokenizer) != identity["tokenizer_model_sha256"] or identity["special_ids"] != SPECIAL:
|
| 36 |
+
raise ValueError("Tokenizer differs from the checkpoint's tokenizer identity")
|
| 37 |
+
model = TinyGPTZh13(GPTZh13Config(**saved["model_config"]))
|
| 38 |
+
model.load_state_dict(saved["model"], strict=True)
|
| 39 |
+
model.to(device).eval()
|
| 40 |
+
processor = spm.SentencePieceProcessor(model_file=str(tokenizer))
|
| 41 |
+
meta = {"checkpoint": str(checkpoint), "checkpoint_sha256": file_sha(checkpoint), "step": saved["step"],
|
| 42 |
+
"arm": saved["config"].get("arm"), "tokenizer_model_sha256": identity["tokenizer_model_sha256"]}
|
| 43 |
+
return model, processor, meta
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def common_prefix(sequences):
|
| 47 |
+
length = min(map(len, sequences))
|
| 48 |
+
for i in range(length):
|
| 49 |
+
if any(s[i] != sequences[0][i] for s in sequences):
|
| 50 |
+
return i
|
| 51 |
+
return length
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@torch.inference_mode()
|
| 55 |
+
def score_item(model, processor, context, candidates, device="cpu"):
|
| 56 |
+
if not candidates or len(set(candidates)) != len(candidates) or any(not c for c in candidates):
|
| 57 |
+
raise ValueError("Candidates must be distinct nonempty strings")
|
| 58 |
+
context_ids = [SPECIAL["bos"], *processor.encode(context)]
|
| 59 |
+
sequences = []
|
| 60 |
+
for candidate in candidates:
|
| 61 |
+
content = processor.encode(context + candidate)
|
| 62 |
+
if processor.decode(content) != context + candidate:
|
| 63 |
+
raise ValueError("Context + candidate does not roundtrip with the tokenizer")
|
| 64 |
+
sequence = [SPECIAL["bos"], *content]
|
| 65 |
+
if not 1 <= len(sequence) - 1 <= model.config.context_length:
|
| 66 |
+
raise ValueError("Context + candidate exceeds the model context; no silent truncation")
|
| 67 |
+
sequences.append(sequence)
|
| 68 |
+
common = common_prefix([context_ids, *sequences])
|
| 69 |
+
if common < 1 or any(len(s) <= common for s in sequences):
|
| 70 |
+
raise ValueError("Every candidate needs scored targets")
|
| 71 |
+
width = max(len(s) - 1 for s in sequences)
|
| 72 |
+
inputs = torch.full((len(sequences), width), SPECIAL["pad"], dtype=torch.long)
|
| 73 |
+
targets = inputs.clone()
|
| 74 |
+
mask = torch.zeros_like(inputs, dtype=torch.bool)
|
| 75 |
+
for row, s in enumerate(sequences):
|
| 76 |
+
inputs[row, :len(s) - 1] = torch.tensor(s[:-1])
|
| 77 |
+
targets[row, :len(s) - 1] = torch.tensor(s[1:])
|
| 78 |
+
mask[row, common - 1:len(s) - 1] = True
|
| 79 |
+
logits = model(inputs.to(device)).float()
|
| 80 |
+
values = logits.log_softmax(-1).gather(-1, targets.to(device).unsqueeze(-1)).squeeze(-1).cpu()
|
| 81 |
+
scores = [float(values[row][mask[row]].sum()) for row in range(len(sequences))]
|
| 82 |
+
if not all(math.isfinite(v) for v in scores):
|
| 83 |
+
raise ValueError("Non-finite candidate score")
|
| 84 |
+
return {"scores": scores, "scored_tokens": [int(mask[row].sum()) for row in range(len(sequences))],
|
| 85 |
+
"common_prefix_tokens_including_bos": common, "context_tokens_including_bos": len(context_ids),
|
| 86 |
+
"boundary_retokenized": any(s[:len(context_ids)] != context_ids for s in sequences)}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def run(checkpoint, tokenizer, frozen, out, track="full", device="cpu", split="development", blind_plan=None,
|
| 90 |
+
loaded=None):
|
| 91 |
+
"""`loaded` = (model, processor, meta) scores another forward (e.g. Core ML) with the same rules."""
|
| 92 |
+
if split not in ("development", "blind"):
|
| 93 |
+
raise ValueError(f"Unknown split {split}")
|
| 94 |
+
if split == "blind" and not blind_plan:
|
| 95 |
+
raise ValueError("blind needs a verified committed plan")
|
| 96 |
+
frozen, out = Path(frozen), Path(out)
|
| 97 |
+
if out.exists():
|
| 98 |
+
raise ValueError(f"{out} exists; choose a new file")
|
| 99 |
+
manifest = json.loads((frozen / "manifest.json").read_text("utf-8"))
|
| 100 |
+
if manifest["version"] != VERSION:
|
| 101 |
+
raise ValueError(f"Expected {VERSION}")
|
| 102 |
+
items = {i["id"]: i for i in read_jsonl(frozen / "items.jsonl")
|
| 103 |
+
if i["split"] == split and (track == "full" or i["keys_abbrev"] is not None)}
|
| 104 |
+
pools = {p["id"]: p for p in read_jsonl(frozen / f"pool-{track}.jsonl") if p["id"] in items}
|
| 105 |
+
if set(pools) != set(items):
|
| 106 |
+
raise ValueError(f"pool-{track}.jsonl does not cover every {split} item")
|
| 107 |
+
model, processor, meta = loaded or load(checkpoint, tokenizer, device)
|
| 108 |
+
with torch.autocast(torch.device(device).type, enabled=False):
|
| 109 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 110 |
+
retokenized = empty = fallbacks = 0
|
| 111 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
temporary = out.with_suffix(out.suffix + ".tmp")
|
| 113 |
+
with open(temporary, "w", encoding="utf-8", newline="\n") as stream:
|
| 114 |
+
for item_id in sorted(items):
|
| 115 |
+
texts = [c["text"] for c in pools[item_id]["candidates"]]
|
| 116 |
+
if not texts: # empty Rime pool: no ranking; the item stays in the denominator
|
| 117 |
+
empty += 1
|
| 118 |
+
result = {"scores": []}
|
| 119 |
+
else:
|
| 120 |
+
try:
|
| 121 |
+
result = score_item(model, processor, items[item_id]["left_context"], texts, device)
|
| 122 |
+
except ValueError:
|
| 123 |
+
if split != "blind":
|
| 124 |
+
raise
|
| 125 |
+
fallbacks += 1 # the benchmark rule: this item keeps the pool order
|
| 126 |
+
result = {"scores": None, "boundary_retokenized": False}
|
| 127 |
+
retokenized += result["boundary_retokenized"]
|
| 128 |
+
stream.write(json.dumps({"id": item_id, "candidates": texts, **result}, ensure_ascii=False) + "\n")
|
| 129 |
+
temporary.replace(out)
|
| 130 |
+
summary = {**meta, "version": VERSION, "track": track, "split": split, "items": len(items),
|
| 131 |
+
"boundary_retokenized_items": retokenized, "empty_pools": empty, "fallbacks": fallbacks, "scores_sha256": file_sha(out),
|
| 132 |
+
"scoring": "joint tokenization, common-prefix suffix log-probability sum, FP32, no EOS",
|
| 133 |
+
**({"blind_plan": blind_plan} if blind_plan else {})}
|
| 134 |
+
out.with_suffix(".meta.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
| 135 |
+
return summary
|
source/src/vimeml/benchmarks/zh_baselines.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Baselines for vimeml-tiny-zh-v1 on the Standard zh benchmark (docs/zh-CN/benchmarks/baselines-zh-v1-plan.md).
|
| 2 |
+
|
| 3 |
+
engine: a Rime configuration ranks on its own; the first `--n` whole-input Han candidates of the
|
| 4 |
+
engine (rime_candidates.py query, the same rule that built the frozen pools) are the ranking.
|
| 5 |
+
lm: an external causal LM reranks the frozen pool with the v1 scoring rule: start token + left
|
| 6 |
+
context + candidate tokenized jointly, the sum of FP32 full-vocabulary log-probabilities
|
| 7 |
+
from the first token where any candidate differs from the context alone, no EOS.
|
| 8 |
+
Both write <out>/result/{items.jsonl,summary.json} in score_standard_ime_zh.py's format, so its
|
| 9 |
+
`compare` pairs them with the v1 runs. blind needs a committed plan that names the benchmark.
|
| 10 |
+
"""
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
from vimeml.benchmarks.zh13_lm_scores import VERSION, common_prefix, read_jsonl
|
| 19 |
+
from vimeml.training.data import file_sha
|
| 20 |
+
|
| 21 |
+
FROZEN = "outputs/benchmarks/ime-standard-zh-v1/frozen-r1"
|
| 22 |
+
SCORER = "scripts/benchmarks/score_standard_ime_zh.py"
|
| 23 |
+
RIME = "scripts/benchmarks/rime_candidates.py"
|
| 24 |
+
OPTIONAL = "artifacts/external-eval/site-packages"
|
| 25 |
+
ENGINES = ("ice", "ice-gram", "luna")
|
| 26 |
+
EXTERNAL = {
|
| 27 |
+
"qwen2.5-0.5b": {"id": "Qwen/Qwen2.5-0.5B", "revision": "060db6499f32faf8b98477b0a26969ef7d8b9987"},
|
| 28 |
+
"qwen3-0.6b-base": {"id": "Qwen/Qwen3-0.6B-Base", "revision": "da87bfb608c14b7cf20ba1ce41287e8de496c0cd"},
|
| 29 |
+
}
|
| 30 |
+
GRAMMAR_SHA256 = "3457b69f5fe0fc4f5d211c878bbfa2e2361b90639952c9845c8e31e9d047cde6"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def scorer_module(root):
|
| 34 |
+
spec = importlib.util.spec_from_file_location("score_standard_ime_zh", root / SCORER)
|
| 35 |
+
module = importlib.util.module_from_spec(spec)
|
| 36 |
+
spec.loader.exec_module(module)
|
| 37 |
+
return module
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def gate(root, split, plan):
|
| 41 |
+
if split not in ("development", "blind"):
|
| 42 |
+
raise ValueError(f"Unknown split {split}")
|
| 43 |
+
if split == "blind":
|
| 44 |
+
if not plan:
|
| 45 |
+
raise ValueError("blind needs --blind-plan, a committed plan naming the benchmark")
|
| 46 |
+
return scorer_module(root).check_blind_plan(plan)
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_items(root, split, track):
|
| 51 |
+
return {i["id"]: i for i in read_jsonl(root / FROZEN / "items.jsonl")
|
| 52 |
+
if i["split"] == split and (track == "full" or i["keys_abbrev"] is not None)}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def engine(root, variant, split, track, out, plan=None, n=20):
|
| 56 |
+
root, out = Path(root), Path(out)
|
| 57 |
+
plan_record = gate(root, split, plan)
|
| 58 |
+
if variant not in ENGINES:
|
| 59 |
+
raise ValueError(f"Unknown engine {variant}")
|
| 60 |
+
if variant == "ice-gram" and file_sha(root / "datasets/ime-standard-zh-v1/engine/grammar/wanxiang-lts-zh-hans.gram") != GRAMMAR_SHA256:
|
| 61 |
+
raise ValueError("grammar model differs from the registered SHA256")
|
| 62 |
+
out.mkdir(parents=True)
|
| 63 |
+
items = load_items(root, split, track)
|
| 64 |
+
with open(out / "inputs.jsonl", "w", encoding="utf-8", newline="\n") as stream:
|
| 65 |
+
for row in read_jsonl(root / FROZEN / f"rime-{track}.jsonl"):
|
| 66 |
+
if row["id"] in items:
|
| 67 |
+
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 68 |
+
done = subprocess.run([sys.executable, "-I", "-X", "utf8", str(root / RIME), "query", "--variant", variant, "--n", str(n),
|
| 69 |
+
str(out / "inputs.jsonl"), str(out / "candidates.jsonl")], capture_output=True, text=True, encoding="utf-8")
|
| 70 |
+
if done.returncode:
|
| 71 |
+
raise SystemExit(f"rime_candidates.py failed:\n{done.stderr}")
|
| 72 |
+
found = {r["id"]: r for r in read_jsonl(out / "candidates.jsonl")}
|
| 73 |
+
if set(found) != set(items):
|
| 74 |
+
raise SystemExit("engine output does not cover every item")
|
| 75 |
+
scorer = scorer_module(root)
|
| 76 |
+
overlap = {r["id"] for r in read_jsonl(root / FROZEN / "overlap" / "overlap.jsonl")}
|
| 77 |
+
manifest = json.loads((root / FROZEN / "manifest.json").read_text(encoding="utf-8"))
|
| 78 |
+
rows = []
|
| 79 |
+
for item_id in sorted(items):
|
| 80 |
+
item, ranked = items[item_id], found[item_id]["candidates"]
|
| 81 |
+
accepted = {item["target"], *item["alternatives"]}
|
| 82 |
+
rank = next((k + 1 for k, text in enumerate(ranked) if text in accepted), None)
|
| 83 |
+
rows.append({"id": item_id, "source": item["source"], "dialogue": f'{item["source"]}:{item["dialogue_id"]}',
|
| 84 |
+
"length": scorer.length_bin(item["target"]), "target": item["target"],
|
| 85 |
+
"choice": ranked[0] if ranked else None, "rank": rank, "overlap": item_id in overlap})
|
| 86 |
+
summary = {"version": VERSION, "track": track, "split": split, "system": f"rime-{variant}",
|
| 87 |
+
"engine": found[next(iter(found))]["engine"], "scores": None, "fallbacks": 0, "blind_plan": plan_record,
|
| 88 |
+
"labels": manifest["labels"], **scorer.summarize(rows),
|
| 89 |
+
"sensitivity_without_overlap": scorer.rates([r for r in rows if not r["overlap"]]),
|
| 90 |
+
"overlap_items": sum(r["overlap"] for r in rows)}
|
| 91 |
+
result = out / "result"
|
| 92 |
+
result.mkdir()
|
| 93 |
+
with open(result / "items.jsonl", "w", encoding="utf-8", newline="\n") as stream:
|
| 94 |
+
for row in rows:
|
| 95 |
+
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 96 |
+
(result / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
| 97 |
+
return summary
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class External:
|
| 101 |
+
def __init__(self, root, key, device):
|
| 102 |
+
sys.path.insert(0, str(Path(root) / OPTIONAL))
|
| 103 |
+
import torch
|
| 104 |
+
from huggingface_hub import snapshot_download
|
| 105 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 106 |
+
spec = EXTERNAL[key]
|
| 107 |
+
path = snapshot_download(spec["id"], revision=spec["revision"], local_files_only=True)
|
| 108 |
+
self.torch, self.device, self.spec = torch, device, spec
|
| 109 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 110 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 111 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
| 112 |
+
self.model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.float32).to(device).eval()
|
| 113 |
+
self.start = self.tokenizer.convert_tokens_to_ids("<|endoftext|>")
|
| 114 |
+
self.parameters = sum(p.numel() for p in self.model.parameters())
|
| 115 |
+
|
| 116 |
+
def encode(self, text):
|
| 117 |
+
return self.tokenizer.encode(text, add_special_tokens=False)
|
| 118 |
+
|
| 119 |
+
def score(self, context, candidates):
|
| 120 |
+
torch = self.torch
|
| 121 |
+
context_ids = [self.start, *self.encode(context)]
|
| 122 |
+
sequences = []
|
| 123 |
+
for candidate in candidates:
|
| 124 |
+
ids = self.encode(context + candidate)
|
| 125 |
+
if self.tokenizer.decode(ids, clean_up_tokenization_spaces=False) != context + candidate:
|
| 126 |
+
raise ValueError("Context + candidate does not roundtrip with the tokenizer")
|
| 127 |
+
sequences.append([self.start, *ids])
|
| 128 |
+
common = common_prefix([context_ids, *sequences])
|
| 129 |
+
if common < 1 or any(len(s) <= common for s in sequences):
|
| 130 |
+
raise ValueError("Every candidate needs scored targets")
|
| 131 |
+
width = max(map(len, sequences))
|
| 132 |
+
ids = torch.full((len(sequences), width), self.start, dtype=torch.long)
|
| 133 |
+
attention = torch.zeros_like(ids)
|
| 134 |
+
for row, s in enumerate(sequences):
|
| 135 |
+
ids[row, :len(s)] = torch.tensor(s)
|
| 136 |
+
attention[row, :len(s)] = 1
|
| 137 |
+
rows, positions, targets = [], [], []
|
| 138 |
+
for row, s in enumerate(sequences):
|
| 139 |
+
for position in range(common - 1, len(s) - 1):
|
| 140 |
+
rows.append(row); positions.append(position); targets.append(s[position + 1])
|
| 141 |
+
with torch.inference_mode():
|
| 142 |
+
hidden = self.model.model(input_ids=ids.to(self.device), attention_mask=attention.to(self.device),
|
| 143 |
+
use_cache=False).last_hidden_state
|
| 144 |
+
selected = hidden[torch.tensor(rows, device=self.device), torch.tensor(positions, device=self.device)]
|
| 145 |
+
logits = self.model.lm_head(selected).float().log_softmax(-1)
|
| 146 |
+
values = logits.gather(-1, torch.tensor(targets, device=self.device).unsqueeze(-1)).squeeze(-1).cpu()
|
| 147 |
+
scores = [0.0] * len(sequences)
|
| 148 |
+
for row, value in zip(rows, values.tolist()):
|
| 149 |
+
scores[row] += value
|
| 150 |
+
if not all(math.isfinite(v) for v in scores):
|
| 151 |
+
raise ValueError("Non-finite candidate score")
|
| 152 |
+
return scores, any(s[:len(context_ids)] != context_ids for s in sequences)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def lm(root, key, split, track, out, plan=None, device="cuda"):
|
| 156 |
+
root, out = Path(root), Path(out)
|
| 157 |
+
gate(root, split, plan)
|
| 158 |
+
if key not in EXTERNAL:
|
| 159 |
+
raise ValueError(f"Unknown model {key}")
|
| 160 |
+
out.mkdir(parents=True)
|
| 161 |
+
items = load_items(root, split, track)
|
| 162 |
+
pools = {p["id"]: p for p in read_jsonl(root / FROZEN / f"pool-{track}.jsonl") if p["id"] in items}
|
| 163 |
+
if set(pools) != set(items):
|
| 164 |
+
raise SystemExit(f"pool-{track}.jsonl does not cover every {split} item")
|
| 165 |
+
model = External(root, key, device)
|
| 166 |
+
fallbacks = retokenized = empty = 0
|
| 167 |
+
with open(out / "scores.jsonl", "w", encoding="utf-8", newline="\n") as stream:
|
| 168 |
+
for item_id in sorted(items):
|
| 169 |
+
texts = [c["text"] for c in pools[item_id]["candidates"]]
|
| 170 |
+
scores = []
|
| 171 |
+
if not texts:
|
| 172 |
+
empty += 1
|
| 173 |
+
else:
|
| 174 |
+
try:
|
| 175 |
+
scores, changed = model.score(items[item_id]["left_context"], texts)
|
| 176 |
+
retokenized += changed
|
| 177 |
+
except ValueError:
|
| 178 |
+
fallbacks += 1 # the benchmark rule: this item keeps the pool order
|
| 179 |
+
scores = None
|
| 180 |
+
stream.write(json.dumps({"id": item_id, "candidates": texts, "scores": scores}, ensure_ascii=False) + "\n")
|
| 181 |
+
meta = {"model": model.spec, "parameters": model.parameters, "dtype": "float32", "device": device, "version": VERSION,
|
| 182 |
+
"track": track, "split": split, "items": len(items), "empty_pools": empty, "fallbacks": fallbacks,
|
| 183 |
+
"boundary_retokenized_items": retokenized, "scores_sha256": file_sha(out / "scores.jsonl"),
|
| 184 |
+
"scoring": "start <|endoftext|> + left context + candidate, joint tokenization, common-prefix suffix log-probability sum, FP32, no EOS"}
|
| 185 |
+
(out / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
| 186 |
+
command = [sys.executable, "-I", "-X", "utf8", str(root / SCORER), "score", str(root / FROZEN), str(out / "result"),
|
| 187 |
+
"--track", track, "--split", split, "--scores", str(out / "scores.jsonl"), "--name", key]
|
| 188 |
+
if plan:
|
| 189 |
+
command += ["--blind-plan", str(plan)]
|
| 190 |
+
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8")
|
| 191 |
+
if done.returncode:
|
| 192 |
+
raise SystemExit(f"scorer failed:\n{done.stderr}")
|
| 193 |
+
return json.loads((out / "result" / "summary.json").read_text(encoding="utf-8"))
|
source/src/vimeml/benchmarks/zh_v1_confirm.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preregistered blind confirmation of vimeml-tiny-zh-v1 (docs/zh-CN/benchmarks/confirmation-zh-v1-plan.md).
|
| 2 |
+
|
| 3 |
+
Everything the plan fixes is a constant here. run() checks that the plan and code are committed and
|
| 4 |
+
unmodified and that the checkpoint and frozen files have the registered SHA256, rescores development
|
| 5 |
+
and requires the ranks recorded by the judgement, writes a consumption record, and only then opens
|
| 6 |
+
blind. Once an attempt has finished, blind is never scored again by this script.
|
| 7 |
+
"""
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from vimeml.benchmarks.zh13_lm_scores import VERSION, read_jsonl, run as score_lm
|
| 16 |
+
from vimeml.training.data import file_sha
|
| 17 |
+
|
| 18 |
+
PLAN = "docs/zh-CN/benchmarks/confirmation-zh-v1-plan.md"
|
| 19 |
+
CHECKPOINT = "artifacts/models/tiny-zh13-12k-fresh-s1-d384-l9/final.pt"
|
| 20 |
+
TOKENIZER = "artifacts/tokenizers/zh-v13/zh-unigram-12288/tokenizer.model"
|
| 21 |
+
FROZEN = "outputs/benchmarks/ime-standard-zh-v1/frozen-r1"
|
| 22 |
+
JUDGED = "outputs/benchmarks/zh13-20m/judgement/scores"
|
| 23 |
+
ARM = "12k-fresh-s1"
|
| 24 |
+
BASE = "outputs/benchmarks/zh-v1-confirmation"
|
| 25 |
+
SCORER = "scripts/benchmarks/score_standard_ime_zh.py"
|
| 26 |
+
SHA256 = {
|
| 27 |
+
CHECKPOINT: "44c423a1e7cb0e32161afc94d6167cabb439a3d25fd9de6d1fbb150a927542d4",
|
| 28 |
+
TOKENIZER: "68bd37c45bcb018b32b2eef5b241561ab5b6dc1b77c1c3aadcc1b41c4bf47e5a",
|
| 29 |
+
f"{FROZEN}/items.jsonl": "43d6fe0a4d88d856a9d9d18fe7bd1bdaa0da6d229ca6154dcdfc6575f8d0adaa",
|
| 30 |
+
f"{FROZEN}/pool-full.jsonl": "82bcd51f97886742659855e1f27e20f7bddccca231db81a4ce284c95f6467fd8",
|
| 31 |
+
f"{FROZEN}/pool-abbrev.jsonl": "9773050b66851582424e595a14c9ff2041a51d94b9cf0b703e5e7a7f212b0e2e",
|
| 32 |
+
f"{FROZEN}/manifest.json": "6b9d0a66aa46446a330301b00462c8e63b2f4ea63aa6d0a75ede47ef6a7bb701",
|
| 33 |
+
}
|
| 34 |
+
COMMITTED = (PLAN, SCORER, "scripts/benchmarks/confirm_zh_v1.py", "src/vimeml/benchmarks/zh_v1_confirm.py",
|
| 35 |
+
"src/vimeml/benchmarks/zh13_lm_scores.py", "src/vimeml/benchmarks/statistics.py",
|
| 36 |
+
"src/vimeml/training/model_zh13.py", "src/vimeml/training/joint_zh13.py")
|
| 37 |
+
RIME_BLIND_TOP1 = {"full": 1045, "abbrev": 147} # recorded in docs/zh-CN/benchmarks/standard-ime-zh.md
|
| 38 |
+
SOURCES = ("crosswoz", "risawoz", "kdconv")
|
| 39 |
+
TRACKS = ("full", "abbrev")
|
| 40 |
+
ALPHA = 0.05
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def decide(compare):
|
| 44 |
+
"""The plan's rule, from the full-track `compare` output of Rime -> the candidate."""
|
| 45 |
+
top1, top3 = compare["top1"], compare["top3"]
|
| 46 |
+
h1 = top1["net"] > 0 and top1["exact_mcnemar_p"] < ALPHA
|
| 47 |
+
sources = {s: compare["top1_by_source"][s]["net"] > 0 for s in SOURCES}
|
| 48 |
+
top3_guard = not (top3["net"] < 0 and top3["exact_mcnemar_p"] < ALPHA)
|
| 49 |
+
return {"h1_confirmed": h1, "every_source_positive": sources, "top3_no_significant_drop": top3_guard,
|
| 50 |
+
"passed": h1 and all(sources.values()) and top3_guard}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def wilson(hits, n, z=1.959963984540054):
|
| 54 |
+
centre, margin = hits + z * z / 2, z * math.sqrt(hits * (n - hits) / n + z * z / 4)
|
| 55 |
+
denominator = n + z * z
|
| 56 |
+
return [(centre - margin) / denominator, (centre + margin) / denominator]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def git(root, *args):
|
| 60 |
+
return subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def check_committed(root):
|
| 64 |
+
for path in COMMITTED:
|
| 65 |
+
if git(root, "ls-files", "--error-unmatch", path).returncode:
|
| 66 |
+
raise SystemExit(f"not committed: {path}")
|
| 67 |
+
if git(root, "diff", "--quiet", "HEAD", "--", path).returncode:
|
| 68 |
+
raise SystemExit(f"differs from the committed version: {path}")
|
| 69 |
+
if VERSION not in (root / PLAN).read_text(encoding="utf-8"):
|
| 70 |
+
raise SystemExit(f"{PLAN} does not name {VERSION}")
|
| 71 |
+
return {"path": PLAN, "commit": git(root, "log", "-1", "--format=%H", "--", PLAN).stdout.strip(),
|
| 72 |
+
"head": git(root, "rev-parse", "HEAD").stdout.strip()}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def check_identities(root):
|
| 76 |
+
for path, expected in SHA256.items():
|
| 77 |
+
if file_sha(root / path) != expected:
|
| 78 |
+
raise SystemExit(f"SHA256 differs from the plan: {path}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def run_scorer(root, out, track, split="development", scores=None, name=None, plan=None):
|
| 82 |
+
command = [sys.executable, "-I", "-X", "utf8", str(root / SCORER), "score", str(root / FROZEN), str(out), "--track", track]
|
| 83 |
+
command += ["--split", split]
|
| 84 |
+
if scores:
|
| 85 |
+
command += ["--scores", str(scores), "--name", name]
|
| 86 |
+
if plan:
|
| 87 |
+
command += ["--blind-plan", str(root / plan)]
|
| 88 |
+
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8")
|
| 89 |
+
if done.returncode:
|
| 90 |
+
raise SystemExit(f"scorer failed for {out.name}:\n{done.stderr}")
|
| 91 |
+
return json.loads((out / "summary.json").read_text(encoding="utf-8"))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def preflight(root, out, device):
|
| 95 |
+
"""Rescore development; every rank must equal the judged run, otherwise blind stays closed."""
|
| 96 |
+
for track in TRACKS:
|
| 97 |
+
scores = out / "development" / f"{track}.jsonl"
|
| 98 |
+
score_lm(root / CHECKPOINT, root / TOKENIZER, root / FROZEN, scores, track, device)
|
| 99 |
+
scored = out / "development" / f"score-{track}"
|
| 100 |
+
run_scorer(root, scored, track, scores=scores, name=ARM)
|
| 101 |
+
now = {r["id"]: r["rank"] for r in read_jsonl(scored / "items.jsonl")}
|
| 102 |
+
judged = {r["id"]: r["rank"] for r in read_jsonl(root / JUDGED / f"{ARM}-{track}" / "items.jsonl")}
|
| 103 |
+
if now != judged:
|
| 104 |
+
changed = sum(now.get(i) != judged[i] for i in judged)
|
| 105 |
+
raise SystemExit(f"preflight failed: {changed} {track} ranks differ from the judgement; blind not opened")
|
| 106 |
+
print(f"preflight {track}: {len(now)} ranks equal the judgement", flush=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def next_directory(base, prefix):
|
| 110 |
+
used = [int(p.name.rsplit("-", 1)[1]) for p in base.glob(f"{prefix}-*") if p.is_dir()]
|
| 111 |
+
directory = base / f"{prefix}-{max(used, default=0) + 1:02d}"
|
| 112 |
+
directory.mkdir(parents=True)
|
| 113 |
+
return directory
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def read_consumption(path):
|
| 117 |
+
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"benchmark": VERSION, "split": "blind", "attempts": []}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def write_consumption(path, record):
|
| 121 |
+
path.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def confirm(root, out, plan, device):
|
| 125 |
+
tracks = {}
|
| 126 |
+
for track in TRACKS:
|
| 127 |
+
scores = out / "blind" / f"{track}.jsonl"
|
| 128 |
+
meta = score_lm(root / CHECKPOINT, root / TOKENIZER, root / FROZEN, scores, track, device, split="blind", blind_plan=plan)
|
| 129 |
+
rime = run_scorer(root, out / f"rime-{track}", track, "blind", plan=PLAN)
|
| 130 |
+
if rime["all"]["top1"] != RIME_BLIND_TOP1[track]:
|
| 131 |
+
raise SystemExit(f"Rime blind {track} Top-1 is {rime['all']['top1']}, recorded {RIME_BLIND_TOP1[track]}")
|
| 132 |
+
model = run_scorer(root, out / f"v1-{track}", track, "blind", scores=scores, name="vimeml-tiny-zh-v1", plan=PLAN)
|
| 133 |
+
compared = out / f"compare-{track}.json"
|
| 134 |
+
done = subprocess.run([sys.executable, "-I", "-X", "utf8", str(root / SCORER), "compare",
|
| 135 |
+
str(out / f"rime-{track}"), str(out / f"v1-{track}"), str(compared)], capture_output=True, text=True, encoding="utf-8")
|
| 136 |
+
if done.returncode:
|
| 137 |
+
raise SystemExit(f"compare failed for {track}:\n{done.stderr}")
|
| 138 |
+
tracks[track] = {"rime": rime, "model": model, "compare": json.loads(compared.read_text(encoding="utf-8")), "meta": meta}
|
| 139 |
+
full = tracks["full"]["model"]["all"]
|
| 140 |
+
result = {"version": VERSION, "split": "blind", "plan": plan, "arm": ARM, "sha256": SHA256,
|
| 141 |
+
"decision": decide(tracks["full"]["compare"]), "top1_wilson_95": wilson(full["top1"], full["n"]),
|
| 142 |
+
"fallbacks": {t: tracks[t]["model"]["fallbacks"] for t in TRACKS},
|
| 143 |
+
"tracks": {t: {k: tracks[t][k] for k in ("rime", "model", "compare")} for t in TRACKS}}
|
| 144 |
+
(out / "summary.json").write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
| 145 |
+
return result
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def run(root, device="cuda", preflight_only=False):
|
| 149 |
+
root, base = Path(root), Path(root) / BASE
|
| 150 |
+
ledger = base / "consumption.json"
|
| 151 |
+
check_identities(root)
|
| 152 |
+
if preflight_only:
|
| 153 |
+
out = next_directory(base, "preflight")
|
| 154 |
+
preflight(root, out, device)
|
| 155 |
+
print(f"preflight passed, blind not opened: {out}")
|
| 156 |
+
return None
|
| 157 |
+
plan = check_committed(root)
|
| 158 |
+
record = read_consumption(ledger)
|
| 159 |
+
if any(a["status"] == "finished" for a in record["attempts"]):
|
| 160 |
+
raise SystemExit(f"blind confirmation already finished, see {ledger}; it is not rerun")
|
| 161 |
+
out = next_directory(base, "run")
|
| 162 |
+
preflight(root, out, device)
|
| 163 |
+
attempt = {"directory": out.name, "plan": plan, "opened_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "status": "opened"}
|
| 164 |
+
record["attempts"].append(attempt)
|
| 165 |
+
write_consumption(ledger, record)
|
| 166 |
+
result = confirm(root, out, plan, device)
|
| 167 |
+
attempt.update(status="finished", summary_sha256=file_sha(out / "summary.json"), passed=result["decision"]["passed"])
|
| 168 |
+
write_consumption(ledger, record)
|
| 169 |
+
return result
|
source/src/vimeml/corpus/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""VimeML corpus utilities."""
|
source/src/vimeml/corpus/build.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run local cleaning workers concurrently, then merge into one corpus.
|
| 2 |
+
|
| 3 |
+
Each cleaning worker owns its SQLite database. Completed parts are then merged
|
| 4 |
+
through the parallel hash-bucket exporter.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
from contextlib import ExitStack
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 18 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 19 |
+
|
| 20 |
+
from vimeml.data.build import dump_json, file_sha
|
| 21 |
+
from vimeml.data.corpus_parts import AUDITS, load_plan, PART_SCHEMA_VERSION
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def tail(path, maximum=8192):
|
| 25 |
+
if not path.exists():
|
| 26 |
+
return ""
|
| 27 |
+
with path.open("rb") as stream:
|
| 28 |
+
stream.seek(max(0, path.stat().st_size - maximum))
|
| 29 |
+
return stream.read().decode("utf-8", errors="replace")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def elapsed_text(seconds):
|
| 33 |
+
minutes, seconds = divmod(int(seconds), 60)
|
| 34 |
+
hours, minutes = divmod(minutes, 60)
|
| 35 |
+
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def preserve_interrupted(path, owner):
|
| 39 |
+
path, owner = path.resolve(), owner.resolve()
|
| 40 |
+
if not owner.is_relative_to(ROOT) or not path.is_relative_to(owner) or path == owner:
|
| 41 |
+
raise ValueError("Interrupted output must stay inside its owned workspace.")
|
| 42 |
+
destination = path.with_name(f"{path.name}-interrupted-{time.time_ns()}")
|
| 43 |
+
if not destination.resolve().is_relative_to(owner):
|
| 44 |
+
raise ValueError("Invalid interrupted-output destination.")
|
| 45 |
+
path.rename(destination)
|
| 46 |
+
print(f"Preserved interrupted output: {destination}", flush=True)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def completed_part(directory, index, workers, signature):
|
| 50 |
+
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
|
| 51 |
+
if (manifest.get("status") != "complete" or manifest.get("stage") != "preprocessed_part"
|
| 52 |
+
or manifest.get("part_schema_version") != PART_SCHEMA_VERSION
|
| 53 |
+
or manifest.get("partition") != {"index": index, "count": workers}
|
| 54 |
+
or manifest.get("pipeline_signature") != signature):
|
| 55 |
+
raise ValueError(f"Completed worker has a different code/config version: {directory}")
|
| 56 |
+
for name in ("index.sqlite", "part-stats.json", *(f"{name}.jsonl" for name in AUDITS)):
|
| 57 |
+
if file_sha(directory / name) != manifest["artifact_sha256"].get(name):
|
| 58 |
+
raise ValueError(f"Worker result is damaged: {directory / name}")
|
| 59 |
+
return sum(manifest["selected_documents"].values())
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def expected_documents(inventory):
|
| 63 |
+
import pyarrow.parquet as pq
|
| 64 |
+
|
| 65 |
+
total = 0
|
| 66 |
+
for relative, source, limit in inventory:
|
| 67 |
+
path = ROOT / relative
|
| 68 |
+
if not path.is_file():
|
| 69 |
+
raise FileNotFoundError(path)
|
| 70 |
+
if source == "fineweb":
|
| 71 |
+
with pq.ParquetFile(path) as parquet:
|
| 72 |
+
count = parquet.metadata.num_rows
|
| 73 |
+
else:
|
| 74 |
+
with path.open(encoding="utf-8-sig") as stream:
|
| 75 |
+
count = sum(1 for _ in stream)
|
| 76 |
+
total += min(count, limit) if limit else count
|
| 77 |
+
return total
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def run(config_path, output=None, workers=None, resume=False, progress_seconds=10):
|
| 81 |
+
start = time.monotonic()
|
| 82 |
+
config_path = config_path.resolve()
|
| 83 |
+
config, inventory, _, _, _, _, signature = load_plan(config_path)
|
| 84 |
+
cpu_count = os.cpu_count() or 1
|
| 85 |
+
if workers is None:
|
| 86 |
+
workers = min(10, max(1, cpu_count - 1), len(inventory))
|
| 87 |
+
if type(workers) is not int or not 1 <= workers <= min(128, len(inventory)):
|
| 88 |
+
raise ValueError(f"workers must be between 1 and {min(128, len(inventory))}.")
|
| 89 |
+
if progress_seconds <= 0:
|
| 90 |
+
raise ValueError("progress_seconds must be positive.")
|
| 91 |
+
output = (ROOT / (output or config["build"]["output_dir"])).resolve()
|
| 92 |
+
work = output.with_name(output.name + "-work")
|
| 93 |
+
if not output.is_relative_to(ROOT) or output == ROOT or work == ROOT:
|
| 94 |
+
raise ValueError("Parallel output must be a directory inside the repository.")
|
| 95 |
+
planned = expected_documents(inventory)
|
| 96 |
+
run_plan = {"pipeline_signature": signature, "workers": workers, "output": str(output),
|
| 97 |
+
"expected_documents": planned, "config": str(config_path),
|
| 98 |
+
"input_snapshots": {relative: {"bytes": (ROOT / relative).stat().st_size,
|
| 99 |
+
"mtime_ns": (ROOT / relative).stat().st_mtime_ns}
|
| 100 |
+
for relative, _, _ in inventory}}
|
| 101 |
+
marker = work / "run-plan.json"
|
| 102 |
+
if work.exists() and any(work.iterdir()):
|
| 103 |
+
if not resume:
|
| 104 |
+
raise FileExistsError(f"Work directory exists: {work}; use --resume or a new --output.")
|
| 105 |
+
if not marker.is_file() or json.loads(marker.read_text(encoding="utf-8")) != run_plan:
|
| 106 |
+
raise ValueError("Resume requires the same output, workers, inputs and processing policy.")
|
| 107 |
+
else:
|
| 108 |
+
if resume:
|
| 109 |
+
raise FileNotFoundError(f"No saved parallel run to resume: {work}")
|
| 110 |
+
if output.exists() and (not output.is_dir() or any(output.iterdir())):
|
| 111 |
+
raise FileExistsError(f"Output must be absent or empty: {output}")
|
| 112 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
dump_json(marker, run_plan)
|
| 114 |
+
if output.exists() and any(output.iterdir()):
|
| 115 |
+
manifest_path = output / "manifest.json"
|
| 116 |
+
if manifest_path.is_file():
|
| 117 |
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 118 |
+
if manifest.get("status") == "complete" and manifest.get("pipeline_signature") == signature:
|
| 119 |
+
print(f"Corpus already complete: {output}", flush=True)
|
| 120 |
+
return json.loads((output / "stats.json").read_text(encoding="utf-8"))
|
| 121 |
+
raise ValueError("Existing final output does not match this parallel run.")
|
| 122 |
+
preserve_interrupted(output, ROOT)
|
| 123 |
+
parts = [work / "parts" / f"worker-{index:03d}" for index in range(workers)]
|
| 124 |
+
logs = work / "logs"
|
| 125 |
+
logs.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
processed = [0] * workers
|
| 127 |
+
reused = []
|
| 128 |
+
for index, directory in enumerate(parts):
|
| 129 |
+
if (directory / "manifest.json").is_file():
|
| 130 |
+
processed[index] = completed_part(directory, index, workers, signature)
|
| 131 |
+
reused.append(index)
|
| 132 |
+
elif directory.exists():
|
| 133 |
+
preserve_interrupted(directory, work)
|
| 134 |
+
print(f"Parallel cleaning: {workers} processes / {cpu_count} logical CPUs; {planned:,} documents", flush=True)
|
| 135 |
+
print(f"Worker logs: {logs}", flush=True)
|
| 136 |
+
if reused:
|
| 137 |
+
print(f"Reusing {len(reused)} completed workers; {sum(processed):,} documents already processed", flush=True)
|
| 138 |
+
env = os.environ.copy()
|
| 139 |
+
env.update({"PYTHONUTF8": "1", "PYTHONUNBUFFERED": "1", "OMP_NUM_THREADS": "1", "ARROW_IO_THREADS": "1"})
|
| 140 |
+
children = {}
|
| 141 |
+
pids = {}
|
| 142 |
+
merge_process = None
|
| 143 |
+
try:
|
| 144 |
+
with ExitStack() as stack:
|
| 145 |
+
for index, directory in enumerate(parts):
|
| 146 |
+
if index in reused:
|
| 147 |
+
continue
|
| 148 |
+
log = stack.enter_context((logs / f"worker-{index:03d}.log").open("wb"))
|
| 149 |
+
child = subprocess.Popen([sys.executable, "-X", "utf8", str(ROOT / "src/vimeml/data/preprocess_part.py"),
|
| 150 |
+
"--config", str(config_path), "--part", f"{index}/{workers}", "--output", str(directory)],
|
| 151 |
+
cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)
|
| 152 |
+
children[index] = child
|
| 153 |
+
pids[str(index)] = child.pid
|
| 154 |
+
pending = set(children)
|
| 155 |
+
next_progress = 0.0
|
| 156 |
+
while pending:
|
| 157 |
+
for index in list(pending):
|
| 158 |
+
child = children[index]
|
| 159 |
+
code = child.poll()
|
| 160 |
+
for match in re.finditer(r"read (\d+) document origins", tail(logs / f"worker-{index:03d}.log")):
|
| 161 |
+
processed[index] = max(processed[index], int(match[1]))
|
| 162 |
+
if code is None:
|
| 163 |
+
continue
|
| 164 |
+
if code != 0:
|
| 165 |
+
raise RuntimeError(f"Worker {index} failed (exit {code}). See {logs / f'worker-{index:03d}.log'}\n{tail(logs / f'worker-{index:03d}.log', 2500)}")
|
| 166 |
+
# Full checksums are verified by merge; read the success count now.
|
| 167 |
+
manifest = json.loads((parts[index] / "manifest.json").read_text(encoding="utf-8"))
|
| 168 |
+
processed[index] = sum(manifest["selected_documents"].values())
|
| 169 |
+
pending.remove(index)
|
| 170 |
+
now = time.monotonic()
|
| 171 |
+
if now >= next_progress or not pending:
|
| 172 |
+
total = sum(processed)
|
| 173 |
+
print(f"[cleaning] {total:,}/{planned:,} ({total/max(1,planned):.1%}); "
|
| 174 |
+
f"running={len(pending)}; completed={workers-len(pending)}/{workers}; elapsed={elapsed_text(now-start)}", flush=True)
|
| 175 |
+
next_progress = now + progress_seconds
|
| 176 |
+
if pending:
|
| 177 |
+
time.sleep(0.25)
|
| 178 |
+
preprocess_seconds = time.monotonic() - start
|
| 179 |
+
print("[merge] All cleaning workers completed. Global deduplication and export now run in one process.", flush=True)
|
| 180 |
+
log = stack.enter_context((logs / "merge.log").open("wb"))
|
| 181 |
+
merge_work = work / "merge"
|
| 182 |
+
if merge_work.exists() and any(merge_work.iterdir()):
|
| 183 |
+
preserve_interrupted(merge_work, work)
|
| 184 |
+
merge_process = subprocess.Popen([sys.executable, "-X", "utf8", str(ROOT / "scripts/corpus/merge.py"),
|
| 185 |
+
"--config", str(config_path), "--parts", *(str(p) for p in parts),
|
| 186 |
+
"--output", str(output), "--work", str(merge_work),
|
| 187 |
+
"--workers", str(min(workers, 8))],
|
| 188 |
+
cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT)
|
| 189 |
+
next_progress = 0.0
|
| 190 |
+
last_message = ""
|
| 191 |
+
while merge_process.poll() is None:
|
| 192 |
+
now = time.monotonic()
|
| 193 |
+
if now >= next_progress:
|
| 194 |
+
messages = [line for line in tail(logs / "merge.log").splitlines() if line.startswith(("Validating", "[fast-merge "))]
|
| 195 |
+
if messages:
|
| 196 |
+
last_message = messages[-1]
|
| 197 |
+
print(f"[merge] elapsed={elapsed_text(now-start)}; {last_message or 'Starting merge'}", flush=True)
|
| 198 |
+
next_progress = now + progress_seconds
|
| 199 |
+
time.sleep(0.25)
|
| 200 |
+
if merge_process.returncode:
|
| 201 |
+
raise RuntimeError(f"Merge failed (exit {merge_process.returncode}). See {logs / 'merge.log'}\n{tail(logs / 'merge.log', 2500)}")
|
| 202 |
+
stats = json.loads((output / "stats.json").read_text(encoding="utf-8"))
|
| 203 |
+
dump_json(work / "run-summary.json", {
|
| 204 |
+
"status": "complete", "workers": workers, "worker_pids": pids, "reused_workers": reused,
|
| 205 |
+
"document_origins": stats["document_origins"], "preprocess_seconds": round(preprocess_seconds, 3),
|
| 206 |
+
"total_seconds": round(time.monotonic()-start, 3), "output": str(output),
|
| 207 |
+
})
|
| 208 |
+
print(f"Complete: {stats['document_origins']:,} documents; {stats['unique_sentences']:,} unique sentences; "
|
| 209 |
+
f"elapsed={elapsed_text(time.monotonic()-start)}\nCorpus: {output}", flush=True)
|
| 210 |
+
return stats
|
| 211 |
+
except BaseException:
|
| 212 |
+
for child in [*children.values(), merge_process]:
|
| 213 |
+
if child is not None and child.poll() is None:
|
| 214 |
+
child.terminate()
|
| 215 |
+
for child in [*children.values(), merge_process]:
|
| 216 |
+
if child is not None and child.poll() is None:
|
| 217 |
+
try:
|
| 218 |
+
child.wait(timeout=5)
|
| 219 |
+
except subprocess.TimeoutExpired:
|
| 220 |
+
child.kill()
|
| 221 |
+
child.wait()
|
| 222 |
+
print(f"Run stopped. Completed workers are retained; retry with --resume. Logs: {logs}", flush=True)
|
| 223 |
+
raise
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def main():
|
| 227 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 228 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/corpus-parallel.toml")
|
| 229 |
+
parser.add_argument("--output", help="Final corpus directory; intermediate files use OUTPUT-work.")
|
| 230 |
+
parser.add_argument("--workers", type=int, help="Default: up to 10 processes, limited by CPUs and input files.")
|
| 231 |
+
parser.add_argument("--resume", action="store_true", help="Reuse completed workers from this parallel run.")
|
| 232 |
+
parser.add_argument("--progress-seconds", type=float, default=10)
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
try:
|
| 235 |
+
run(args.config, args.output, args.workers, args.resume, args.progress_seconds)
|
| 236 |
+
except KeyboardInterrupt:
|
| 237 |
+
raise SystemExit(130) from None
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
if __name__ == "__main__":
|
| 241 |
+
main()
|
source/src/vimeml/corpus/zh_filter.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage-A rules for the Chinese web corpus (FineWeb2 cmn_Hani).
|
| 2 |
+
|
| 3 |
+
Each document gets one decision:
|
| 4 |
+
|
| 5 |
+
drop blocked TLD, tier-1 domain, gambling pinyin in the host, a fake government host
|
| 6 |
+
(x.gov.cn.spam.cn), a content-term hit, too little Chinese text, or mostly repeated lines
|
| 7 |
+
review tier-2 domain, or a single weak term; kept in full for human review
|
| 8 |
+
keep everything else
|
| 9 |
+
|
| 10 |
+
Traditional-script pages are converted to Simplified with OpenCC `tw2sp` (characters
|
| 11 |
+
and Taiwan phrasing, e.g. 軟體 -> 软件) and tagged `script='hant'`. Term lists and
|
| 12 |
+
domains come from configs/zh-filter-terms.toml; matching runs on the converted text,
|
| 13 |
+
lower-cased for Latin letters.
|
| 14 |
+
"""
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from functools import lru_cache
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import re
|
| 19 |
+
import tomllib
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
HAN=re.compile(r'[㐀-䶿一-鿿豈-]')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass(frozen=True)
|
| 26 |
+
class Rules:
|
| 27 |
+
pattern: re.Pattern
|
| 28 |
+
category: dict
|
| 29 |
+
weak: frozenset
|
| 30 |
+
tlds: frozenset
|
| 31 |
+
tier1: tuple
|
| 32 |
+
tier2: tuple
|
| 33 |
+
host_terms: tuple=()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_rules(path):
|
| 37 |
+
spec=tomllib.loads(Path(path).read_text(encoding='utf-8'))
|
| 38 |
+
category={}
|
| 39 |
+
for cat,terms in spec['categories'].items():
|
| 40 |
+
for t in terms:
|
| 41 |
+
category.setdefault(t.lower(),cat)
|
| 42 |
+
weak=frozenset(t.lower() for t in spec.get('rules',{}).get('weak',[]))
|
| 43 |
+
unknown=weak-set(category)
|
| 44 |
+
if unknown:
|
| 45 |
+
raise ValueError(f'weak terms missing from every category: {sorted(unknown)}')
|
| 46 |
+
terms=sorted(category,key=len,reverse=True)
|
| 47 |
+
domains=spec.get('domains',{})
|
| 48 |
+
return Rules(pattern=re.compile('|'.join(map(re.escape,terms))),category=category,weak=weak,
|
| 49 |
+
tlds=frozenset(domains.get('block_tlds',[])),tier1=tuple(domains.get('block',[])),
|
| 50 |
+
tier2=tuple(domains.get('block_tier2',[])),host_terms=tuple(domains.get('host_terms',[])))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def in_domains(host,domains):
|
| 54 |
+
return any(host==d or host.endswith('.'+d) for d in domains)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def term_hits(text,rules):
|
| 58 |
+
"""Distinct terms found in `text` (already lower-cased), grouped by category."""
|
| 59 |
+
found={}
|
| 60 |
+
for m in rules.pattern.finditer(text):
|
| 61 |
+
t=m.group(0)
|
| 62 |
+
found.setdefault(rules.category[t],set()).add(t)
|
| 63 |
+
return {c:sorted(ts) for c,ts in found.items()}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def counts_as_hit(hits,weak):
|
| 67 |
+
"""A document hits when it contains a non-weak term, or two different terms."""
|
| 68 |
+
found={t for ts in hits.values() for t in ts}
|
| 69 |
+
return bool(found-weak) or len(found)>=2
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@lru_cache(maxsize=1)
|
| 73 |
+
def _converters():
|
| 74 |
+
import opencc
|
| 75 |
+
return opencc.OpenCC('t2s'),opencc.OpenCC('tw2sp')
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@lru_cache(maxsize=1)
|
| 79 |
+
def traditional_chars():
|
| 80 |
+
"""CJK characters that OpenCC t2s maps to a different character."""
|
| 81 |
+
t2s,_=_converters()
|
| 82 |
+
chars=[chr(c) for r in ((0x3400,0x4dc0),(0x4e00,0xa000),(0xf900,0xfb00)) for c in range(*r)]
|
| 83 |
+
out=t2s.convert(''.join(chars))
|
| 84 |
+
return frozenset(a for a,b in zip(chars,out) if a!=b)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def traditional_ratio(han):
|
| 88 |
+
trad=traditional_chars()
|
| 89 |
+
return sum(c in trad for c in han)/max(1,len(han))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def to_simplified(text):
|
| 93 |
+
return _converters()[1].convert(text)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def repeated_line_fraction(text):
|
| 97 |
+
"""Share of non-blank line characters that sit in lines occurring more than once."""
|
| 98 |
+
lines=[l.strip() for l in text.split('\n')]
|
| 99 |
+
lines=[l for l in lines if l]
|
| 100 |
+
total=sum(map(len,lines))
|
| 101 |
+
if not total:
|
| 102 |
+
return 0.0
|
| 103 |
+
counts={}
|
| 104 |
+
for l in lines:
|
| 105 |
+
counts[l]=counts.get(l,0)+1
|
| 106 |
+
return sum(len(l)*n for l,n in counts.items() if n>1)/total
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass(frozen=True)
|
| 110 |
+
class Thresholds:
|
| 111 |
+
min_han: int=100
|
| 112 |
+
min_han_share: float=0.4
|
| 113 |
+
max_repeated_lines: float=0.3
|
| 114 |
+
traditional: float=0.08
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def classify(text,host,rules,th=Thresholds()):
|
| 118 |
+
"""Return the converted text and the stage-A decision for one document."""
|
| 119 |
+
han=HAN.findall(text)
|
| 120 |
+
script='hans'
|
| 121 |
+
if traditional_ratio(han)>th.traditional:
|
| 122 |
+
text=to_simplified(text); script='hant'
|
| 123 |
+
lower=text.lower()
|
| 124 |
+
hits=term_hits(lower,rules)
|
| 125 |
+
drop=[]; review=[]
|
| 126 |
+
tld=host.rsplit('.',1)[-1]
|
| 127 |
+
if tld in rules.tlds: drop.append('tld')
|
| 128 |
+
if in_domains(host,rules.tier1): drop.append('domain_tier1')
|
| 129 |
+
if not host.endswith(('.gov.cn','.edu.cn')) and any(k in host for k in rules.host_terms):
|
| 130 |
+
drop.append('host_term')
|
| 131 |
+
if ('.gov.cn.' in host or '.edu.cn.' in host) and not host.endswith(('.gov.cn','.edu.cn')):
|
| 132 |
+
drop.append('fake_gov')
|
| 133 |
+
if hits:
|
| 134 |
+
if counts_as_hit(hits,rules.weak): drop.extend(f'term_{c}' for c in sorted(hits))
|
| 135 |
+
else: review.append('weak_term')
|
| 136 |
+
if in_domains(host,rules.tier2): review.append('domain_tier2')
|
| 137 |
+
nonspace=sum(not c.isspace() for c in text)
|
| 138 |
+
if len(han)<th.min_han: drop.append('short')
|
| 139 |
+
elif len(han)<th.min_han_share*nonspace: drop.append('low_han')
|
| 140 |
+
if repeated_line_fraction(text)>th.max_repeated_lines: drop.append('repetitive')
|
| 141 |
+
decision='drop' if drop else 'review' if review else 'keep'
|
| 142 |
+
return dict(text=text,script=script,decision=decision,reasons=drop+review,
|
| 143 |
+
hits=[t for ts in hits.values() for t in ts],han=len(han))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
SECOND_LEVEL=('com','net','org','gov','edu','ac')
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def registrable(host):
|
| 150 |
+
"""example.com, example.com.cn: the last two labels, or three under com/net/... + ccTLD."""
|
| 151 |
+
parts=host.split('.')
|
| 152 |
+
if len(parts)>=3 and len(parts[-1])==2 and parts[-2] in SECOND_LEVEL:
|
| 153 |
+
return '.'.join(parts[-3:])
|
| 154 |
+
return '.'.join(parts[-2:])
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def random_looking(label):
|
| 158 |
+
"""Letters and digits interleaved at least twice (u07bgqr7k, hc28hpjs, kzlue2y).
|
| 159 |
+
|
| 160 |
+
Ordinary Chinese site names often carry one number block (lady8844, it168, 51cto,
|
| 161 |
+
3dmgame); those switch between letters and digits only once.
|
| 162 |
+
"""
|
| 163 |
+
kinds=[c.isdigit() for c in label if c.isalnum()]
|
| 164 |
+
switches=sum(a!=b for a,b in zip(kinds,kinds[1:]))
|
| 165 |
+
return len(label)>=5 and switches>=2
|
source/src/vimeml/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""VimeML data utilities."""
|
source/src/vimeml/data/annotations.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validated, locally approved corpus decisions; model replies alone are advisory."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import sqlite3
|
| 7 |
+
|
| 8 |
+
from vimeml.data.segment import LIST_ITEM, split_sentences
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_annotations(db, path):
|
| 12 |
+
db.executescript("""
|
| 13 |
+
CREATE TABLE annotations (
|
| 14 |
+
id TEXT PRIMARY KEY, doc_hash TEXT NOT NULL, target TEXT NOT NULL UNIQUE, payload TEXT NOT NULL,
|
| 15 |
+
matched INTEGER NOT NULL DEFAULT 0
|
| 16 |
+
);
|
| 17 |
+
CREATE INDEX annotations_document ON annotations(doc_hash);
|
| 18 |
+
""")
|
| 19 |
+
if path is None:
|
| 20 |
+
return 0
|
| 21 |
+
count = 0
|
| 22 |
+
with path.open(encoding="utf-8-sig") as stream:
|
| 23 |
+
for line_number, line in enumerate(stream, 1):
|
| 24 |
+
item = json.loads(line)
|
| 25 |
+
if not isinstance(item, dict):
|
| 26 |
+
raise ValueError(f"Annotation line {line_number}: expected an object.")
|
| 27 |
+
if item.get("schema_version") != 1 or item.get("status") != "approved":
|
| 28 |
+
raise ValueError(f"Annotation line {line_number}: only approved v1 records are accepted.")
|
| 29 |
+
if item.get("approved_by") not in {"human", "assistant"}:
|
| 30 |
+
raise ValueError("Annotations require an explicit human/assistant review.")
|
| 31 |
+
if not isinstance(item.get("id"), str) or not item["id"] or not isinstance(item.get("doc_id"), str):
|
| 32 |
+
raise ValueError("Annotation identity is missing.")
|
| 33 |
+
if not isinstance(item.get("doc_hash"), str) or not re.fullmatch(r"[0-9a-f]{64}", item["doc_hash"]):
|
| 34 |
+
raise ValueError("Invalid annotation document hash.")
|
| 35 |
+
if not isinstance(item.get("reason_zh"), str) or not item["reason_zh"].strip():
|
| 36 |
+
raise ValueError("Annotation approval reason is missing.")
|
| 37 |
+
kind, action = item.get("kind"), item.get("action")
|
| 38 |
+
if kind == "boundary" and action in {"join", "separate"}:
|
| 39 |
+
fields = ("left_block", "right_block", "left_text", "right_text")
|
| 40 |
+
target = (item["doc_hash"], kind, item.get("left_block"), item.get("right_block"))
|
| 41 |
+
elif kind == "block" and action in {"keep", "drop", "review"}:
|
| 42 |
+
fields = ("block_id", "text")
|
| 43 |
+
target = (item["doc_hash"], kind, item.get("block_id"))
|
| 44 |
+
elif kind == "fragment" and action in {"keep", "drop", "review"}:
|
| 45 |
+
fields = ("text", "text_hash")
|
| 46 |
+
spans = item.get("cleaned_block_spans")
|
| 47 |
+
if not isinstance(spans, list) or not spans:
|
| 48 |
+
raise ValueError("Fragment annotation requires cleaned-block spans.")
|
| 49 |
+
for span in spans:
|
| 50 |
+
if not isinstance(span, dict) or not re.fullmatch(r"b[0-9]+", str(span.get("block_id", ""))) or type(span.get("start")) is not int or type(span.get("end")) is not int or not 0 <= span["start"] < span["end"]:
|
| 51 |
+
raise ValueError("Invalid fragment span.")
|
| 52 |
+
if any(not isinstance(item.get(field), str) or not item[field] for field in fields):
|
| 53 |
+
raise ValueError("Fragment annotation snapshot is missing.")
|
| 54 |
+
if hashlib.sha256(item["text"].encode("utf-8")).hexdigest() != item["text_hash"]:
|
| 55 |
+
raise ValueError("Fragment annotation text hash mismatch.")
|
| 56 |
+
target = (item["doc_hash"], kind, item["text_hash"], json.dumps(spans, sort_keys=True))
|
| 57 |
+
else:
|
| 58 |
+
raise ValueError("Unknown annotation kind/action.")
|
| 59 |
+
if any(not isinstance(item.get(field), str) or not item[field] for field in fields):
|
| 60 |
+
raise ValueError("Annotation snapshot is missing.")
|
| 61 |
+
try:
|
| 62 |
+
db.execute("INSERT INTO annotations(id,doc_hash,target,payload) VALUES (?,?,?,?)", (
|
| 63 |
+
item["id"], item["doc_hash"], json.dumps(target, sort_keys=True), json.dumps(item, ensure_ascii=False),
|
| 64 |
+
))
|
| 65 |
+
except sqlite3.IntegrityError:
|
| 66 |
+
raise ValueError("Conflicting or duplicated annotation target/ID.") from None
|
| 67 |
+
count += 1
|
| 68 |
+
return count
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def document_annotations(db, doc_hash, blocks):
|
| 72 |
+
items = [json.loads(row[0]) for row in db.execute(
|
| 73 |
+
"SELECT payload FROM annotations WHERE doc_hash=? ORDER BY id", (doc_hash,)
|
| 74 |
+
)]
|
| 75 |
+
by_id = {block["id"]: block for block in blocks}
|
| 76 |
+
boundaries, fragments, block_ids = {}, [], {}
|
| 77 |
+
for item in items:
|
| 78 |
+
if item["kind"] == "fragment":
|
| 79 |
+
fragments.append(item)
|
| 80 |
+
continue
|
| 81 |
+
fields = (("left_block", "left_text"), ("right_block", "right_text")) if item["kind"] == "boundary" else (("block_id", "text"),)
|
| 82 |
+
for id_field, text_field in fields:
|
| 83 |
+
block = by_id.get(item[id_field])
|
| 84 |
+
if block is None or block["text"] != item[text_field]:
|
| 85 |
+
raise ValueError(f"Annotation {item['id']}: cleaned block snapshot mismatch.")
|
| 86 |
+
if item["kind"] == "block":
|
| 87 |
+
block = by_id[item["block_id"]]
|
| 88 |
+
if item["action"] == "keep" and block["action"] != "keep":
|
| 89 |
+
raise ValueError("Rule-quarantined or dropped blocks cannot be rescued by a keep label.")
|
| 90 |
+
block["action"] = item["action"]
|
| 91 |
+
block_ids[item["block_id"]] = item["id"]
|
| 92 |
+
# Check boundaries after all block labels have been applied.
|
| 93 |
+
for item in items:
|
| 94 |
+
if item["kind"] != "boundary":
|
| 95 |
+
continue
|
| 96 |
+
left, right = by_id[item["left_block"]], by_id[item["right_block"]]
|
| 97 |
+
if right["line_index"] != left["line_index"] + 1:
|
| 98 |
+
raise ValueError("Reviewed boundaries must be between adjacent original lines.")
|
| 99 |
+
if item["action"] == "join" and (
|
| 100 |
+
any(block["action"] != "keep" or not block["text"] or LIST_ITEM.match(block["text"]) for block in (left, right))
|
| 101 |
+
or split_sentences(left["text"])[-1]["terminated"]
|
| 102 |
+
):
|
| 103 |
+
raise ValueError(f"Annotation {item['id']}: join crosses a protected boundary.")
|
| 104 |
+
boundaries[(item["left_block"], item["right_block"])] = item
|
| 105 |
+
for item in items:
|
| 106 |
+
if item["kind"] != "fragment":
|
| 107 |
+
db.execute("UPDATE annotations SET matched=1 WHERE id=?", (item["id"],))
|
| 108 |
+
return boundaries, fragments, block_ids
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def match_fragment(db, labels, text, spans):
|
| 112 |
+
matched = [item for item in labels if item["text"] == text and item["cleaned_block_spans"] == spans]
|
| 113 |
+
if len(matched) > 1:
|
| 114 |
+
raise ValueError("Multiple fragment annotations matched one output.")
|
| 115 |
+
if not matched:
|
| 116 |
+
return None
|
| 117 |
+
item = matched[0]
|
| 118 |
+
db.execute("UPDATE annotations SET matched=1 WHERE id=?", (item["id"],))
|
| 119 |
+
return item
|
source/src/vimeml/data/build.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a reproducible Japanese corpus, optionally applying approved local labels."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import sqlite3
|
| 8 |
+
import sys
|
| 9 |
+
import tomllib
|
| 10 |
+
import unicodedata
|
| 11 |
+
from collections import Counter
|
| 12 |
+
from contextlib import ExitStack, closing
|
| 13 |
+
from itertools import islice
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from urllib.parse import urlsplit, urlunsplit
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 18 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 19 |
+
|
| 20 |
+
from vimeml.data.clean import clean_block
|
| 21 |
+
from vimeml.data.readers import iter_fineweb, iter_tatoeba
|
| 22 |
+
from vimeml.data.segment import restore_linebreaks, split_sentences
|
| 23 |
+
from vimeml.data.annotations import load_annotations, document_annotations, match_fragment
|
| 24 |
+
|
| 25 |
+
SPLITS = ("train", "validation", "test")
|
| 26 |
+
|
| 27 |
+
SCHEMA = """
|
| 28 |
+
CREATE TABLE parents (key TEXT PRIMARY KEY, parent TEXT NOT NULL);
|
| 29 |
+
CREATE TABLE aliases (key TEXT PRIMARY KEY, doc_hash TEXT NOT NULL);
|
| 30 |
+
CREATE TABLE contents (
|
| 31 |
+
doc_hash TEXT PRIMARY KEY, group_id TEXT, split_rank INTEGER
|
| 32 |
+
);
|
| 33 |
+
CREATE TABLE origins (
|
| 34 |
+
doc_hash TEXT NOT NULL, doc_id TEXT NOT NULL, source TEXT NOT NULL,
|
| 35 |
+
source_file TEXT NOT NULL, row_index INTEGER NOT NULL, info TEXT NOT NULL,
|
| 36 |
+
PRIMARY KEY (source_file, row_index)
|
| 37 |
+
);
|
| 38 |
+
CREATE INDEX origins_content ON origins(doc_hash);
|
| 39 |
+
CREATE INDEX origins_identity ON origins(doc_id);
|
| 40 |
+
CREATE TABLE units (
|
| 41 |
+
doc_hash TEXT NOT NULL, text_hash TEXT NOT NULL, text TEXT NOT NULL,
|
| 42 |
+
paragraph_index INTEGER NOT NULL, sentence_index INTEGER NOT NULL,
|
| 43 |
+
spans TEXT NOT NULL, annotation_ids TEXT NOT NULL,
|
| 44 |
+
PRIMARY KEY (doc_hash, paragraph_index, sentence_index)
|
| 45 |
+
);
|
| 46 |
+
CREATE INDEX units_text ON units(text_hash);
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
WINNERS = """
|
| 50 |
+
CREATE TABLE winners AS
|
| 51 |
+
SELECT u.text_hash, MAX(c.split_rank) AS split_rank,
|
| 52 |
+
GROUP_CONCAT(DISTINCT o.source) AS sources
|
| 53 |
+
FROM units u
|
| 54 |
+
JOIN contents c ON c.doc_hash = u.doc_hash
|
| 55 |
+
JOIN origins o ON o.doc_hash = u.doc_hash
|
| 56 |
+
GROUP BY u.text_hash;
|
| 57 |
+
CREATE UNIQUE INDEX winners_text ON winners(text_hash);
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
PRIMARY_ROWS = """
|
| 61 |
+
WITH ranked AS (
|
| 62 |
+
SELECT u.*, o.doc_id, o.source, o.source_file, o.row_index,
|
| 63 |
+
c.group_id, w.split_rank, w.sources,
|
| 64 |
+
ROW_NUMBER() OVER (
|
| 65 |
+
PARTITION BY u.text_hash
|
| 66 |
+
ORDER BY CASE o.source WHEN 'tatoeba' THEN 0 ELSE 1 END,
|
| 67 |
+
o.doc_id, o.source_file, o.row_index,
|
| 68 |
+
u.paragraph_index, u.sentence_index
|
| 69 |
+
) AS preference
|
| 70 |
+
FROM units u
|
| 71 |
+
JOIN contents c ON c.doc_hash = u.doc_hash
|
| 72 |
+
JOIN origins o ON o.doc_hash = u.doc_hash
|
| 73 |
+
JOIN winners w ON w.text_hash = u.text_hash
|
| 74 |
+
WHERE c.split_rank = w.split_rank
|
| 75 |
+
)
|
| 76 |
+
SELECT * FROM ranked WHERE preference = 1 ORDER BY text_hash;
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def sha(text):
|
| 81 |
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def file_sha(path):
|
| 85 |
+
digest = hashlib.sha256()
|
| 86 |
+
with path.open("rb") as stream:
|
| 87 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 88 |
+
digest.update(chunk)
|
| 89 |
+
return digest.hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def display_path(path):
|
| 93 |
+
path = path.resolve()
|
| 94 |
+
return path.relative_to(ROOT).as_posix() if path.is_relative_to(ROOT) else str(path)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def dump_line(stream, value):
|
| 98 |
+
stream.write(json.dumps(value, ensure_ascii=False, allow_nan=False) + "\n")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def dump_json(path, value):
|
| 102 |
+
path.write_text(
|
| 103 |
+
json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n",
|
| 104 |
+
encoding="utf-8",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def canonical_url(value):
|
| 109 |
+
if not isinstance(value, str):
|
| 110 |
+
return None
|
| 111 |
+
try:
|
| 112 |
+
parts = urlsplit(value.strip())
|
| 113 |
+
if parts.scheme.lower() not in {"http", "https"} or not parts.netloc:
|
| 114 |
+
return None
|
| 115 |
+
# Keep the query and path; remove only the fragment, lowercase host.
|
| 116 |
+
return urlunsplit((
|
| 117 |
+
parts.scheme.lower(), parts.netloc.lower(),
|
| 118 |
+
parts.path or "/", parts.query, "",
|
| 119 |
+
))
|
| 120 |
+
except ValueError:
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def find(db, key):
|
| 125 |
+
trail = []
|
| 126 |
+
while True:
|
| 127 |
+
parent = db.execute(
|
| 128 |
+
"SELECT parent FROM parents WHERE key = ?", (key,)
|
| 129 |
+
).fetchone()[0]
|
| 130 |
+
if parent == key:
|
| 131 |
+
break
|
| 132 |
+
trail.append(key)
|
| 133 |
+
key = parent
|
| 134 |
+
for item in trail:
|
| 135 |
+
db.execute("UPDATE parents SET parent = ? WHERE key = ?", (key, item))
|
| 136 |
+
return key
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def attach_alias(db, doc_hash, alias):
|
| 140 |
+
previous = db.execute(
|
| 141 |
+
"SELECT doc_hash FROM aliases WHERE key = ?", (alias,)
|
| 142 |
+
).fetchone()
|
| 143 |
+
if previous is None:
|
| 144 |
+
db.execute("INSERT INTO aliases VALUES (?, ?)", (alias, doc_hash))
|
| 145 |
+
return
|
| 146 |
+
left, right = find(db, doc_hash), find(db, previous[0])
|
| 147 |
+
if left != right:
|
| 148 |
+
root, child = sorted((left, right))
|
| 149 |
+
db.execute("UPDATE parents SET parent = ? WHERE key = ?", (root, child))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def validate(config):
|
| 153 |
+
if config["build"]["quality_mode"] not in {"rules_only", "rules_with_approved_annotations"}:
|
| 154 |
+
raise ValueError("Unknown quality_mode.")
|
| 155 |
+
if config["build"]["quality_mode"] == "rules_with_approved_annotations" and not config.get("review", {}).get("annotations"):
|
| 156 |
+
raise ValueError("Approved-annotation mode requires a local annotations JSONL.")
|
| 157 |
+
ratios = [config["split"][name] for name in SPLITS]
|
| 158 |
+
if (
|
| 159 |
+
any(isinstance(x, bool) or not isinstance(x, (int, float))
|
| 160 |
+
or not math.isfinite(x) or x <= 0 for x in ratios)
|
| 161 |
+
or not math.isclose(sum(ratios), 1.0, abs_tol=1e-9)
|
| 162 |
+
):
|
| 163 |
+
raise ValueError("Split ratios must be positive and sum to 1.")
|
| 164 |
+
for key in ("fineweb_documents_per_shard", "tatoeba_documents"):
|
| 165 |
+
value = config["build"][key]
|
| 166 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
| 167 |
+
raise ValueError(f"{key} must be a nonnegative integer; 0 means all.")
|
| 168 |
+
for key in ("batch_size", "max_join_chars"):
|
| 169 |
+
value = config["build"][key]
|
| 170 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
| 171 |
+
raise ValueError(f"{key} must be a positive integer.")
|
| 172 |
+
seed = config["build"]["seed"]
|
| 173 |
+
if isinstance(seed, bool) or not isinstance(seed, int):
|
| 174 |
+
raise ValueError("seed must be an integer.")
|
| 175 |
+
for key in ("commit_every", "progress_every"):
|
| 176 |
+
value = config["build"].get(key, 200)
|
| 177 |
+
if type(value) is not int or value < 1:
|
| 178 |
+
raise ValueError(f"{key} must be a positive integer.")
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def run(config_path, output_override=None):
|
| 182 |
+
config_path = config_path.resolve()
|
| 183 |
+
config = tomllib.loads(config_path.read_text(encoding="utf-8-sig"))
|
| 184 |
+
validate(config)
|
| 185 |
+
settings = config["build"]
|
| 186 |
+
files = sorted(ROOT.glob(config["inputs"]["fineweb_glob"]))
|
| 187 |
+
if not files:
|
| 188 |
+
raise FileNotFoundError("No FineWeb2 parquet inputs found.")
|
| 189 |
+
tatoeba = (ROOT / config["inputs"]["tatoeba_path"]).resolve()
|
| 190 |
+
if not tatoeba.is_file():
|
| 191 |
+
raise FileNotFoundError(tatoeba)
|
| 192 |
+
|
| 193 |
+
calibration_ids = set()
|
| 194 |
+
calibration_path = config["inputs"].get("calibration_review")
|
| 195 |
+
calibration_file = (ROOT / calibration_path).resolve() if calibration_path else None
|
| 196 |
+
if calibration_file:
|
| 197 |
+
reviews = json.loads(calibration_file.read_text(encoding="utf-8"))
|
| 198 |
+
calibration_ids = {
|
| 199 |
+
f"{item['source']}:{item['id']}" for item in reviews
|
| 200 |
+
}
|
| 201 |
+
calibration_files = [(ROOT / value).resolve() for value in config["inputs"].get("calibration_cases", [])]
|
| 202 |
+
for path in calibration_files:
|
| 203 |
+
cases = json.loads(path.read_text(encoding="utf-8"))
|
| 204 |
+
calibration_ids.update(item["doc_id"] for item in cases)
|
| 205 |
+
annotation_file = None
|
| 206 |
+
if settings["quality_mode"] == "rules_with_approved_annotations":
|
| 207 |
+
annotation_file = (ROOT / config["review"]["annotations"]).resolve()
|
| 208 |
+
if not annotation_file.is_file():
|
| 209 |
+
raise FileNotFoundError(annotation_file)
|
| 210 |
+
|
| 211 |
+
tracked_files = files + [tatoeba, config_path] + ([calibration_file] if calibration_file else []) + calibration_files + ([annotation_file] if annotation_file else [])
|
| 212 |
+
code_files = [Path(__file__).resolve()] + [ROOT / f"src/vimeml/data/{name}.py" for name in ("readers", "clean", "segment", "annotations")]
|
| 213 |
+
tracked_files += code_files
|
| 214 |
+
snapshots = {path: (path.stat().st_size, path.stat().st_mtime_ns) for path in tracked_files}
|
| 215 |
+
# Small policy/code files are fingerprinted before processing as well.
|
| 216 |
+
initial_hashes = {path: file_sha(path) for path in tracked_files if path not in files + [tatoeba]}
|
| 217 |
+
|
| 218 |
+
output = (ROOT / (output_override or settings["output_dir"])).resolve()
|
| 219 |
+
# Refuse to overwrite any earlier build, including an interrupted one.
|
| 220 |
+
if output.exists() and (not output.is_dir() or any(output.iterdir())):
|
| 221 |
+
raise FileExistsError(f"Output must be absent or empty: {output}")
|
| 222 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 223 |
+
|
| 224 |
+
counts = Counter()
|
| 225 |
+
rule_reasons = Counter()
|
| 226 |
+
fragment_flags = Counter()
|
| 227 |
+
selected_documents = Counter()
|
| 228 |
+
|
| 229 |
+
with ExitStack() as stack:
|
| 230 |
+
db = sqlite3.connect(output / "index.sqlite")
|
| 231 |
+
stack.callback(db.close)
|
| 232 |
+
db.row_factory = sqlite3.Row
|
| 233 |
+
db.execute("PRAGMA temp_store = FILE")
|
| 234 |
+
db.executescript(SCHEMA)
|
| 235 |
+
annotation_count = load_annotations(db, annotation_file)
|
| 236 |
+
effective_blocks = Counter()
|
| 237 |
+
audits = {
|
| 238 |
+
name: stack.enter_context(
|
| 239 |
+
(output / f"{name}.jsonl").open("w", encoding="utf-8", newline="\n")
|
| 240 |
+
)
|
| 241 |
+
for name in ("review_blocks", "dropped_blocks", "fragments")
|
| 242 |
+
}
|
| 243 |
+
inputs = [
|
| 244 |
+
(path, "fineweb", settings["fineweb_documents_per_shard"])
|
| 245 |
+
for path in files
|
| 246 |
+
]
|
| 247 |
+
inputs.append((tatoeba, "tatoeba", settings["tatoeba_documents"]))
|
| 248 |
+
|
| 249 |
+
for path, source, limit in inputs:
|
| 250 |
+
reader = (
|
| 251 |
+
iter_fineweb(path, settings["batch_size"])
|
| 252 |
+
if source == "fineweb" else iter_tatoeba(path)
|
| 253 |
+
)
|
| 254 |
+
with closing(reader):
|
| 255 |
+
documents = islice(reader, limit) if limit else reader
|
| 256 |
+
for document in documents:
|
| 257 |
+
counts["document_origins"] += 1
|
| 258 |
+
counts["raw_characters"] += len(document.text)
|
| 259 |
+
selected_documents[document.source_file] += 1
|
| 260 |
+
normalized = unicodedata.normalize(
|
| 261 |
+
"NFC", document.text.replace("\r\n", "\n").replace("\r", "\n")
|
| 262 |
+
).lstrip("\ufeff")
|
| 263 |
+
doc_hash = sha(normalized)
|
| 264 |
+
first = db.execute(
|
| 265 |
+
"INSERT OR IGNORE INTO contents(doc_hash) VALUES (?)",
|
| 266 |
+
(doc_hash,),
|
| 267 |
+
).rowcount == 1
|
| 268 |
+
db.execute(
|
| 269 |
+
"INSERT OR IGNORE INTO parents VALUES (?, ?)",
|
| 270 |
+
(doc_hash, doc_hash),
|
| 271 |
+
)
|
| 272 |
+
attach_alias(db, doc_hash, "id:" + document.doc_id)
|
| 273 |
+
url = canonical_url(document.metadata.get("url"))
|
| 274 |
+
if url:
|
| 275 |
+
attach_alias(db, doc_hash, "url:" + url)
|
| 276 |
+
identity = {
|
| 277 |
+
"source": document.source, "doc_id": document.doc_id,
|
| 278 |
+
"source_id": document.source_id,
|
| 279 |
+
"source_file": document.source_file,
|
| 280 |
+
"row_index": document.row_index, "doc_hash": doc_hash,
|
| 281 |
+
"metadata": document.metadata,
|
| 282 |
+
}
|
| 283 |
+
db.execute(
|
| 284 |
+
"INSERT INTO origins VALUES (?, ?, ?, ?, ?, ?)",
|
| 285 |
+
(
|
| 286 |
+
doc_hash, document.doc_id, document.source,
|
| 287 |
+
document.source_file, document.row_index,
|
| 288 |
+
json.dumps(identity, ensure_ascii=False, allow_nan=False),
|
| 289 |
+
),
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
if first:
|
| 293 |
+
counts["unique_documents"] += 1
|
| 294 |
+
blocks = []
|
| 295 |
+
for index, original in enumerate(normalized.split("\n")):
|
| 296 |
+
result = clean_block(original)
|
| 297 |
+
block_id = f"b{index:03d}"
|
| 298 |
+
counts["input_blocks"] += 1
|
| 299 |
+
counts[result["action"] + "_blocks"] += 1
|
| 300 |
+
rule_reasons[result["reason"]] += 1
|
| 301 |
+
blocks.append({
|
| 302 |
+
"id": block_id, "line_index": index,
|
| 303 |
+
"text": result["text"], "action": result["action"],
|
| 304 |
+
})
|
| 305 |
+
if result["action"] != "keep":
|
| 306 |
+
destination = (
|
| 307 |
+
"dropped_blocks" if result["action"] == "drop"
|
| 308 |
+
else "review_blocks"
|
| 309 |
+
)
|
| 310 |
+
dump_line(audits[destination], {
|
| 311 |
+
"source": document.source,
|
| 312 |
+
"doc_id": document.doc_id, "doc_hash": doc_hash,
|
| 313 |
+
"block_id": block_id, "original_text": original,
|
| 314 |
+
**result,
|
| 315 |
+
})
|
| 316 |
+
|
| 317 |
+
boundaries, fragment_labels, block_labels = document_annotations(db, doc_hash, blocks)
|
| 318 |
+
counts["approved_block_labels"] += len(block_labels)
|
| 319 |
+
effective_blocks.update(block["action"] for block in blocks)
|
| 320 |
+
for block_id, label_id in block_labels.items():
|
| 321 |
+
block = next(item for item in blocks if item["id"] == block_id)
|
| 322 |
+
destination = "dropped_blocks" if block["action"] == "drop" else "review_blocks"
|
| 323 |
+
dump_line(audits[destination], {
|
| 324 |
+
"source": document.source, "doc_id": document.doc_id,
|
| 325 |
+
"doc_hash": doc_hash, "block_id": block_id,
|
| 326 |
+
"text": block["text"], "action": block["action"],
|
| 327 |
+
"reason": "approved_local_annotation", "annotation_id": label_id,
|
| 328 |
+
})
|
| 329 |
+
|
| 330 |
+
paragraphs = restore_linebreaks(
|
| 331 |
+
blocks, max_chars=settings["max_join_chars"],
|
| 332 |
+
boundary_decisions={pair: label["action"] for pair, label in boundaries.items()},
|
| 333 |
+
)
|
| 334 |
+
counts["paragraphs"] += len(paragraphs)
|
| 335 |
+
for pi, paragraph in enumerate(paragraphs):
|
| 336 |
+
counts["join_events"] += len(paragraph["joins"])
|
| 337 |
+
counts["approved_join_events"] += sum(join["reason"] == "approved_annotation" for join in paragraph["joins"])
|
| 338 |
+
paragraph_label_ids = {
|
| 339 |
+
block_labels[part["block_id"]] for part in paragraph["parts"]
|
| 340 |
+
if part["block_id"] in block_labels
|
| 341 |
+
}
|
| 342 |
+
paragraph_label_ids.update(
|
| 343 |
+
boundaries[(join["left_block"], join["right_block"])]["id"]
|
| 344 |
+
for join in paragraph["joins"] if join["reason"] == "approved_annotation"
|
| 345 |
+
)
|
| 346 |
+
for si, sentence in enumerate(split_sentences(paragraph["text"])):
|
| 347 |
+
flags = sorted(set(
|
| 348 |
+
paragraph["flags"] + sentence["flags"]
|
| 349 |
+
))
|
| 350 |
+
spans = []
|
| 351 |
+
for part in paragraph["parts"]:
|
| 352 |
+
left = max(sentence["start"], part["start"])
|
| 353 |
+
right = min(sentence["end"], part["end"])
|
| 354 |
+
if left < right:
|
| 355 |
+
spans.append({
|
| 356 |
+
"block_id": part["block_id"],
|
| 357 |
+
"start": left - part["start"],
|
| 358 |
+
"end": right - part["start"],
|
| 359 |
+
})
|
| 360 |
+
fragment_label = match_fragment(db, fragment_labels, sentence["text"], spans)
|
| 361 |
+
explicitly_kept = fragment_label is not None and fragment_label["action"] == "keep"
|
| 362 |
+
explicitly_excluded = fragment_label is not None and fragment_label["action"] in {"drop", "review"}
|
| 363 |
+
if explicitly_kept and flags:
|
| 364 |
+
raise ValueError(f"Annotation {fragment_label['id']}: flagged fragments cannot be rescued.")
|
| 365 |
+
if (
|
| 366 |
+
(not sentence["terminated"] and not explicitly_kept) or flags or explicitly_excluded
|
| 367 |
+
or not any(c.isalnum() for c in sentence["text"])
|
| 368 |
+
):
|
| 369 |
+
counts["fragments"] += 1
|
| 370 |
+
fragment_flags.update(flags)
|
| 371 |
+
dump_line(audits["fragments"], {
|
| 372 |
+
"source": document.source,
|
| 373 |
+
"doc_id": document.doc_id, "doc_hash": doc_hash,
|
| 374 |
+
"paragraph_index": pi, "sentence_index": si,
|
| 375 |
+
"text": sentence["text"],
|
| 376 |
+
"terminated": sentence["terminated"],
|
| 377 |
+
"flags": flags, "cleaned_block_spans": spans,
|
| 378 |
+
"paragraph_joins": paragraph["joins"],
|
| 379 |
+
"approved_annotation_id": fragment_label["id"] if fragment_label else None,
|
| 380 |
+
})
|
| 381 |
+
continue
|
| 382 |
+
text = sentence["text"]
|
| 383 |
+
label_ids = set(paragraph_label_ids)
|
| 384 |
+
if fragment_label:
|
| 385 |
+
label_ids.add(fragment_label["id"])
|
| 386 |
+
counts["approved_fragment_recoveries"] += int(not sentence["terminated"])
|
| 387 |
+
db.execute(
|
| 388 |
+
"INSERT INTO units VALUES (?, ?, ?, ?, ?, ?, ?)",
|
| 389 |
+
(
|
| 390 |
+
doc_hash, sha(text), text, pi, si,
|
| 391 |
+
json.dumps(spans, ensure_ascii=False),
|
| 392 |
+
json.dumps(sorted(label_ids)),
|
| 393 |
+
),
|
| 394 |
+
)
|
| 395 |
+
counts["sentence_occurrences"] += 1
|
| 396 |
+
if counts["document_origins"] % settings.get("commit_every", 200) == 0:
|
| 397 |
+
db.commit()
|
| 398 |
+
if counts["document_origins"] % settings.get("progress_every", 200) == 0:
|
| 399 |
+
print(f"Read {counts['document_origins']} document origins", flush=True)
|
| 400 |
+
|
| 401 |
+
db.commit()
|
| 402 |
+
forced_roots = set()
|
| 403 |
+
for row in db.execute("SELECT DISTINCT doc_hash FROM annotations"):
|
| 404 |
+
if db.execute("SELECT 1 FROM parents WHERE key=?", (row[0],)).fetchone():
|
| 405 |
+
forced_roots.add(find(db, row[0]))
|
| 406 |
+
for doc_id in sorted(calibration_ids):
|
| 407 |
+
for row in db.execute(
|
| 408 |
+
"SELECT DISTINCT doc_hash FROM origins WHERE doc_id = ?", (doc_id,)
|
| 409 |
+
):
|
| 410 |
+
forced_roots.add(find(db, row["doc_hash"]))
|
| 411 |
+
|
| 412 |
+
for row in db.execute("SELECT doc_hash FROM contents ORDER BY doc_hash"):
|
| 413 |
+
root = find(db, row["doc_hash"])
|
| 414 |
+
value = int(sha(f"{settings['seed']}:{root}")[:16], 16) / 2**64
|
| 415 |
+
rank = (
|
| 416 |
+
0 if root in forced_roots or value < config["split"]["train"]
|
| 417 |
+
else 1 if value < config["split"]["train"] + config["split"]["validation"]
|
| 418 |
+
else 2
|
| 419 |
+
)
|
| 420 |
+
db.execute(
|
| 421 |
+
"UPDATE contents SET group_id = ?, split_rank = ? WHERE doc_hash = ?",
|
| 422 |
+
(root, rank, row["doc_hash"]),
|
| 423 |
+
)
|
| 424 |
+
db.commit()
|
| 425 |
+
db.executescript(WINNERS)
|
| 426 |
+
# Text inspected while tuning the pipeline must not reappear in held-out
|
| 427 |
+
# splits via an unreviewed document with the same sentence.
|
| 428 |
+
db.execute("""
|
| 429 |
+
UPDATE winners SET split_rank=0 WHERE text_hash IN (
|
| 430 |
+
SELECT u.text_hash FROM units u JOIN contents c ON c.doc_hash=u.doc_hash
|
| 431 |
+
WHERE c.group_id IN (SELECT value FROM json_each(?))
|
| 432 |
+
)
|
| 433 |
+
""", (json.dumps(sorted(forced_roots)),))
|
| 434 |
+
|
| 435 |
+
split_stats = {
|
| 436 |
+
name: {"sentences": 0, "characters": 0, "primary_sources": Counter()}
|
| 437 |
+
for name in SPLITS
|
| 438 |
+
}
|
| 439 |
+
outputs = {
|
| 440 |
+
name: (
|
| 441 |
+
stack.enter_context((output / f"{name}.jsonl").open(
|
| 442 |
+
"w", encoding="utf-8", newline="\n"
|
| 443 |
+
)),
|
| 444 |
+
stack.enter_context((output / f"{name}.txt").open(
|
| 445 |
+
"w", encoding="utf-8", newline="\n"
|
| 446 |
+
)),
|
| 447 |
+
)
|
| 448 |
+
for name in SPLITS
|
| 449 |
+
}
|
| 450 |
+
for row in db.execute(PRIMARY_ROWS):
|
| 451 |
+
name = SPLITS[row["split_rank"]]
|
| 452 |
+
record = {
|
| 453 |
+
"text": row["text"], "text_hash": row["text_hash"],
|
| 454 |
+
"source": row["source"], "sources": sorted(row["sources"].split(",")),
|
| 455 |
+
"doc_id": row["doc_id"], "doc_hash": row["doc_hash"],
|
| 456 |
+
"group_id": row["group_id"],
|
| 457 |
+
"source_file": row["source_file"], "row_index": row["row_index"],
|
| 458 |
+
"paragraph_index": row["paragraph_index"],
|
| 459 |
+
"sentence_index": row["sentence_index"],
|
| 460 |
+
"cleaned_block_spans": json.loads(row["spans"]),
|
| 461 |
+
"quality_mode": settings["quality_mode"], "lm_reviewed": False,
|
| 462 |
+
"approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 463 |
+
}
|
| 464 |
+
dump_line(outputs[name][0], record)
|
| 465 |
+
outputs[name][1].write(row["text"] + "\n")
|
| 466 |
+
split_stats[name]["sentences"] += 1
|
| 467 |
+
split_stats[name]["characters"] += len(row["text"])
|
| 468 |
+
split_stats[name]["primary_sources"][row["source"]] += 1
|
| 469 |
+
|
| 470 |
+
with (output / "documents.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 471 |
+
for row in db.execute("""
|
| 472 |
+
SELECT o.info, c.group_id, c.split_rank FROM origins o
|
| 473 |
+
JOIN contents c ON c.doc_hash = o.doc_hash
|
| 474 |
+
ORDER BY o.source_file, o.row_index
|
| 475 |
+
"""):
|
| 476 |
+
dump_line(stream, {
|
| 477 |
+
**json.loads(row["info"]), "group_id": row["group_id"],
|
| 478 |
+
"assigned_split": SPLITS[row["split_rank"]],
|
| 479 |
+
})
|
| 480 |
+
|
| 481 |
+
# Full sentence provenance includes occurrences removed from another split.
|
| 482 |
+
with (output / "provenance.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 483 |
+
for row in db.execute("""
|
| 484 |
+
SELECT u.text_hash, u.doc_hash, u.paragraph_index, u.sentence_index,
|
| 485 |
+
o.doc_id, o.source, o.source_file, o.row_index,
|
| 486 |
+
c.group_id, u.annotation_ids, c.split_rank AS assigned, w.split_rank AS exported
|
| 487 |
+
FROM units u JOIN contents c ON c.doc_hash = u.doc_hash
|
| 488 |
+
JOIN origins o ON o.doc_hash = u.doc_hash
|
| 489 |
+
JOIN winners w ON w.text_hash = u.text_hash
|
| 490 |
+
ORDER BY u.text_hash, o.source_file, o.row_index,
|
| 491 |
+
u.paragraph_index, u.sentence_index
|
| 492 |
+
"""):
|
| 493 |
+
dump_line(stream, {
|
| 494 |
+
key: row[key] for key in row.keys()
|
| 495 |
+
if key not in {"assigned", "exported", "annotation_ids"}
|
| 496 |
+
} | {
|
| 497 |
+
"approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 498 |
+
"assigned_split": SPLITS[row["assigned"]],
|
| 499 |
+
"exported_split": SPLITS[row["exported"]],
|
| 500 |
+
"retained_in_assigned_split": row["assigned"] == row["exported"],
|
| 501 |
+
})
|
| 502 |
+
|
| 503 |
+
unique_sentences = db.execute("SELECT COUNT(*) FROM winners").fetchone()[0]
|
| 504 |
+
cross_split_removed = db.execute("""
|
| 505 |
+
SELECT COUNT(*) FROM units u
|
| 506 |
+
JOIN contents c ON c.doc_hash = u.doc_hash
|
| 507 |
+
JOIN winners w ON w.text_hash = u.text_hash
|
| 508 |
+
WHERE c.split_rank != w.split_rank
|
| 509 |
+
""").fetchone()[0]
|
| 510 |
+
characters = sum(item["characters"] for item in split_stats.values())
|
| 511 |
+
matched_annotations = db.execute("SELECT COUNT(*) FROM annotations WHERE matched=1").fetchone()[0]
|
| 512 |
+
unmatched_annotations = [row[0] for row in db.execute("SELECT id FROM annotations WHERE matched=0 ORDER BY id")]
|
| 513 |
+
dump_json(output / "unmatched_annotations.json", unmatched_annotations)
|
| 514 |
+
if config.get("review", {}).get("require_all_annotations", False) and unmatched_annotations:
|
| 515 |
+
raise ValueError("Approved annotations did not match this build; inspect unmatched_annotations.json.")
|
| 516 |
+
stats = {
|
| 517 |
+
**dict(counts),
|
| 518 |
+
"duplicate_documents": counts["document_origins"] - counts["unique_documents"],
|
| 519 |
+
"unique_sentences": unique_sentences,
|
| 520 |
+
"duplicate_sentence_occurrences": counts["sentence_occurrences"] - unique_sentences,
|
| 521 |
+
"cross_split_occurrences_removed": cross_split_removed,
|
| 522 |
+
"final_characters": characters,
|
| 523 |
+
"splits": {
|
| 524 |
+
name: {**item, "primary_sources": dict(item["primary_sources"])}
|
| 525 |
+
for name, item in split_stats.items()
|
| 526 |
+
},
|
| 527 |
+
"rule_reasons": dict(rule_reasons),
|
| 528 |
+
"block_count_note": "keep/drop/review_blocks count rule-stage decisions before annotations.",
|
| 529 |
+
"effective_block_actions": dict(effective_blocks),
|
| 530 |
+
"fragment_flags": dict(fragment_flags),
|
| 531 |
+
"forced_train_groups": len(forced_roots),
|
| 532 |
+
"annotation_records": annotation_count, "matched_annotations": matched_annotations,
|
| 533 |
+
"unmatched_annotations": len(unmatched_annotations),
|
| 534 |
+
"token_estimate_scenarios": {
|
| 535 |
+
f"{n}_characters_per_token": math.ceil(characters / n) for n in (1, 2, 3)
|
| 536 |
+
},
|
| 537 |
+
"token_estimate_note": "Heuristic scenarios, not measured SentencePiece counts.",
|
| 538 |
+
}
|
| 539 |
+
dump_json(output / "stats.json", stats)
|
| 540 |
+
db.commit()
|
| 541 |
+
|
| 542 |
+
input_files = files + [tatoeba] + ([calibration_file] if calibration_file else []) + calibration_files + ([annotation_file] if annotation_file else [])
|
| 543 |
+
for path, before in snapshots.items():
|
| 544 |
+
if (path.stat().st_size, path.stat().st_mtime_ns) != before:
|
| 545 |
+
raise ValueError(f"Input or code changed during build: {display_path(path)}")
|
| 546 |
+
for path, before in initial_hashes.items():
|
| 547 |
+
if file_sha(path) != before:
|
| 548 |
+
raise ValueError(f"Policy or code changed during build: {display_path(path)}")
|
| 549 |
+
dump_json(output / "manifest.json", {
|
| 550 |
+
"status": "complete",
|
| 551 |
+
"quality_mode": settings["quality_mode"],
|
| 552 |
+
"stage": "full_corpus_staging" if not any(limit for _, _, limit in inputs) else "bounded_integration_check",
|
| 553 |
+
"ready_for_lm_training": False,
|
| 554 |
+
"purpose": "pipeline smoke test" if any(
|
| 555 |
+
limit for _, _, limit in inputs
|
| 556 |
+
) else "full local corpus staging; quality audit and near dedup pending",
|
| 557 |
+
"config": config,
|
| 558 |
+
"python_version": sys.version,
|
| 559 |
+
"selection": "first N documents per input file; 0 means all",
|
| 560 |
+
"selected_documents": dict(selected_documents),
|
| 561 |
+
"grouping": "transitive groups of identical NFC documents, source IDs and canonical URLs",
|
| 562 |
+
"sentence_dedup": "exact NFC text; calibration text forced to train, otherwise test > validation > train",
|
| 563 |
+
"near_duplicate_detection": False,
|
| 564 |
+
"span_offsets": "Unicode code points within cleaned blocks",
|
| 565 |
+
"calibration_policy": "known calibration documents and their groups are forced into train",
|
| 566 |
+
"annotation_policy": "Only approved snapshot-matched local annotations apply; annotation document groups are forced into train; model replies alone are advisory.",
|
| 567 |
+
"input_sha256": {display_path(path): file_sha(path) for path in input_files},
|
| 568 |
+
"code_sha256": {display_path(path): file_sha(path) for path in code_files},
|
| 569 |
+
"config_sha256": file_sha(config_path),
|
| 570 |
+
"effective_output_dir": display_path(output),
|
| 571 |
+
})
|
| 572 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2))
|
| 573 |
+
print(f"Corpus: {output}")
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def main():
|
| 577 |
+
parser = argparse.ArgumentParser()
|
| 578 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/corpus.toml")
|
| 579 |
+
parser.add_argument("--output", help="Override output directory; must be absent or empty.")
|
| 580 |
+
args = parser.parse_args()
|
| 581 |
+
run(args.config, args.output)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
if __name__ == "__main__":
|
| 585 |
+
main()
|
source/src/vimeml/data/clean.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative text-block cleaning rules."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import unicodedata
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
URL_ONLY = re.compile(r"(?:[→↗➜>]\s*)?https?://\S+")
|
| 8 |
+
PAIRED_DECORATION = re.compile(r"([◇◆■□★☆]{2,})(.+?)\1")
|
| 9 |
+
NAVIGATION_SUFFIX = re.compile(r"[。!?!?]\s*Next\s*$")
|
| 10 |
+
DECORATION_CHARS = set(" -=_*#~・◇◆■□★☆→←↑↓/\\|─━")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def clean_block(original: str) -> dict:
|
| 14 |
+
changes = []
|
| 15 |
+
flags = []
|
| 16 |
+
|
| 17 |
+
text = unicodedata.normalize("NFC", original)
|
| 18 |
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
| 19 |
+
text = text.lstrip("\ufeff")
|
| 20 |
+
|
| 21 |
+
# Replace controls with spaces to avoid joining unrelated words.
|
| 22 |
+
text = "".join(
|
| 23 |
+
" " if unicodedata.category(char) == "Cc"
|
| 24 |
+
and char not in "\n\t" else char
|
| 25 |
+
for char in text
|
| 26 |
+
).strip()
|
| 27 |
+
|
| 28 |
+
if text != original:
|
| 29 |
+
changes.append("basic_normalization")
|
| 30 |
+
|
| 31 |
+
action = "keep"
|
| 32 |
+
reason = "no_definite_noise"
|
| 33 |
+
|
| 34 |
+
if not text:
|
| 35 |
+
action, reason = "drop", "empty"
|
| 36 |
+
elif URL_ONLY.fullmatch(text):
|
| 37 |
+
action, reason = "drop", "standalone_url"
|
| 38 |
+
elif all(char in DECORATION_CHARS for char in text):
|
| 39 |
+
action, reason = "drop", "decoration_only"
|
| 40 |
+
else:
|
| 41 |
+
match = PAIRED_DECORATION.fullmatch(text)
|
| 42 |
+
if match:
|
| 43 |
+
text = match.group(2).strip()
|
| 44 |
+
changes.append("paired_decoration_removed")
|
| 45 |
+
|
| 46 |
+
if "\ufffd" in text:
|
| 47 |
+
flags.append("replacement_character")
|
| 48 |
+
if NAVIGATION_SUFFIX.search(text):
|
| 49 |
+
flags.append("possible_navigation_suffix")
|
| 50 |
+
|
| 51 |
+
if flags:
|
| 52 |
+
action, reason = "review", "suspected_noise"
|
| 53 |
+
|
| 54 |
+
return {
|
| 55 |
+
"text": text,
|
| 56 |
+
"action": action,
|
| 57 |
+
"reason": reason,
|
| 58 |
+
"changes": changes,
|
| 59 |
+
"flags": flags,
|
| 60 |
+
}
|
source/src/vimeml/data/corpus_export.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared corpus export contract for partitioned preprocessing results."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
|
| 8 |
+
from vimeml.data.build import SPLITS, WINNERS, PRIMARY_ROWS, find, sha, dump_line, dump_json
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def export_corpus(db, output, config, calibration_ids, counts, rule_reasons,
|
| 12 |
+
fragment_flags, effective_blocks, annotation_count):
|
| 13 |
+
settings = config['build']
|
| 14 |
+
with ExitStack() as stack:
|
| 15 |
+
forced_roots = set()
|
| 16 |
+
for row in db.execute("SELECT DISTINCT doc_hash FROM annotations"):
|
| 17 |
+
if db.execute("SELECT 1 FROM parents WHERE key=?", (row[0],)).fetchone():
|
| 18 |
+
forced_roots.add(find(db, row[0]))
|
| 19 |
+
for doc_id in sorted(calibration_ids):
|
| 20 |
+
for row in db.execute(
|
| 21 |
+
"SELECT DISTINCT doc_hash FROM origins WHERE doc_id = ?", (doc_id,)
|
| 22 |
+
):
|
| 23 |
+
forced_roots.add(find(db, row["doc_hash"]))
|
| 24 |
+
|
| 25 |
+
for row in db.execute("SELECT doc_hash FROM contents ORDER BY doc_hash"):
|
| 26 |
+
root = find(db, row["doc_hash"])
|
| 27 |
+
value = int(sha(f"{settings['seed']}:{root}")[:16], 16) / 2**64
|
| 28 |
+
rank = (
|
| 29 |
+
0 if root in forced_roots or value < config["split"]["train"]
|
| 30 |
+
else 1 if value < config["split"]["train"] + config["split"]["validation"]
|
| 31 |
+
else 2
|
| 32 |
+
)
|
| 33 |
+
db.execute(
|
| 34 |
+
"UPDATE contents SET group_id = ?, split_rank = ? WHERE doc_hash = ?",
|
| 35 |
+
(root, rank, row["doc_hash"]),
|
| 36 |
+
)
|
| 37 |
+
db.commit()
|
| 38 |
+
db.executescript(WINNERS)
|
| 39 |
+
# Text inspected while tuning the pipeline must not reappear in held-out
|
| 40 |
+
# splits via an unreviewed document with the same sentence.
|
| 41 |
+
db.execute("""
|
| 42 |
+
UPDATE winners SET split_rank=0 WHERE text_hash IN (
|
| 43 |
+
SELECT u.text_hash FROM units u JOIN contents c ON c.doc_hash=u.doc_hash
|
| 44 |
+
WHERE c.group_id IN (SELECT value FROM json_each(?))
|
| 45 |
+
)
|
| 46 |
+
""", (json.dumps(sorted(forced_roots)),))
|
| 47 |
+
|
| 48 |
+
split_stats = {
|
| 49 |
+
name: {"sentences": 0, "characters": 0, "primary_sources": Counter()}
|
| 50 |
+
for name in SPLITS
|
| 51 |
+
}
|
| 52 |
+
outputs = {
|
| 53 |
+
name: (
|
| 54 |
+
stack.enter_context((output / f"{name}.jsonl").open(
|
| 55 |
+
"w", encoding="utf-8", newline="\n"
|
| 56 |
+
)),
|
| 57 |
+
stack.enter_context((output / f"{name}.txt").open(
|
| 58 |
+
"w", encoding="utf-8", newline="\n"
|
| 59 |
+
)),
|
| 60 |
+
)
|
| 61 |
+
for name in SPLITS
|
| 62 |
+
}
|
| 63 |
+
for row in db.execute(PRIMARY_ROWS):
|
| 64 |
+
name = SPLITS[row["split_rank"]]
|
| 65 |
+
record = {
|
| 66 |
+
"text": row["text"], "text_hash": row["text_hash"],
|
| 67 |
+
"source": row["source"], "sources": sorted(row["sources"].split(",")),
|
| 68 |
+
"doc_id": row["doc_id"], "doc_hash": row["doc_hash"],
|
| 69 |
+
"group_id": row["group_id"],
|
| 70 |
+
"source_file": row["source_file"], "row_index": row["row_index"],
|
| 71 |
+
"paragraph_index": row["paragraph_index"],
|
| 72 |
+
"sentence_index": row["sentence_index"],
|
| 73 |
+
"cleaned_block_spans": json.loads(row["spans"]),
|
| 74 |
+
"quality_mode": settings["quality_mode"], "lm_reviewed": False,
|
| 75 |
+
"approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 76 |
+
}
|
| 77 |
+
dump_line(outputs[name][0], record)
|
| 78 |
+
outputs[name][1].write(row["text"] + "\n")
|
| 79 |
+
split_stats[name]["sentences"] += 1
|
| 80 |
+
split_stats[name]["characters"] += len(row["text"])
|
| 81 |
+
split_stats[name]["primary_sources"][row["source"]] += 1
|
| 82 |
+
|
| 83 |
+
with (output / "documents.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 84 |
+
for row in db.execute("""
|
| 85 |
+
SELECT o.info, c.group_id, c.split_rank FROM origins o
|
| 86 |
+
JOIN contents c ON c.doc_hash = o.doc_hash
|
| 87 |
+
ORDER BY o.source_file, o.row_index
|
| 88 |
+
"""):
|
| 89 |
+
dump_line(stream, {
|
| 90 |
+
**json.loads(row["info"]), "group_id": row["group_id"],
|
| 91 |
+
"assigned_split": SPLITS[row["split_rank"]],
|
| 92 |
+
})
|
| 93 |
+
|
| 94 |
+
# Full sentence provenance includes occurrences removed from another split.
|
| 95 |
+
with (output / "provenance.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 96 |
+
for row in db.execute("""
|
| 97 |
+
SELECT u.text_hash, u.doc_hash, u.paragraph_index, u.sentence_index,
|
| 98 |
+
o.doc_id, o.source, o.source_file, o.row_index,
|
| 99 |
+
c.group_id, u.annotation_ids, c.split_rank AS assigned, w.split_rank AS exported
|
| 100 |
+
FROM units u JOIN contents c ON c.doc_hash = u.doc_hash
|
| 101 |
+
JOIN origins o ON o.doc_hash = u.doc_hash
|
| 102 |
+
JOIN winners w ON w.text_hash = u.text_hash
|
| 103 |
+
ORDER BY u.text_hash, o.source_file, o.row_index,
|
| 104 |
+
u.paragraph_index, u.sentence_index
|
| 105 |
+
"""):
|
| 106 |
+
dump_line(stream, {
|
| 107 |
+
key: row[key] for key in row.keys()
|
| 108 |
+
if key not in {"assigned", "exported", "annotation_ids"}
|
| 109 |
+
} | {
|
| 110 |
+
"approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 111 |
+
"assigned_split": SPLITS[row["assigned"]],
|
| 112 |
+
"exported_split": SPLITS[row["exported"]],
|
| 113 |
+
"retained_in_assigned_split": row["assigned"] == row["exported"],
|
| 114 |
+
})
|
| 115 |
+
|
| 116 |
+
unique_sentences = db.execute("SELECT COUNT(*) FROM winners").fetchone()[0]
|
| 117 |
+
cross_split_removed = db.execute("""
|
| 118 |
+
SELECT COUNT(*) FROM units u
|
| 119 |
+
JOIN contents c ON c.doc_hash = u.doc_hash
|
| 120 |
+
JOIN winners w ON w.text_hash = u.text_hash
|
| 121 |
+
WHERE c.split_rank != w.split_rank
|
| 122 |
+
""").fetchone()[0]
|
| 123 |
+
characters = sum(item["characters"] for item in split_stats.values())
|
| 124 |
+
matched_annotations = db.execute("SELECT COUNT(*) FROM annotations WHERE matched=1").fetchone()[0]
|
| 125 |
+
unmatched_annotations = [row[0] for row in db.execute("SELECT id FROM annotations WHERE matched=0 ORDER BY id")]
|
| 126 |
+
dump_json(output / "unmatched_annotations.json", unmatched_annotations)
|
| 127 |
+
if config.get("review", {}).get("require_all_annotations", False) and unmatched_annotations:
|
| 128 |
+
raise ValueError("Approved annotations did not match this build; inspect unmatched_annotations.json.")
|
| 129 |
+
stats = {
|
| 130 |
+
**dict(counts),
|
| 131 |
+
"duplicate_documents": counts["document_origins"] - counts["unique_documents"],
|
| 132 |
+
"unique_sentences": unique_sentences,
|
| 133 |
+
"duplicate_sentence_occurrences": counts["sentence_occurrences"] - unique_sentences,
|
| 134 |
+
"cross_split_occurrences_removed": cross_split_removed,
|
| 135 |
+
"final_characters": characters,
|
| 136 |
+
"splits": {
|
| 137 |
+
name: {**item, "primary_sources": dict(item["primary_sources"])}
|
| 138 |
+
for name, item in split_stats.items()
|
| 139 |
+
},
|
| 140 |
+
"rule_reasons": dict(rule_reasons),
|
| 141 |
+
"block_count_note": "keep/drop/review_blocks count rule-stage decisions before annotations.",
|
| 142 |
+
"effective_block_actions": dict(effective_blocks),
|
| 143 |
+
"fragment_flags": dict(fragment_flags),
|
| 144 |
+
"forced_train_groups": len(forced_roots),
|
| 145 |
+
"annotation_records": annotation_count, "matched_annotations": matched_annotations,
|
| 146 |
+
"unmatched_annotations": len(unmatched_annotations),
|
| 147 |
+
"token_estimate_scenarios": {
|
| 148 |
+
f"{n}_characters_per_token": math.ceil(characters / n) for n in (1, 2, 3)
|
| 149 |
+
},
|
| 150 |
+
"token_estimate_note": "Heuristic scenarios, not measured SentencePiece counts.",
|
| 151 |
+
}
|
| 152 |
+
dump_json(output / "stats.json", stats)
|
| 153 |
+
db.commit()
|
| 154 |
+
|
| 155 |
+
return stats
|
source/src/vimeml/data/corpus_parts.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable input plans and shared operations for independent corpus parts."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
import sys
|
| 6 |
+
import tomllib
|
| 7 |
+
from collections import Counter
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 11 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 12 |
+
|
| 13 |
+
from vimeml.data.build import validate, file_sha, sha, display_path, SCHEMA, dump_line, dump_json
|
| 14 |
+
from vimeml.data.clean import clean_block
|
| 15 |
+
from vimeml.data.segment import restore_linebreaks, split_sentences
|
| 16 |
+
from vimeml.data.annotations import load_annotations, document_annotations, match_fragment
|
| 17 |
+
|
| 18 |
+
PART_SCHEMA_VERSION = 1
|
| 19 |
+
AUDITS = ("review_blocks", "dropped_blocks", "fragments")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def text_sha(path):
|
| 23 |
+
# Git may check out CRLF on Windows and LF on Mac. These text files have
|
| 24 |
+
# identical semantics; hash normalized UTF-8 text rather than platform bytes.
|
| 25 |
+
return sha(path.read_text(encoding="utf-8-sig"))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_plan(config_path):
|
| 29 |
+
config = tomllib.loads(config_path.read_text(encoding="utf-8-sig"))
|
| 30 |
+
validate(config)
|
| 31 |
+
paths = config["inputs"]["fineweb_paths"]
|
| 32 |
+
if not isinstance(paths, list) or not paths or any(not isinstance(p, str) for p in paths):
|
| 33 |
+
raise ValueError("Partition builds require an explicit fineweb_paths list.")
|
| 34 |
+
inventory = [(p, "fineweb", config["build"]["fineweb_documents_per_shard"]) for p in sorted(paths)]
|
| 35 |
+
inventory.append((config["inputs"]["tatoeba_path"], "tatoeba", config["build"]["tatoeba_documents"]))
|
| 36 |
+
if len({p for p, _, _ in inventory}) != len(inventory):
|
| 37 |
+
raise ValueError("Input paths must be unique.")
|
| 38 |
+
for p, _, _ in inventory:
|
| 39 |
+
if Path(p).is_absolute() or not (ROOT / p).resolve().is_relative_to(ROOT):
|
| 40 |
+
raise ValueError("Input paths must be portable paths inside the repository.")
|
| 41 |
+
policy_paths = {}
|
| 42 |
+
if config["build"]["quality_mode"] == "rules_with_approved_annotations":
|
| 43 |
+
policy_paths["annotations"] = ROOT / config["review"]["annotations"]
|
| 44 |
+
policy_paths["calibration_ids"] = ROOT / config["inputs"]["calibration_ids"]
|
| 45 |
+
calibration_ids = json.loads(policy_paths["calibration_ids"].read_text(encoding="utf-8-sig"))
|
| 46 |
+
if not isinstance(calibration_ids, list) or any(not isinstance(p, str) for p in calibration_ids):
|
| 47 |
+
raise ValueError("calibration_ids must contain a JSON list of document IDs.")
|
| 48 |
+
policy_hashes = {key: text_sha(path) for key, path in policy_paths.items()}
|
| 49 |
+
names = ("build", "readers", "clean", "segment", "annotations", "corpus_parts", "corpus_export", "preprocess_part", "merge_parts")
|
| 50 |
+
code_hashes = {f"src/vimeml/data/{name}.py": text_sha(ROOT / f"src/vimeml/data/{name}.py") for name in names}
|
| 51 |
+
relevant = {key: value for key, value in config["build"].items() if key not in {"output_dir", "commit_every", "progress_every", "batch_size"}}
|
| 52 |
+
signature = sha(json.dumps({"schema": PART_SCHEMA_VERSION, "inventory": inventory,
|
| 53 |
+
"build": relevant, "split": config["split"], "review": config.get("review", {}),
|
| 54 |
+
"policy_sha256": policy_hashes, "code_sha256": code_hashes}, sort_keys=True))
|
| 55 |
+
return config, inventory, policy_paths, set(calibration_ids), policy_hashes, code_hashes, signature
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def parse_part(value):
|
| 59 |
+
try:
|
| 60 |
+
index, total = map(int, value.split("/"))
|
| 61 |
+
except (ValueError, AttributeError):
|
| 62 |
+
raise ValueError("Use --part INDEX/COUNT, e.g. 0/2 or 1/2.") from None
|
| 63 |
+
if not 1 <= total <= 128 or not 0 <= index < total:
|
| 64 |
+
raise ValueError("Part index is zero-based and must be less than the part count.")
|
| 65 |
+
return index, total
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def create_database(output, annotation_path):
|
| 69 |
+
if output.exists() and (not output.is_dir() or any(output.iterdir())):
|
| 70 |
+
raise FileExistsError(f"Output must be absent or empty: {output}")
|
| 71 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
db = sqlite3.connect(output / "index.sqlite", uri=True)
|
| 73 |
+
try:
|
| 74 |
+
db.row_factory = sqlite3.Row
|
| 75 |
+
db.execute("PRAGMA temp_store=FILE")
|
| 76 |
+
db.executescript(SCHEMA)
|
| 77 |
+
db.execute("CREATE TABLE document_metrics(doc_hash TEXT PRIMARY KEY, payload TEXT NOT NULL)")
|
| 78 |
+
annotation_count = load_annotations(db, annotation_path)
|
| 79 |
+
return db, annotation_count
|
| 80 |
+
except BaseException:
|
| 81 |
+
db.close()
|
| 82 |
+
raise
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def aggregate_metrics(db):
|
| 86 |
+
totals = {key: Counter() for key in ("counts", "rule_reasons", "fragment_flags", "effective_blocks")}
|
| 87 |
+
for row in db.execute("SELECT payload FROM document_metrics ORDER BY doc_hash"):
|
| 88 |
+
metrics = json.loads(row[0])
|
| 89 |
+
for key in totals:
|
| 90 |
+
totals[key].update(metrics[key])
|
| 91 |
+
return totals
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def process_content(db, document, normalized, doc_hash, settings, audits):
|
| 95 |
+
counts, rule_reasons, fragment_flags, effective_blocks = (Counter() for _ in range(4))
|
| 96 |
+
counts["unique_documents"] += 1
|
| 97 |
+
blocks = []
|
| 98 |
+
for index, original in enumerate(normalized.split("\n")):
|
| 99 |
+
result = clean_block(original)
|
| 100 |
+
block_id = f"b{index:03d}"
|
| 101 |
+
counts["input_blocks"] += 1
|
| 102 |
+
counts[result["action"] + "_blocks"] += 1
|
| 103 |
+
rule_reasons[result["reason"]] += 1
|
| 104 |
+
blocks.append({
|
| 105 |
+
"id": block_id, "line_index": index,
|
| 106 |
+
"text": result["text"], "action": result["action"],
|
| 107 |
+
})
|
| 108 |
+
if result["action"] != "keep":
|
| 109 |
+
destination = (
|
| 110 |
+
"dropped_blocks" if result["action"] == "drop"
|
| 111 |
+
else "review_blocks"
|
| 112 |
+
)
|
| 113 |
+
dump_line(audits[destination], {
|
| 114 |
+
"source": document.source,
|
| 115 |
+
"doc_id": document.doc_id, "doc_hash": doc_hash,
|
| 116 |
+
"block_id": block_id, "original_text": original,
|
| 117 |
+
**result,
|
| 118 |
+
})
|
| 119 |
+
|
| 120 |
+
boundaries, fragment_labels, block_labels = document_annotations(db, doc_hash, blocks)
|
| 121 |
+
counts["approved_block_labels"] += len(block_labels)
|
| 122 |
+
effective_blocks.update(block["action"] for block in blocks)
|
| 123 |
+
for block_id, label_id in block_labels.items():
|
| 124 |
+
block = next(item for item in blocks if item["id"] == block_id)
|
| 125 |
+
destination = "dropped_blocks" if block["action"] == "drop" else "review_blocks"
|
| 126 |
+
dump_line(audits[destination], {
|
| 127 |
+
"source": document.source, "doc_id": document.doc_id,
|
| 128 |
+
"doc_hash": doc_hash, "block_id": block_id,
|
| 129 |
+
"text": block["text"], "action": block["action"],
|
| 130 |
+
"reason": "approved_local_annotation", "annotation_id": label_id,
|
| 131 |
+
})
|
| 132 |
+
|
| 133 |
+
paragraphs = restore_linebreaks(
|
| 134 |
+
blocks, max_chars=settings["max_join_chars"],
|
| 135 |
+
boundary_decisions={pair: label["action"] for pair, label in boundaries.items()},
|
| 136 |
+
)
|
| 137 |
+
counts["paragraphs"] += len(paragraphs)
|
| 138 |
+
for pi, paragraph in enumerate(paragraphs):
|
| 139 |
+
counts["join_events"] += len(paragraph["joins"])
|
| 140 |
+
counts["approved_join_events"] += sum(join["reason"] == "approved_annotation" for join in paragraph["joins"])
|
| 141 |
+
paragraph_label_ids = {
|
| 142 |
+
block_labels[part["block_id"]] for part in paragraph["parts"]
|
| 143 |
+
if part["block_id"] in block_labels
|
| 144 |
+
}
|
| 145 |
+
paragraph_label_ids.update(
|
| 146 |
+
boundaries[(join["left_block"], join["right_block"])]["id"]
|
| 147 |
+
for join in paragraph["joins"] if join["reason"] == "approved_annotation"
|
| 148 |
+
)
|
| 149 |
+
for si, sentence in enumerate(split_sentences(paragraph["text"])):
|
| 150 |
+
flags = sorted(set(
|
| 151 |
+
paragraph["flags"] + sentence["flags"]
|
| 152 |
+
))
|
| 153 |
+
spans = []
|
| 154 |
+
for part in paragraph["parts"]:
|
| 155 |
+
left = max(sentence["start"], part["start"])
|
| 156 |
+
right = min(sentence["end"], part["end"])
|
| 157 |
+
if left < right:
|
| 158 |
+
spans.append({
|
| 159 |
+
"block_id": part["block_id"],
|
| 160 |
+
"start": left - part["start"],
|
| 161 |
+
"end": right - part["start"],
|
| 162 |
+
})
|
| 163 |
+
fragment_label = match_fragment(db, fragment_labels, sentence["text"], spans)
|
| 164 |
+
explicitly_kept = fragment_label is not None and fragment_label["action"] == "keep"
|
| 165 |
+
explicitly_excluded = fragment_label is not None and fragment_label["action"] in {"drop", "review"}
|
| 166 |
+
if explicitly_kept and flags:
|
| 167 |
+
raise ValueError(f"Annotation {fragment_label['id']}: flagged fragments cannot be rescued.")
|
| 168 |
+
if (
|
| 169 |
+
(not sentence["terminated"] and not explicitly_kept) or flags or explicitly_excluded
|
| 170 |
+
or not any(c.isalnum() for c in sentence["text"])
|
| 171 |
+
):
|
| 172 |
+
counts["fragments"] += 1
|
| 173 |
+
fragment_flags.update(flags)
|
| 174 |
+
dump_line(audits["fragments"], {
|
| 175 |
+
"source": document.source,
|
| 176 |
+
"doc_id": document.doc_id, "doc_hash": doc_hash,
|
| 177 |
+
"paragraph_index": pi, "sentence_index": si,
|
| 178 |
+
"text": sentence["text"],
|
| 179 |
+
"terminated": sentence["terminated"],
|
| 180 |
+
"flags": flags, "cleaned_block_spans": spans,
|
| 181 |
+
"paragraph_joins": paragraph["joins"],
|
| 182 |
+
"approved_annotation_id": fragment_label["id"] if fragment_label else None,
|
| 183 |
+
})
|
| 184 |
+
continue
|
| 185 |
+
text = sentence["text"]
|
| 186 |
+
label_ids = set(paragraph_label_ids)
|
| 187 |
+
if fragment_label:
|
| 188 |
+
label_ids.add(fragment_label["id"])
|
| 189 |
+
counts["approved_fragment_recoveries"] += int(not sentence["terminated"])
|
| 190 |
+
db.execute(
|
| 191 |
+
"INSERT INTO units VALUES (?, ?, ?, ?, ?, ?, ?)",
|
| 192 |
+
(
|
| 193 |
+
doc_hash, sha(text), text, pi, si,
|
| 194 |
+
json.dumps(spans, ensure_ascii=False),
|
| 195 |
+
json.dumps(sorted(label_ids)),
|
| 196 |
+
),
|
| 197 |
+
)
|
| 198 |
+
counts["sentence_occurrences"] += 1
|
| 199 |
+
return {'counts': dict(counts), 'rule_reasons': dict(rule_reasons),
|
| 200 |
+
'fragment_flags': dict(fragment_flags), 'effective_blocks': dict(effective_blocks)}
|
source/src/vimeml/data/merge_parts.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Merge completed preprocessing parts and perform global corpus dedup/splitting."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 10 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 11 |
+
|
| 12 |
+
from vimeml.data.corpus_parts import (PART_SCHEMA_VERSION, AUDITS, load_plan, create_database, aggregate_metrics)
|
| 13 |
+
from vimeml.data.corpus_export import export_corpus
|
| 14 |
+
from vimeml.data.build import attach_alias, canonical_url, file_sha, display_path, dump_json, dump_line
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def validate_parts(config_path, parts):
|
| 18 |
+
plan = load_plan(config_path)
|
| 19 |
+
_, inventory, _, _, _, _, signature = plan
|
| 20 |
+
loaded = []
|
| 21 |
+
for directory in parts:
|
| 22 |
+
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
|
| 23 |
+
if (manifest.get("status") != "complete" or manifest.get("stage") != "preprocessed_part"
|
| 24 |
+
or manifest.get("part_schema_version") != PART_SCHEMA_VERSION):
|
| 25 |
+
raise ValueError(f"Not a completed preprocessing part: {directory}")
|
| 26 |
+
if manifest["pipeline_signature"] != signature:
|
| 27 |
+
raise ValueError(f"Code/config/approval versions differ: {directory}")
|
| 28 |
+
loaded.append((directory, manifest))
|
| 29 |
+
if not loaded:
|
| 30 |
+
raise ValueError("No parts supplied.")
|
| 31 |
+
total = loaded[0][1]["partition"]["count"]
|
| 32 |
+
if len(loaded) != total or any(m["partition"]["count"] != total for _, m in loaded):
|
| 33 |
+
raise ValueError("All planned parts must be supplied exactly once.")
|
| 34 |
+
if {m["partition"]["index"] for _, m in loaded} != set(range(total)):
|
| 35 |
+
raise ValueError("Missing or duplicated part index.")
|
| 36 |
+
for directory, manifest in loaded:
|
| 37 |
+
index = manifest["partition"]["index"]
|
| 38 |
+
expected = {p for number, (p, _, _) in enumerate(inventory) if number % total == index}
|
| 39 |
+
if manifest["planned_inputs"] != [p for p, _, _ in inventory] or set(manifest["input_sha256"]) != expected or set(manifest["selected_documents"]) != expected:
|
| 40 |
+
raise ValueError(f"Part input assignment differs from plan: {directory}")
|
| 41 |
+
print(f"Validating part {index + 1}/{total}: {directory}", flush=True)
|
| 42 |
+
for name in ("index.sqlite", "part-stats.json", *(f"{name}.jsonl" for name in AUDITS)):
|
| 43 |
+
if file_sha(directory / name) != manifest["artifact_sha256"].get(name):
|
| 44 |
+
raise ValueError(f"Copied part file is damaged or changed: {directory / name}")
|
| 45 |
+
return plan, sorted(loaded, key=lambda item: item[1]["partition"]["index"])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run(config_path, parts, output):
|
| 49 |
+
# Raw parquet/TSV files are not needed on the merging machine.
|
| 50 |
+
plan, parts = validate_parts(config_path, parts)
|
| 51 |
+
config, _, policies, calibration_ids, policy_hashes, code_hashes, signature = plan
|
| 52 |
+
selected_documents, input_hashes = {}, {}
|
| 53 |
+
raw_characters = 0
|
| 54 |
+
with ExitStack() as stack:
|
| 55 |
+
db, annotation_count = create_database(output, policies.get("annotations"))
|
| 56 |
+
stack.callback(db.close)
|
| 57 |
+
audits = {name: stack.enter_context((output / f"{name}.jsonl").open("w", encoding="utf-8", newline="\n")) for name in AUDITS}
|
| 58 |
+
for directory, manifest in parts:
|
| 59 |
+
print(f"Importing part {manifest['partition']['index']}: {directory}", flush=True)
|
| 60 |
+
# Read-only ATTACH works for both Windows and POSIX file paths.
|
| 61 |
+
db.execute("ATTACH DATABASE ? AS part", ((directory / "index.sqlite").resolve().as_uri() + "?mode=ro",))
|
| 62 |
+
try:
|
| 63 |
+
db.execute("CREATE TEMP TABLE new_documents AS SELECT doc_hash FROM part.contents WHERE doc_hash NOT IN (SELECT doc_hash FROM contents)")
|
| 64 |
+
db.execute("CREATE UNIQUE INDEX temp.new_documents_hash ON new_documents(doc_hash)")
|
| 65 |
+
db.execute("INSERT INTO contents(doc_hash) SELECT doc_hash FROM new_documents")
|
| 66 |
+
db.execute("INSERT INTO parents SELECT doc_hash,doc_hash FROM new_documents")
|
| 67 |
+
# An identical document is cleaned once globally, even if it
|
| 68 |
+
# appeared on both workers. All of its origins are retained.
|
| 69 |
+
db.execute("INSERT INTO units SELECT * FROM part.units WHERE doc_hash IN (SELECT doc_hash FROM new_documents)")
|
| 70 |
+
db.execute("INSERT INTO document_metrics SELECT * FROM part.document_metrics WHERE doc_hash IN (SELECT doc_hash FROM new_documents)")
|
| 71 |
+
db.execute("INSERT INTO origins SELECT * FROM part.origins")
|
| 72 |
+
db.execute("UPDATE annotations SET matched=1 WHERE id IN (SELECT id FROM part.annotations WHERE matched=1)")
|
| 73 |
+
for name in AUDITS:
|
| 74 |
+
with (directory / f"{name}.jsonl").open(encoding="utf-8") as stream:
|
| 75 |
+
for line in stream:
|
| 76 |
+
item = json.loads(line)
|
| 77 |
+
if db.execute("SELECT 1 FROM new_documents WHERE doc_hash=?", (item["doc_hash"],)).fetchone():
|
| 78 |
+
dump_line(audits[name], item)
|
| 79 |
+
db.execute("DROP TABLE new_documents")
|
| 80 |
+
db.commit()
|
| 81 |
+
finally:
|
| 82 |
+
db.rollback()
|
| 83 |
+
db.execute("DETACH DATABASE part")
|
| 84 |
+
selected_documents.update(manifest["selected_documents"])
|
| 85 |
+
input_hashes.update(manifest["input_sha256"])
|
| 86 |
+
raw_characters += json.loads((directory / "part-stats.json").read_text(encoding="utf-8"))["raw_characters"]
|
| 87 |
+
origin_count = db.execute("SELECT COUNT(*) FROM origins").fetchone()[0]
|
| 88 |
+
if origin_count != sum(selected_documents.values()):
|
| 89 |
+
raise ValueError("Imported source record counts disagree with part manifests.")
|
| 90 |
+
print(f"Grouping {origin_count} document origins globally", flush=True)
|
| 91 |
+
for number, row in enumerate(db.execute("SELECT doc_hash,doc_id,info FROM origins ORDER BY source_file,row_index"), 1):
|
| 92 |
+
attach_alias(db, row["doc_hash"], "id:" + row["doc_id"])
|
| 93 |
+
url = canonical_url(json.loads(row["info"])["metadata"].get("url"))
|
| 94 |
+
if url:
|
| 95 |
+
attach_alias(db, row["doc_hash"], "url:" + url)
|
| 96 |
+
if number % config["build"].get("commit_every", 5000) == 0:
|
| 97 |
+
db.commit()
|
| 98 |
+
if number % config["build"].get("progress_every", 5000) == 0:
|
| 99 |
+
print(f"Grouped {number} document origins", flush=True)
|
| 100 |
+
db.commit()
|
| 101 |
+
metrics = aggregate_metrics(db)
|
| 102 |
+
metrics["counts"]["document_origins"] = origin_count
|
| 103 |
+
metrics["counts"]["raw_characters"] = raw_characters
|
| 104 |
+
print("Deduplicating sentences, assigning splits and exporting corpus", flush=True)
|
| 105 |
+
stats = export_corpus(db, output, config, calibration_ids, metrics["counts"], metrics["rule_reasons"],
|
| 106 |
+
metrics["fragment_flags"], metrics["effective_blocks"], annotation_count)
|
| 107 |
+
if load_plan(config_path)[-1] != signature:
|
| 108 |
+
raise ValueError("Code or policy changed during merge; output is incomplete.")
|
| 109 |
+
dump_json(output / "manifest.json", {
|
| 110 |
+
"status": "complete", "stage": "merged_corpus_staging", "ready_for_lm_training": False,
|
| 111 |
+
"quality_mode": config["build"]["quality_mode"], "config": config,
|
| 112 |
+
"config_sha256": file_sha(config_path), "pipeline_signature": signature, "python_version": sys.version,
|
| 113 |
+
"input_sha256": input_hashes, "selected_documents": selected_documents,
|
| 114 |
+
"policy_sha256": policy_hashes, "code_sha256": code_hashes,
|
| 115 |
+
"fingerprint_normalization": "Code and policy: UTF-8 text with LF line endings, no BOM; input/artifact hashes: exact bytes.",
|
| 116 |
+
"part_manifest_sha256": {display_path(p / "manifest.json"): file_sha(p / "manifest.json") for p, _ in parts},
|
| 117 |
+
"grouping": "transitive groups of identical NFC documents, source IDs and canonical URLs",
|
| 118 |
+
"sentence_dedup": "exact NFC text; calibration text forced to train, otherwise test > validation > train",
|
| 119 |
+
"near_duplicate_detection": False, "span_offsets": "Unicode code points within cleaned blocks",
|
| 120 |
+
"calibration_policy": "known calibration documents and their groups and sentences are forced into train",
|
| 121 |
+
"annotation_policy": "Only approved snapshot-matched local labels apply; model replies alone are advisory.",
|
| 122 |
+
})
|
| 123 |
+
print(json.dumps(stats, ensure_ascii=False, indent=2))
|
| 124 |
+
print(f"Corpus: {output}")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def main():
|
| 128 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 129 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/corpus-sharded.toml")
|
| 130 |
+
parser.add_argument("--parts", nargs="+", type=Path, required=True)
|
| 131 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 132 |
+
args = parser.parse_args()
|
| 133 |
+
run(args.config.resolve(), [p.resolve() for p in args.parts], args.output.resolve())
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
source/src/vimeml/data/merge_parts_fast.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Merge existing cleaning parts using global document groups and parallel hash buckets.
|
| 2 |
+
|
| 3 |
+
Only completed worker outputs are read. No raw inputs or network calls are needed.
|
| 4 |
+
index.sqlite is a document/review index; sentence storage lives in the exported files.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import sqlite3
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from array import array
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from concurrent.futures import ProcessPoolExecutor, wait, FIRST_COMPLETED
|
| 18 |
+
from contextlib import ExitStack, closing
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 22 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 23 |
+
|
| 24 |
+
from vimeml.data.annotations import load_annotations
|
| 25 |
+
from vimeml.data.build import SPLITS, canonical_url, display_path, dump_json, dump_line, file_sha, sha
|
| 26 |
+
from vimeml.data.corpus_parts import AUDITS, load_plan, text_sha
|
| 27 |
+
from vimeml.data.merge_parts import validate_parts
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def log(message):
|
| 31 |
+
print(f"[fast-merge {time.strftime('%H:%M:%S')}] {message}", flush=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def readonly(path):
|
| 35 |
+
db = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
|
| 36 |
+
db.row_factory = sqlite3.Row
|
| 37 |
+
return db
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def tune(db, cache_mb):
|
| 41 |
+
# Budgets are per process, not a hard upper bound on Python/Arrow memory.
|
| 42 |
+
db.execute(f"PRAGMA cache_size=-{cache_mb * 1024}")
|
| 43 |
+
db.execute("PRAGMA temp_store=FILE")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parallel(function, jobs, workers, stage):
|
| 47 |
+
results = []
|
| 48 |
+
with ProcessPoolExecutor(max_workers=workers) as pool:
|
| 49 |
+
pending = {pool.submit(function, job) for job in jobs}
|
| 50 |
+
total = len(pending)
|
| 51 |
+
while pending:
|
| 52 |
+
finished, pending = wait(pending, timeout=10, return_when=FIRST_COMPLETED)
|
| 53 |
+
for future in finished:
|
| 54 |
+
results.append(future.result())
|
| 55 |
+
log(f"{stage}: {len(results)}/{total} completed, {len(pending)} pending")
|
| 56 |
+
return results
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def root_of(parents, node):
|
| 60 |
+
root = node
|
| 61 |
+
while parents[root] != root:
|
| 62 |
+
root = parents[root]
|
| 63 |
+
while parents[node] != node:
|
| 64 |
+
following = parents[node]
|
| 65 |
+
parents[node] = root
|
| 66 |
+
node = following
|
| 67 |
+
return root
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def make_metadata(output, work, parts, config, policies, calibration_ids, cache_mb):
|
| 71 |
+
"""Keep wide sentence data out of the global database entirely."""
|
| 72 |
+
db = sqlite3.connect(output / "index.sqlite", uri=True)
|
| 73 |
+
db.row_factory = sqlite3.Row
|
| 74 |
+
tune(db, cache_mb)
|
| 75 |
+
db.executescript("""
|
| 76 |
+
CREATE TABLE contents (
|
| 77 |
+
doc_hash TEXT PRIMARY KEY, group_id TEXT, split_rank INTEGER,
|
| 78 |
+
owner INTEGER NOT NULL, forced INTEGER NOT NULL DEFAULT 0,
|
| 79 |
+
origin_priority INTEGER, primary_origin INTEGER, source_mask INTEGER
|
| 80 |
+
) WITHOUT ROWID;
|
| 81 |
+
CREATE TABLE origins (
|
| 82 |
+
doc_hash TEXT NOT NULL, doc_id TEXT NOT NULL, source TEXT NOT NULL,
|
| 83 |
+
source_file TEXT NOT NULL, row_index INTEGER NOT NULL, info TEXT NOT NULL,
|
| 84 |
+
PRIMARY KEY(source_file,row_index)
|
| 85 |
+
);
|
| 86 |
+
""")
|
| 87 |
+
annotation_count = load_annotations(db, policies.get("annotations"))
|
| 88 |
+
excluded = {}
|
| 89 |
+
try:
|
| 90 |
+
for directory, manifest in parts:
|
| 91 |
+
index = manifest["partition"]["index"]
|
| 92 |
+
log(f"Import document metadata: part {index}")
|
| 93 |
+
db.execute("ATTACH DATABASE ? AS part", ((directory / "index.sqlite").resolve().as_uri() + "?mode=ro",))
|
| 94 |
+
try:
|
| 95 |
+
excluded[index] = [r[0] for r in db.execute(
|
| 96 |
+
"SELECT p.doc_hash FROM part.contents p JOIN contents c ON c.doc_hash=p.doc_hash")]
|
| 97 |
+
db.execute("INSERT OR IGNORE INTO contents(doc_hash,owner) SELECT doc_hash,? FROM part.contents", (index,))
|
| 98 |
+
db.execute("INSERT INTO origins SELECT * FROM part.origins")
|
| 99 |
+
db.execute("UPDATE annotations SET matched=1 WHERE id IN (SELECT id FROM part.annotations WHERE matched=1)")
|
| 100 |
+
db.commit()
|
| 101 |
+
finally:
|
| 102 |
+
db.rollback()
|
| 103 |
+
db.execute("DETACH DATABASE part")
|
| 104 |
+
log("Build document lookup indexes")
|
| 105 |
+
db.executescript("CREATE INDEX origins_content ON origins(doc_hash); CREATE INDEX origins_identity ON origins(doc_id);")
|
| 106 |
+
hashes = [r[0] for r in db.execute("SELECT doc_hash FROM contents ORDER BY doc_hash")]
|
| 107 |
+
nodes = {key: i for i, key in enumerate(hashes)}
|
| 108 |
+
parents = array("I", range(len(hashes)))
|
| 109 |
+
aliases = {}
|
| 110 |
+
inspected = {nodes[r[0]] for r in db.execute("SELECT DISTINCT doc_hash FROM annotations") if r[0] in nodes}
|
| 111 |
+
for number, row in enumerate(db.execute("SELECT doc_hash,doc_id,info FROM origins"), 1):
|
| 112 |
+
node = nodes[row["doc_hash"]]
|
| 113 |
+
if row["doc_id"] in calibration_ids:
|
| 114 |
+
inspected.add(node)
|
| 115 |
+
url = canonical_url(json.loads(row["info"])["metadata"].get("url"))
|
| 116 |
+
for alias in ("id:" + row["doc_id"], "url:" + url if url else None):
|
| 117 |
+
if alias is None:
|
| 118 |
+
continue
|
| 119 |
+
previous = aliases.get(alias)
|
| 120 |
+
if previous is None:
|
| 121 |
+
aliases[alias] = node
|
| 122 |
+
else:
|
| 123 |
+
left, right = root_of(parents, node), root_of(parents, previous)
|
| 124 |
+
# Nodes follow lexicographic hash order, exactly as the old union-find.
|
| 125 |
+
if left != right:
|
| 126 |
+
parents[max(left, right)] = min(left, right)
|
| 127 |
+
if number % 100000 == 0:
|
| 128 |
+
log(f"Group documents: {number:,} origins")
|
| 129 |
+
del aliases
|
| 130 |
+
forced_roots = {root_of(parents, node) for node in inspected}
|
| 131 |
+
settings = config["build"]
|
| 132 |
+
updates = []
|
| 133 |
+
for node, key in enumerate(hashes):
|
| 134 |
+
root = root_of(parents, node)
|
| 135 |
+
value = int(sha(f"{settings['seed']}:{hashes[root]}")[:16], 16) / 2**64
|
| 136 |
+
forced = root in forced_roots
|
| 137 |
+
rank = (0 if forced or value < config["split"]["train"]
|
| 138 |
+
else 1 if value < config["split"]["train"] + config["split"]["validation"] else 2)
|
| 139 |
+
updates.append((hashes[root], rank, int(forced), key))
|
| 140 |
+
if len(updates) == 10000:
|
| 141 |
+
db.executemany("UPDATE contents SET group_id=?,split_rank=?,forced=? WHERE doc_hash=?", updates)
|
| 142 |
+
updates.clear()
|
| 143 |
+
db.executemany("UPDATE contents SET group_id=?,split_rank=?,forced=? WHERE doc_hash=?", updates)
|
| 144 |
+
db.commit()
|
| 145 |
+
# Compute one preferred origin and source mask per content before sentence joins.
|
| 146 |
+
# Fixed-size arrays avoid a second dictionary of 2 million wide origin records.
|
| 147 |
+
primary = array("Q", [0]) * len(hashes)
|
| 148 |
+
priority = array("Q", [0]) * len(hashes)
|
| 149 |
+
masks = bytearray(len(hashes))
|
| 150 |
+
log("Choose primary document origins")
|
| 151 |
+
for order, row in enumerate(db.execute("""
|
| 152 |
+
SELECT rowid AS origin_id,doc_hash,source FROM origins
|
| 153 |
+
ORDER BY CASE source WHEN 'tatoeba' THEN 0 ELSE 1 END,doc_id,source_file,row_index
|
| 154 |
+
"""), 1):
|
| 155 |
+
node = nodes[row["doc_hash"]]
|
| 156 |
+
if not primary[node]:
|
| 157 |
+
primary[node], priority[node] = row["origin_id"], order
|
| 158 |
+
if row["source"] not in {"fineweb", "tatoeba"}:
|
| 159 |
+
raise ValueError(f"Unsupported source: {row['source']}")
|
| 160 |
+
masks[node] |= 1 if row["source"] == "fineweb" else 2
|
| 161 |
+
updates = []
|
| 162 |
+
for node, key in enumerate(hashes):
|
| 163 |
+
updates.append((priority[node], primary[node], masks[node], key))
|
| 164 |
+
if len(updates) == 10000:
|
| 165 |
+
db.executemany("UPDATE contents SET origin_priority=?,primary_origin=?,source_mask=? WHERE doc_hash=?", updates)
|
| 166 |
+
updates.clear()
|
| 167 |
+
db.executemany("UPDATE contents SET origin_priority=?,primary_origin=?,source_mask=? WHERE doc_hash=?", updates)
|
| 168 |
+
db.commit()
|
| 169 |
+
with (output / "documents.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 170 |
+
for row in db.execute("""
|
| 171 |
+
SELECT o.info,c.group_id,c.split_rank FROM origins o JOIN contents c ON c.doc_hash=o.doc_hash
|
| 172 |
+
ORDER BY o.source_file,o.row_index
|
| 173 |
+
"""):
|
| 174 |
+
dump_line(stream, {**json.loads(row["info"]), "group_id": row["group_id"],
|
| 175 |
+
"assigned_split": SPLITS[row["split_rank"]]})
|
| 176 |
+
unmatched = [r[0] for r in db.execute("SELECT id FROM annotations WHERE matched=0 ORDER BY id")]
|
| 177 |
+
dump_json(output / "unmatched_annotations.json", unmatched)
|
| 178 |
+
if config.get("review", {}).get("require_all_annotations", False) and unmatched:
|
| 179 |
+
raise ValueError("Approved annotations did not match; inspect unmatched_annotations.json.")
|
| 180 |
+
origin_count = db.execute("SELECT COUNT(*) FROM origins").fetchone()[0]
|
| 181 |
+
if origin_count != sum(sum(m["selected_documents"].values()) for _, m in parts):
|
| 182 |
+
raise ValueError("Imported origin counts disagree with manifests.")
|
| 183 |
+
result = {"origin_count": origin_count, "annotation_count": annotation_count,
|
| 184 |
+
"matched_annotations": annotation_count - len(unmatched),
|
| 185 |
+
"unmatched_annotations": len(unmatched), "forced_train_groups": len(forced_roots)}
|
| 186 |
+
finally:
|
| 187 |
+
db.close()
|
| 188 |
+
# Workers receive only small exclusion lists, not all document identities.
|
| 189 |
+
for index, values in excluded.items():
|
| 190 |
+
dump_json(work / f"excluded-{index:03d}.json", values)
|
| 191 |
+
return result
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def repartition(job):
|
| 195 |
+
directory, work, index, buckets, cache_mb = job
|
| 196 |
+
import pyarrow as pa
|
| 197 |
+
import pyarrow.parquet as pq
|
| 198 |
+
|
| 199 |
+
start = time.monotonic()
|
| 200 |
+
destination = work / f"part-{index:03d}"
|
| 201 |
+
destination.mkdir()
|
| 202 |
+
excluded = set(json.loads((work / f"excluded-{index:03d}.json").read_text(encoding="utf-8")))
|
| 203 |
+
fields = ("doc_hash", "text_hash", "text", "paragraph_index", "sentence_index", "spans", "annotation_ids")
|
| 204 |
+
schema = pa.schema([(name, pa.int64() if name.endswith("_index") else pa.string()) for name in fields])
|
| 205 |
+
metrics = {name: Counter() for name in ("counts", "rule_reasons", "fragment_flags", "effective_blocks")}
|
| 206 |
+
sentences = 0
|
| 207 |
+
with ExitStack() as stack:
|
| 208 |
+
db = stack.enter_context(closing(readonly(directory / "index.sqlite")))
|
| 209 |
+
tune(db, cache_mb)
|
| 210 |
+
writers = {}
|
| 211 |
+
cursor = db.execute("SELECT * FROM units")
|
| 212 |
+
while rows := cursor.fetchmany(65536):
|
| 213 |
+
groups = {}
|
| 214 |
+
for row in rows:
|
| 215 |
+
if row["doc_hash"] in excluded:
|
| 216 |
+
continue
|
| 217 |
+
bucket = int(row["text_hash"][:2], 16) * buckets // 256
|
| 218 |
+
groups.setdefault(bucket, []).append(dict(row))
|
| 219 |
+
sentences += 1
|
| 220 |
+
for bucket, values in groups.items():
|
| 221 |
+
if bucket not in writers:
|
| 222 |
+
writers[bucket] = stack.enter_context(pq.ParquetWriter(
|
| 223 |
+
destination / f"bucket-{bucket:03d}.parquet", schema, compression="zstd", use_dictionary=False))
|
| 224 |
+
writers[bucket].write_table(pa.Table.from_pylist(values, schema=schema))
|
| 225 |
+
for row in db.execute("SELECT doc_hash,payload FROM document_metrics"):
|
| 226 |
+
if row["doc_hash"] not in excluded:
|
| 227 |
+
payload = json.loads(row["payload"])
|
| 228 |
+
for name, total in metrics.items():
|
| 229 |
+
total.update(payload[name])
|
| 230 |
+
for name in AUDITS:
|
| 231 |
+
with (directory / f"{name}.jsonl").open(encoding="utf-8") as source, \
|
| 232 |
+
(destination / f"{name}.jsonl").open("w", encoding="utf-8", newline="\n") as target:
|
| 233 |
+
for line in source:
|
| 234 |
+
# Preserve original audit formatting/order when no global content duplicate exists.
|
| 235 |
+
if not excluded or json.loads(line)["doc_hash"] not in excluded:
|
| 236 |
+
target.write(line)
|
| 237 |
+
log(f"Repartition part {index}: {sentences:,} sentences in {time.monotonic() - start:.1f}s")
|
| 238 |
+
return {"index": index, "sentences": sentences, "metrics": {k: dict(v) for k, v in metrics.items()}}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def export_bucket(job):
|
| 242 |
+
bucket, work, metadata, part_indices, quality_mode, cache_mb = job
|
| 243 |
+
import pyarrow.parquet as pq
|
| 244 |
+
|
| 245 |
+
start = time.monotonic()
|
| 246 |
+
destination = work / f"export-{bucket:03d}"
|
| 247 |
+
destination.mkdir()
|
| 248 |
+
scratch = destination / "bucket.sqlite"
|
| 249 |
+
split_stats = {name: {"sentences": 0, "characters": 0, "primary_sources": Counter()} for name in SPLITS}
|
| 250 |
+
with ExitStack() as stack:
|
| 251 |
+
db = stack.enter_context(closing(sqlite3.connect(scratch, uri=True)))
|
| 252 |
+
db.row_factory = sqlite3.Row
|
| 253 |
+
tune(db, cache_mb)
|
| 254 |
+
db.executescript("""
|
| 255 |
+
CREATE TABLE units(doc_hash TEXT,text_hash TEXT,text TEXT,paragraph_index INTEGER,
|
| 256 |
+
sentence_index INTEGER,spans TEXT,annotation_ids TEXT);
|
| 257 |
+
""")
|
| 258 |
+
# Independent scratch DBs have no shared writer and indexes are built after bulk loading.
|
| 259 |
+
fields = ("doc_hash", "text_hash", "text", "paragraph_index", "sentence_index", "spans", "annotation_ids")
|
| 260 |
+
for index in part_indices:
|
| 261 |
+
path = work / f"part-{index:03d}" / f"bucket-{bucket:03d}.parquet"
|
| 262 |
+
if path.exists():
|
| 263 |
+
for batch in pq.ParquetFile(path).iter_batches(batch_size=16384, use_threads=False):
|
| 264 |
+
columns = [batch.column(name).to_pylist() for name in fields]
|
| 265 |
+
db.executemany("INSERT INTO units VALUES(?,?,?,?,?,?,?)", zip(*columns))
|
| 266 |
+
db.commit()
|
| 267 |
+
db.execute("ATTACH DATABASE ? AS meta", (metadata.resolve().as_uri() + "?mode=ro",))
|
| 268 |
+
db.execute(f"PRAGMA meta.cache_size=-{cache_mb * 1024}")
|
| 269 |
+
# Copy only this bucket's narrow per-document lookup, keeping hot joins in its own DB.
|
| 270 |
+
db.executescript("""
|
| 271 |
+
CREATE TABLE docs AS SELECT c.doc_hash,c.group_id,c.split_rank,c.forced,c.origin_priority,
|
| 272 |
+
c.primary_origin,c.source_mask
|
| 273 |
+
FROM meta.contents c JOIN (SELECT DISTINCT doc_hash FROM units) u ON u.doc_hash=c.doc_hash;
|
| 274 |
+
CREATE UNIQUE INDEX docs_hash ON docs(doc_hash);
|
| 275 |
+
CREATE TABLE winners AS
|
| 276 |
+
SELECT u.text_hash, CASE WHEN MAX(d.forced) THEN 0 ELSE MAX(d.split_rank) END split_rank,
|
| 277 |
+
MAX(d.source_mask & 1) fineweb,MAX(d.source_mask & 2) tatoeba
|
| 278 |
+
FROM units u JOIN docs d ON d.doc_hash=u.doc_hash GROUP BY u.text_hash;
|
| 279 |
+
CREATE UNIQUE INDEX winners_hash ON winners(text_hash);
|
| 280 |
+
CREATE TABLE chosen AS
|
| 281 |
+
SELECT unit_id,text_hash FROM (
|
| 282 |
+
SELECT u.rowid unit_id,u.text_hash,
|
| 283 |
+
ROW_NUMBER() OVER(PARTITION BY u.text_hash
|
| 284 |
+
ORDER BY d.origin_priority,u.paragraph_index,u.sentence_index) preference
|
| 285 |
+
FROM units u JOIN docs d ON d.doc_hash=u.doc_hash
|
| 286 |
+
JOIN winners w ON w.text_hash=u.text_hash WHERE d.split_rank=w.split_rank
|
| 287 |
+
) WHERE preference=1;
|
| 288 |
+
CREATE UNIQUE INDEX chosen_hash ON chosen(text_hash);
|
| 289 |
+
""")
|
| 290 |
+
outputs = {name: (stack.enter_context((destination / f"{name}.jsonl").open("w", encoding="utf-8", newline="\n")),
|
| 291 |
+
stack.enter_context((destination / f"{name}.txt").open("w", encoding="utf-8", newline="\n")))
|
| 292 |
+
for name in SPLITS}
|
| 293 |
+
for row in db.execute("""
|
| 294 |
+
SELECT u.*,d.group_id,o.doc_id,o.source,o.source_file,o.row_index,w.split_rank,w.fineweb,w.tatoeba
|
| 295 |
+
FROM chosen x JOIN units u ON u.rowid=x.unit_id JOIN docs d ON d.doc_hash=u.doc_hash
|
| 296 |
+
JOIN meta.origins o ON o.rowid=d.primary_origin JOIN winners w ON w.text_hash=u.text_hash
|
| 297 |
+
ORDER BY x.text_hash
|
| 298 |
+
"""):
|
| 299 |
+
name = SPLITS[row["split_rank"]]
|
| 300 |
+
record = {
|
| 301 |
+
"text": row["text"], "text_hash": row["text_hash"], "source": row["source"],
|
| 302 |
+
"sources": [source for source, present in (("fineweb", row["fineweb"]), ("tatoeba", row["tatoeba"])) if present],
|
| 303 |
+
"doc_id": row["doc_id"], "doc_hash": row["doc_hash"], "group_id": row["group_id"],
|
| 304 |
+
"source_file": row["source_file"], "row_index": row["row_index"],
|
| 305 |
+
"paragraph_index": row["paragraph_index"], "sentence_index": row["sentence_index"],
|
| 306 |
+
"cleaned_block_spans": json.loads(row["spans"]), "quality_mode": quality_mode,
|
| 307 |
+
"lm_reviewed": False, "approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 308 |
+
}
|
| 309 |
+
dump_line(outputs[name][0], record)
|
| 310 |
+
outputs[name][1].write(row["text"] + "\n")
|
| 311 |
+
split_stats[name]["sentences"] += 1
|
| 312 |
+
split_stats[name]["characters"] += len(row["text"])
|
| 313 |
+
split_stats[name]["primary_sources"][row["source"]] += 1
|
| 314 |
+
with (destination / "provenance.jsonl").open("w", encoding="utf-8", newline="\n") as stream:
|
| 315 |
+
for row in db.execute("""
|
| 316 |
+
SELECT u.text_hash,u.doc_hash,u.paragraph_index,u.sentence_index,
|
| 317 |
+
o.doc_id,o.source,o.source_file,o.row_index,d.group_id,u.annotation_ids,
|
| 318 |
+
d.split_rank assigned,w.split_rank exported
|
| 319 |
+
FROM units u JOIN docs d ON d.doc_hash=u.doc_hash
|
| 320 |
+
JOIN meta.origins o ON o.doc_hash=u.doc_hash JOIN winners w ON w.text_hash=u.text_hash
|
| 321 |
+
ORDER BY u.text_hash,o.source_file,o.row_index,u.paragraph_index,u.sentence_index
|
| 322 |
+
"""):
|
| 323 |
+
dump_line(stream, {key: row[key] for key in row.keys() if key not in {"assigned", "exported", "annotation_ids"}} | {
|
| 324 |
+
"approved_annotation_ids": json.loads(row["annotation_ids"]),
|
| 325 |
+
"assigned_split": SPLITS[row["assigned"]], "exported_split": SPLITS[row["exported"]],
|
| 326 |
+
"retained_in_assigned_split": row["assigned"] == row["exported"],
|
| 327 |
+
})
|
| 328 |
+
unique = db.execute("SELECT COUNT(*) FROM winners").fetchone()[0]
|
| 329 |
+
removed = db.execute("""SELECT COUNT(*) FROM units u JOIN docs d ON d.doc_hash=u.doc_hash
|
| 330 |
+
JOIN winners w ON w.text_hash=u.text_hash WHERE d.split_rank!=w.split_rank""").fetchone()[0]
|
| 331 |
+
# Only the exact, locally created scratch database is removed; all exports/parts remain.
|
| 332 |
+
scratch.unlink()
|
| 333 |
+
log(f"Bucket {bucket}: {unique:,} unique sentences in {time.monotonic() - start:.1f}s")
|
| 334 |
+
return {"bucket": bucket, "unique_sentences": unique, "cross_split_occurrences_removed": removed,
|
| 335 |
+
"splits": {name: {**s, "primary_sources": dict(s["primary_sources"])} for name, s in split_stats.items()}}
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def concatenate(job):
|
| 339 |
+
destination, sources = job
|
| 340 |
+
with destination.open("wb") as target:
|
| 341 |
+
for source in sources:
|
| 342 |
+
with source.open("rb") as stream:
|
| 343 |
+
shutil.copyfileobj(stream, target, length=4 * 1024 * 1024)
|
| 344 |
+
return destination.name
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def run(config_path, parts, output, *, workers=4, buckets=64, cache_mb=128, work=None):
|
| 348 |
+
if type(workers) is not int or not 1 <= workers <= 32 or buckets not in {1, 4, 16, 64, 256} or not 16 <= cache_mb <= 2048:
|
| 349 |
+
raise ValueError("workers: 1..32; buckets: 1/4/16/64/256; cache-mb: 16..2048")
|
| 350 |
+
config_path, output = Path(config_path).resolve(), Path(output).resolve()
|
| 351 |
+
parts = [Path(p).resolve() for p in parts]
|
| 352 |
+
work = Path(work).resolve() if work else output.with_name(output.name + "-work")
|
| 353 |
+
# Refuse overlapping paths, including accidentally pointing at a completed worker.
|
| 354 |
+
for left, right in [(output, work), *((path, target) for path in parts for target in (output, work))]:
|
| 355 |
+
if left.is_relative_to(right) or right.is_relative_to(left):
|
| 356 |
+
raise ValueError("Inputs, output and work directories must not overlap.")
|
| 357 |
+
for path in (output, work):
|
| 358 |
+
if path.exists() and (not path.is_dir() or any(path.iterdir())):
|
| 359 |
+
raise FileExistsError(f"Use a new, empty output/work directory: {path}")
|
| 360 |
+
started = time.monotonic()
|
| 361 |
+
log("Validate completed worker artifacts (read only)")
|
| 362 |
+
plan, parts = validate_parts(config_path, parts)
|
| 363 |
+
config, _, policies, calibration_ids, policy_hashes, code_hashes, signature = plan
|
| 364 |
+
implementation_sha = text_sha(Path(__file__))
|
| 365 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 366 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 367 |
+
stage_times = {}
|
| 368 |
+
start = time.monotonic()
|
| 369 |
+
metadata = make_metadata(output, work, parts, config, policies, calibration_ids, cache_mb)
|
| 370 |
+
stage_times["metadata_seconds"] = time.monotonic() - start
|
| 371 |
+
indices = [m["partition"]["index"] for _, m in parts]
|
| 372 |
+
start = time.monotonic()
|
| 373 |
+
log(f"Repartition existing sentences: {workers} processes, {buckets} buckets")
|
| 374 |
+
part_results = parallel(repartition, [(p, work, m["partition"]["index"], buckets, cache_mb) for p, m in parts], workers, "repartition")
|
| 375 |
+
stage_times["repartition_seconds"] = time.monotonic() - start
|
| 376 |
+
start = time.monotonic()
|
| 377 |
+
bucket_results = parallel(export_bucket, [(b, work, output / "index.sqlite", indices,
|
| 378 |
+
config["build"]["quality_mode"], cache_mb) for b in range(buckets)], workers, "dedup/export")
|
| 379 |
+
stage_times["dedup_export_seconds"] = time.monotonic() - start
|
| 380 |
+
start = time.monotonic()
|
| 381 |
+
files = [f"{name}.{suffix}" for name in SPLITS for suffix in ("txt", "jsonl")] + ["provenance.jsonl"]
|
| 382 |
+
jobs = [(output / name, [work / f"export-{b:03d}" / name for b in range(buckets)]) for name in files]
|
| 383 |
+
jobs.extend((output / f"{name}.jsonl", [work / f"part-{i:03d}" / f"{name}.jsonl" for i in indices]) for name in AUDITS)
|
| 384 |
+
parallel(concatenate, jobs, min(workers, len(jobs)), "assemble")
|
| 385 |
+
stage_times["assemble_seconds"] = time.monotonic() - start
|
| 386 |
+
totals = {name: Counter() for name in ("counts", "rule_reasons", "fragment_flags", "effective_blocks")}
|
| 387 |
+
for result in sorted(part_results, key=lambda r: r["index"]):
|
| 388 |
+
for name in totals:
|
| 389 |
+
totals[name].update(result["metrics"][name])
|
| 390 |
+
counts = totals["counts"]
|
| 391 |
+
counts["document_origins"] = metadata["origin_count"]
|
| 392 |
+
counts["raw_characters"] = sum(json.loads((p / "part-stats.json").read_text(encoding="utf-8"))["raw_characters"] for p, _ in parts)
|
| 393 |
+
split_stats = {name: {"sentences": 0, "characters": 0, "primary_sources": Counter()} for name in SPLITS}
|
| 394 |
+
for result in bucket_results:
|
| 395 |
+
for name, values in result["splits"].items():
|
| 396 |
+
for key in ("sentences", "characters"):
|
| 397 |
+
split_stats[name][key] += values[key]
|
| 398 |
+
split_stats[name]["primary_sources"].update(values["primary_sources"])
|
| 399 |
+
unique = sum(r["unique_sentences"] for r in bucket_results)
|
| 400 |
+
characters = sum(s["characters"] for s in split_stats.values())
|
| 401 |
+
if sum(r["sentences"] for r in part_results) != counts["sentence_occurrences"] or sum(s["sentences"] for s in split_stats.values()) != unique:
|
| 402 |
+
raise ValueError("Repartition/export counts disagree; output is incomplete.")
|
| 403 |
+
stats = {
|
| 404 |
+
**dict(counts), "duplicate_documents": counts["document_origins"] - counts["unique_documents"],
|
| 405 |
+
"unique_sentences": unique, "duplicate_sentence_occurrences": counts["sentence_occurrences"] - unique,
|
| 406 |
+
"cross_split_occurrences_removed": sum(r["cross_split_occurrences_removed"] for r in bucket_results),
|
| 407 |
+
"final_characters": characters,
|
| 408 |
+
"splits": {name: {**s, "primary_sources": dict(s["primary_sources"])} for name, s in split_stats.items()},
|
| 409 |
+
"rule_reasons": dict(totals["rule_reasons"]),
|
| 410 |
+
"block_count_note": "keep/drop/review_blocks count rule-stage decisions before annotations.",
|
| 411 |
+
"effective_block_actions": dict(totals["effective_blocks"]), "fragment_flags": dict(totals["fragment_flags"]),
|
| 412 |
+
"forced_train_groups": metadata["forced_train_groups"], "annotation_records": metadata["annotation_count"],
|
| 413 |
+
"matched_annotations": metadata["matched_annotations"], "unmatched_annotations": metadata["unmatched_annotations"],
|
| 414 |
+
"token_estimate_scenarios": {f"{n}_characters_per_token": math.ceil(characters / n) for n in (1, 2, 3)},
|
| 415 |
+
"token_estimate_note": "Heuristic scenarios, not measured SentencePiece counts.",
|
| 416 |
+
}
|
| 417 |
+
dump_json(output / "stats.json", stats)
|
| 418 |
+
if load_plan(config_path)[-1] != signature or text_sha(Path(__file__)) != implementation_sha:
|
| 419 |
+
raise ValueError("Code/config/policy changed during merge; output is incomplete.")
|
| 420 |
+
dump_json(output / "manifest.json", {
|
| 421 |
+
"status": "complete", "stage": "merged_corpus_staging", "ready_for_lm_training": False,
|
| 422 |
+
"quality_mode": config["build"]["quality_mode"], "config": config, "config_sha256": file_sha(config_path),
|
| 423 |
+
"pipeline_signature": signature, "python_version": sys.version,
|
| 424 |
+
"input_sha256": {key: value for _, m in parts for key, value in m["input_sha256"].items()},
|
| 425 |
+
"selected_documents": {key: value for _, m in parts for key, value in m["selected_documents"].items()},
|
| 426 |
+
"policy_sha256": policy_hashes, "code_sha256": code_hashes,
|
| 427 |
+
"fingerprint_normalization": "Code and policy: UTF-8 text with LF line endings, no BOM; input/artifact hashes: exact bytes.",
|
| 428 |
+
"merge_code_sha256": {display_path(Path(__file__)): implementation_sha},
|
| 429 |
+
"part_manifest_sha256": {display_path(p / "manifest.json"): file_sha(p / "manifest.json") for p, _ in parts},
|
| 430 |
+
"grouping": "transitive groups of identical NFC documents, source IDs and canonical URLs",
|
| 431 |
+
"sentence_dedup": "exact NFC text; calibration text forced to train, otherwise test > validation > train",
|
| 432 |
+
"near_duplicate_detection": False, "span_offsets": "Unicode code points within cleaned blocks",
|
| 433 |
+
"calibration_policy": "known calibration documents and their groups and sentences are forced into train",
|
| 434 |
+
"annotation_policy": "Only approved snapshot-matched local labels apply; model replies alone are advisory.",
|
| 435 |
+
"index_format": "document-review-index-v1; origins, contents, annotations; no units/winners tables",
|
| 436 |
+
"merge_backend": "parallel SQLite hash buckets via Parquet; global in-memory document union-find",
|
| 437 |
+
"workers": workers, "buckets": buckets, "cache_mb_per_connection": cache_mb,
|
| 438 |
+
"work_directory": display_path(work),
|
| 439 |
+
})
|
| 440 |
+
stage_times["total_seconds"] = time.monotonic() - started
|
| 441 |
+
dump_json(output / "merge-timing.json", stage_times)
|
| 442 |
+
log(f"Complete: {unique:,} sentences; {stage_times['total_seconds']:.1f}s; corpus: {output}")
|
| 443 |
+
return stats
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def main():
|
| 447 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 448 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/corpus-parallel.toml")
|
| 449 |
+
parser.add_argument("--parts-dir", type=Path, default=ROOT / "outputs/corpus-parallel-v1-work/parts")
|
| 450 |
+
parser.add_argument("--output", type=Path, default=ROOT / "outputs/corpus-fast-v1")
|
| 451 |
+
parser.add_argument("--work", type=Path)
|
| 452 |
+
parser.add_argument("--workers", type=int, default=min(4, os.cpu_count() or 1))
|
| 453 |
+
parser.add_argument("--buckets", type=int, default=64, choices=(1, 4, 16, 64, 256))
|
| 454 |
+
parser.add_argument("--cache-mb", type=int, default=128)
|
| 455 |
+
args = parser.parse_args()
|
| 456 |
+
parts = sorted(p.parent for p in args.parts_dir.resolve().glob("*/manifest.json"))
|
| 457 |
+
if not parts:
|
| 458 |
+
parser.error("No completed worker manifests under --parts-dir")
|
| 459 |
+
run(args.config, parts, args.output, workers=args.workers, buckets=args.buckets, cache_mb=args.cache_mb, work=args.work)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
main()
|
source/src/vimeml/data/preprocess_part.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preprocess assigned source files; final deduplication and splits happen at merge."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import unicodedata
|
| 7 |
+
from collections import Counter
|
| 8 |
+
from contextlib import ExitStack, closing
|
| 9 |
+
from itertools import islice
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 13 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 14 |
+
|
| 15 |
+
from vimeml.data.corpus_parts import (AUDITS, PART_SCHEMA_VERSION, load_plan, parse_part,
|
| 16 |
+
create_database, process_content, aggregate_metrics)
|
| 17 |
+
from vimeml.data.build import sha, file_sha, display_path, dump_json
|
| 18 |
+
from vimeml.data.readers import iter_fineweb, iter_tatoeba
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run(config_path, part, output=None, list_only=False):
|
| 22 |
+
index, total = parse_part(part)
|
| 23 |
+
config, inventory, policies, _, policy_hashes, code_hashes, signature = load_plan(config_path)
|
| 24 |
+
selected = [item for number, item in enumerate(inventory) if number % total == index]
|
| 25 |
+
if not selected:
|
| 26 |
+
raise ValueError("This part has no inputs; use fewer parts.")
|
| 27 |
+
if list_only:
|
| 28 |
+
print(json.dumps({"part": part, "files": [p for p, _, _ in selected]}, ensure_ascii=False, indent=2))
|
| 29 |
+
return
|
| 30 |
+
paths = [ROOT / p for p, _, _ in selected]
|
| 31 |
+
for path in paths:
|
| 32 |
+
if not path.is_file():
|
| 33 |
+
raise FileNotFoundError(f"Missing assigned input: {path}")
|
| 34 |
+
snapshots = {p: (p.stat().st_size, p.stat().st_mtime_ns) for p in paths}
|
| 35 |
+
settings = config["build"]
|
| 36 |
+
output = (ROOT / (output or f"{settings['output_dir']}-part-{index:03d}-of-{total:03d}")).resolve()
|
| 37 |
+
selected_documents = Counter({p: 0 for p, _, _ in selected})
|
| 38 |
+
raw_characters = 0
|
| 39 |
+
with ExitStack() as stack:
|
| 40 |
+
db, annotation_count = create_database(output, policies.get("annotations"))
|
| 41 |
+
stack.callback(db.close)
|
| 42 |
+
audits = {name: stack.enter_context((output / f"{name}.jsonl").open("w", encoding="utf-8", newline="\n")) for name in AUDITS}
|
| 43 |
+
for relative, source, limit in selected:
|
| 44 |
+
path = ROOT / relative
|
| 45 |
+
reader = iter_fineweb(path, settings["batch_size"]) if source == "fineweb" else iter_tatoeba(path)
|
| 46 |
+
with closing(reader):
|
| 47 |
+
for document in islice(reader, limit) if limit else reader:
|
| 48 |
+
selected_documents[relative] += 1
|
| 49 |
+
raw_characters += len(document.text)
|
| 50 |
+
normalized = unicodedata.normalize("NFC", document.text.replace("\r\n", "\n").replace("\r", "\n")).lstrip("\ufeff")
|
| 51 |
+
doc_hash = sha(normalized)
|
| 52 |
+
first = db.execute("INSERT OR IGNORE INTO contents(doc_hash) VALUES (?)", (doc_hash,)).rowcount == 1
|
| 53 |
+
identity = {"source": source, "doc_id": document.doc_id, "source_id": document.source_id,
|
| 54 |
+
"source_file": document.source_file, "row_index": document.row_index,
|
| 55 |
+
"doc_hash": doc_hash, "metadata": document.metadata}
|
| 56 |
+
db.execute("INSERT INTO origins VALUES (?,?,?,?,?,?)", (doc_hash, document.doc_id, source,
|
| 57 |
+
document.source_file, document.row_index, json.dumps(identity, ensure_ascii=False, allow_nan=False)))
|
| 58 |
+
if first:
|
| 59 |
+
metrics = process_content(db, document, normalized, doc_hash, settings, audits)
|
| 60 |
+
db.execute("INSERT INTO document_metrics VALUES (?,?)", (doc_hash, json.dumps(metrics, ensure_ascii=False)))
|
| 61 |
+
count = sum(selected_documents.values())
|
| 62 |
+
if count % settings.get("commit_every", 5000) == 0:
|
| 63 |
+
db.commit()
|
| 64 |
+
if count % settings.get("progress_every", 5000) == 0:
|
| 65 |
+
print(f"Part {part}: read {count} document origins", flush=True)
|
| 66 |
+
db.commit()
|
| 67 |
+
unmatched_here = [row[0] for row in db.execute("SELECT a.id FROM annotations a JOIN contents c ON c.doc_hash=a.doc_hash WHERE a.matched=0")]
|
| 68 |
+
if config.get("review", {}).get("require_all_annotations", False) and unmatched_here:
|
| 69 |
+
raise ValueError(f"Annotations in assigned documents did not match: {unmatched_here}")
|
| 70 |
+
metrics = aggregate_metrics(db)
|
| 71 |
+
stats = {**metrics, "document_origins": sum(selected_documents.values()), "raw_characters": raw_characters,
|
| 72 |
+
"annotation_records": annotation_count,
|
| 73 |
+
"matched_annotations": db.execute("SELECT COUNT(*) FROM annotations WHERE matched=1").fetchone()[0]}
|
| 74 |
+
dump_json(output / "part-stats.json", stats)
|
| 75 |
+
for path, before in snapshots.items():
|
| 76 |
+
if (path.stat().st_size, path.stat().st_mtime_ns) != before:
|
| 77 |
+
raise ValueError(f"Input changed during processing: {path}")
|
| 78 |
+
if load_plan(config_path)[-1] != signature:
|
| 79 |
+
raise ValueError("Code or policy changed during processing; part is incomplete.")
|
| 80 |
+
print(f"Part {part}: hashing completed files", flush=True)
|
| 81 |
+
artifact_hashes = {name: file_sha(output / name) for name in ("index.sqlite", "part-stats.json", *(f"{name}.jsonl" for name in AUDITS))}
|
| 82 |
+
dump_json(output / "manifest.json", {
|
| 83 |
+
"status": "complete", "stage": "preprocessed_part", "part_schema_version": PART_SCHEMA_VERSION,
|
| 84 |
+
"partition": {"index": index, "count": total}, "pipeline_signature": signature,
|
| 85 |
+
"config": config, "config_sha256": file_sha(config_path), "python_version": sys.version,
|
| 86 |
+
"planned_inputs": [p for p, _, _ in inventory], "selected_documents": dict(selected_documents),
|
| 87 |
+
"input_sha256": {display_path(p): file_sha(p) for p in paths},
|
| 88 |
+
"policy_sha256": policy_hashes, "code_sha256": code_hashes, "artifact_sha256": artifact_hashes,
|
| 89 |
+
"fingerprint_normalization": "Code and policy: UTF-8 text with LF line endings, no BOM; input/artifact hashes: exact bytes.",
|
| 90 |
+
"ready_for_lm_training": False,
|
| 91 |
+
})
|
| 92 |
+
print(json.dumps({"part": part, "document_origins": stats["document_origins"], "output": str(output)}, ensure_ascii=False))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 97 |
+
parser.add_argument("--config", type=Path, default=ROOT / "configs/corpus-sharded.toml")
|
| 98 |
+
parser.add_argument("--part", required=True, help="Zero-based INDEX/COUNT; 0/2 and 1/2 for two machines.")
|
| 99 |
+
parser.add_argument("--output")
|
| 100 |
+
parser.add_argument("--list-only", action="store_true", help="Show assigned files; no raw data needed.")
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
run(args.config.resolve(), args.part, args.output, args.list_only)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
source/src/vimeml/data/readers.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming readers for local FineWeb2 and Tatoeba files."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from contextlib import closing
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from itertools import islice
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Iterator
|
| 10 |
+
|
| 11 |
+
import pyarrow.parquet as pq
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class Document:
|
| 19 |
+
source: str
|
| 20 |
+
source_id: str
|
| 21 |
+
text: str
|
| 22 |
+
source_file: str
|
| 23 |
+
row_index: int
|
| 24 |
+
metadata: dict
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def doc_id(self) -> str:
|
| 28 |
+
return f"{self.source}:{self.source_id}"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def relative_path(path: Path) -> str:
|
| 32 |
+
return path.resolve().relative_to(ROOT).as_posix()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def iter_fineweb(
|
| 36 |
+
path: Path, batch_size: int = 1024
|
| 37 |
+
) -> Iterator[Document]:
|
| 38 |
+
path = Path(path)
|
| 39 |
+
if batch_size < 1:
|
| 40 |
+
raise ValueError("batch_size 必须大于 0。")
|
| 41 |
+
|
| 42 |
+
with pq.ParquetFile(path) as parquet:
|
| 43 |
+
names = parquet.schema_arrow.names
|
| 44 |
+
if not {"text", "id"}.issubset(names):
|
| 45 |
+
raise ValueError(f"{path.name}: 缺少 text 或 id 字段。")
|
| 46 |
+
|
| 47 |
+
row_index = 0
|
| 48 |
+
for batch in parquet.iter_batches(batch_size=batch_size):
|
| 49 |
+
for row in batch.to_pylist():
|
| 50 |
+
source_id = row["id"]
|
| 51 |
+
text = row["text"]
|
| 52 |
+
if not isinstance(source_id, str) or not source_id:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"{path.name}, row {row_index}: id 无效。"
|
| 55 |
+
)
|
| 56 |
+
if not isinstance(text, str):
|
| 57 |
+
raise ValueError(
|
| 58 |
+
f"{path.name}, row {row_index}: text 无效。"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
yield Document(
|
| 62 |
+
source="fineweb",
|
| 63 |
+
source_id=source_id,
|
| 64 |
+
text=text,
|
| 65 |
+
source_file=relative_path(path),
|
| 66 |
+
row_index=row_index,
|
| 67 |
+
metadata={
|
| 68 |
+
key: value
|
| 69 |
+
for key, value in row.items()
|
| 70 |
+
if key not in {"text", "id"}
|
| 71 |
+
},
|
| 72 |
+
)
|
| 73 |
+
row_index += 1
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def iter_tatoeba(path: Path) -> Iterator[Document]:
|
| 77 |
+
path = Path(path)
|
| 78 |
+
|
| 79 |
+
with path.open(encoding="utf-8-sig") as stream:
|
| 80 |
+
for row_index, line in enumerate(stream):
|
| 81 |
+
# Preserve literal quotes in the sentence text.
|
| 82 |
+
parts = line.rstrip("\r\n").split("\t", 2)
|
| 83 |
+
if len(parts) != 3:
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"{path.name}, row {row_index}: TSV 格式错误。"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
source_id, language, text = parts
|
| 89 |
+
if not source_id:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
f"{path.name}, row {row_index}: id 为空。"
|
| 92 |
+
)
|
| 93 |
+
if language != "jpn":
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"{path.name}, row {row_index}: "
|
| 96 |
+
f"预期 jpn,实际为 {language!r}。"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
yield Document(
|
| 100 |
+
source="tatoeba",
|
| 101 |
+
source_id=source_id,
|
| 102 |
+
text=text,
|
| 103 |
+
source_file=relative_path(path),
|
| 104 |
+
row_index=row_index,
|
| 105 |
+
metadata={"language": language},
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
parser = argparse.ArgumentParser()
|
| 111 |
+
parser.add_argument("--limit", type=int, default=2)
|
| 112 |
+
args = parser.parse_args()
|
| 113 |
+
if args.limit < 1:
|
| 114 |
+
parser.error("--limit 必须大于 0")
|
| 115 |
+
|
| 116 |
+
fineweb_files = sorted(
|
| 117 |
+
(ROOT / "datasets/fineweb-2-edu-japanese").glob("*.parquet")
|
| 118 |
+
)
|
| 119 |
+
if not fineweb_files:
|
| 120 |
+
raise FileNotFoundError("没有找到 FineWeb2 parquet。")
|
| 121 |
+
|
| 122 |
+
inputs = [
|
| 123 |
+
(path, iter_fineweb) for path in fineweb_files
|
| 124 |
+
]
|
| 125 |
+
inputs.append((
|
| 126 |
+
ROOT / "datasets/Tatoeba/jpn_sentences.tsv",
|
| 127 |
+
iter_tatoeba,
|
| 128 |
+
))
|
| 129 |
+
|
| 130 |
+
preview_documents = 0
|
| 131 |
+
for path, reader in inputs:
|
| 132 |
+
with closing(reader(path)) as documents:
|
| 133 |
+
for document in islice(documents, args.limit):
|
| 134 |
+
print(json.dumps({
|
| 135 |
+
"doc_id": document.doc_id,
|
| 136 |
+
"source": document.source,
|
| 137 |
+
"source_file": document.source_file,
|
| 138 |
+
"row_index": document.row_index,
|
| 139 |
+
"characters": len(document.text),
|
| 140 |
+
"preview": document.text[:100],
|
| 141 |
+
}, ensure_ascii=False))
|
| 142 |
+
preview_documents += 1
|
| 143 |
+
|
| 144 |
+
print(json.dumps({
|
| 145 |
+
"input_files": len(inputs),
|
| 146 |
+
"preview_documents": preview_documents,
|
| 147 |
+
}, ensure_ascii=False))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|
source/src/vimeml/data/segment.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative sentence segmentation for Japanese paragraphs."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
PAIRS = {
|
| 7 |
+
"「": "」",
|
| 8 |
+
"『": "』",
|
| 9 |
+
"(": ")",
|
| 10 |
+
"(": ")",
|
| 11 |
+
"[": "]",
|
| 12 |
+
"【": "】",
|
| 13 |
+
"“": "”",
|
| 14 |
+
}
|
| 15 |
+
ENDINGS = set("。!?!?")
|
| 16 |
+
URL = re.compile(r"https?://[^\s「」『』()()\[\]【】“”。!?]+")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def split_sentences(text: str) -> list[dict]:
|
| 20 |
+
if "\n" in text or "\r" in text:
|
| 21 |
+
raise ValueError("请先处理换行,输入应为单个段落。")
|
| 22 |
+
|
| 23 |
+
results = []
|
| 24 |
+
stack = []
|
| 25 |
+
issues = set()
|
| 26 |
+
start = 0
|
| 27 |
+
url_ranges = [match.span() for match in URL.finditer(text)]
|
| 28 |
+
|
| 29 |
+
def emit(end, terminated):
|
| 30 |
+
nonlocal start
|
| 31 |
+
|
| 32 |
+
raw = text[start:end]
|
| 33 |
+
left = start + len(raw) - len(raw.lstrip())
|
| 34 |
+
right = end - (len(raw) - len(raw.rstrip()))
|
| 35 |
+
|
| 36 |
+
if left < right:
|
| 37 |
+
results.append({
|
| 38 |
+
"text": text[left:right],
|
| 39 |
+
"start": left,
|
| 40 |
+
"end": right,
|
| 41 |
+
"terminated": terminated,
|
| 42 |
+
"flags": sorted(issues),
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
start = end
|
| 46 |
+
issues.clear()
|
| 47 |
+
|
| 48 |
+
for index, char in enumerate(text):
|
| 49 |
+
# Question marks in URLs are not sentence boundaries.
|
| 50 |
+
if any(left <= index < right for left, right in url_ranges):
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
if char in PAIRS:
|
| 54 |
+
stack.append(PAIRS[char])
|
| 55 |
+
elif char in PAIRS.values():
|
| 56 |
+
if stack and stack[-1] == char:
|
| 57 |
+
stack.pop()
|
| 58 |
+
else:
|
| 59 |
+
issues.add("unmatched_closing_bracket")
|
| 60 |
+
|
| 61 |
+
if char in ENDINGS and not stack:
|
| 62 |
+
# Keep consecutive punctuation together, e.g. !?
|
| 63 |
+
if index + 1 < len(text) and text[index + 1] in ENDINGS:
|
| 64 |
+
continue
|
| 65 |
+
emit(index + 1, True)
|
| 66 |
+
|
| 67 |
+
if stack:
|
| 68 |
+
issues.add("unclosed_bracket")
|
| 69 |
+
|
| 70 |
+
tail = text[start:].strip().rstrip(
|
| 71 |
+
"".join(PAIRS.values())
|
| 72 |
+
).rstrip()
|
| 73 |
+
emit(len(text), bool(tail) and tail[-1] in ENDINGS)
|
| 74 |
+
|
| 75 |
+
return results
|
| 76 |
+
|
| 77 |
+
CONTINUATIONS = (
|
| 78 |
+
"のが", "のを", "ので", "のに", "なくて", "して", "ながら",
|
| 79 |
+
"という", "による", "であり", "ても",
|
| 80 |
+
"は", "が", "を", "に", "と", "や", "の", "し", "も",
|
| 81 |
+
)
|
| 82 |
+
LIST_ITEM = re.compile(r"^(?:[-*・●■◆◇]\s*|[0-90-9]+[.).、])")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def join_reason(left: str, right: str):
|
| 86 |
+
if LIST_ITEM.match(left) or LIST_ITEM.match(right):
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
tail = split_sentences(left)[-1]
|
| 90 |
+
if "unclosed_bracket" in tail["flags"]:
|
| 91 |
+
combined = split_sentences(left + right)
|
| 92 |
+
if not any(sentence["flags"] for sentence in combined):
|
| 93 |
+
return "unclosed_bracket"
|
| 94 |
+
return None
|
| 95 |
+
if tail["terminated"]:
|
| 96 |
+
return None
|
| 97 |
+
if left.endswith(("、", ",", ",")):
|
| 98 |
+
return "trailing_comma"
|
| 99 |
+
if left.endswith(CONTINUATIONS):
|
| 100 |
+
return "continuation_suffix"
|
| 101 |
+
if right.startswith(("を", "について", "によって", "として")):
|
| 102 |
+
return "continuation_prefix"
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def closes_brackets_ahead(left: str, blocks: list[dict], start: int, max_chars: int, boundary_decisions=None) -> bool:
|
| 108 |
+
"""Look ahead for a balanced close without crossing a structural boundary."""
|
| 109 |
+
combined = left
|
| 110 |
+
previous_index = blocks[start]["line_index"] - 1
|
| 111 |
+
for position in range(start, len(blocks)):
|
| 112 |
+
block = blocks[position]
|
| 113 |
+
if boundary_decisions and position > 0 and boundary_decisions.get((blocks[position - 1]["id"], block["id"])) == "separate":
|
| 114 |
+
return False
|
| 115 |
+
text = block["text"].strip()
|
| 116 |
+
index = block["line_index"]
|
| 117 |
+
if (
|
| 118 |
+
index != previous_index + 1 or block["action"] != "keep"
|
| 119 |
+
or not text or LIST_ITEM.match(text)
|
| 120 |
+
):
|
| 121 |
+
return False
|
| 122 |
+
previous_index = index
|
| 123 |
+
separator = " " if (
|
| 124 |
+
combined[-1].isascii() and text[0].isascii()
|
| 125 |
+
and combined[-1].isalnum() and text[0].isalnum()
|
| 126 |
+
) else ""
|
| 127 |
+
if len(combined) + len(separator) + len(text) > max_chars:
|
| 128 |
+
return False
|
| 129 |
+
combined += separator + text
|
| 130 |
+
sentences = split_sentences(combined)
|
| 131 |
+
if not any(sentence["flags"] for sentence in sentences):
|
| 132 |
+
return True
|
| 133 |
+
if any("unmatched_closing_bracket" in sentence["flags"] for sentence in sentences):
|
| 134 |
+
return False
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def restore_linebreaks(
|
| 139 |
+
blocks: list[dict], max_chars: int = 2048, boundary_decisions=None
|
| 140 |
+
) -> list[dict]:
|
| 141 |
+
boundary_decisions = boundary_decisions or {}
|
| 142 |
+
if any(value not in {"join", "separate"} for value in boundary_decisions.values()):
|
| 143 |
+
raise ValueError("Unknown approved boundary decision.")
|
| 144 |
+
paragraphs = []
|
| 145 |
+
current = None
|
| 146 |
+
previous_index = None
|
| 147 |
+
|
| 148 |
+
def flush():
|
| 149 |
+
nonlocal current
|
| 150 |
+
if current is not None:
|
| 151 |
+
paragraphs.append(current)
|
| 152 |
+
current = None
|
| 153 |
+
|
| 154 |
+
for position, block in enumerate(blocks):
|
| 155 |
+
index = block["line_index"]
|
| 156 |
+
if not isinstance(index, int) or index < 0:
|
| 157 |
+
raise ValueError("line_index 必须是非负整数。")
|
| 158 |
+
if previous_index is not None and index <= previous_index:
|
| 159 |
+
raise ValueError("文本块必须按原始行号严格递增。")
|
| 160 |
+
|
| 161 |
+
consecutive = (
|
| 162 |
+
previous_index is not None and index == previous_index + 1
|
| 163 |
+
)
|
| 164 |
+
previous_index = index
|
| 165 |
+
|
| 166 |
+
action = block["action"]
|
| 167 |
+
if action not in {"keep", "drop", "review"}:
|
| 168 |
+
raise ValueError("未知的 action。")
|
| 169 |
+
|
| 170 |
+
text = block["text"].strip()
|
| 171 |
+
if action != "keep" or not text:
|
| 172 |
+
flush()
|
| 173 |
+
continue
|
| 174 |
+
if not consecutive:
|
| 175 |
+
flush()
|
| 176 |
+
|
| 177 |
+
reason = join_reason(current["text"], text) if current else None
|
| 178 |
+
decision = boundary_decisions.get((current["parts"][-1]["block_id"], block["id"])) if current else None
|
| 179 |
+
if decision == "separate":
|
| 180 |
+
reason = None
|
| 181 |
+
elif decision == "join":
|
| 182 |
+
if LIST_ITEM.match(current["text"]) or LIST_ITEM.match(text):
|
| 183 |
+
raise ValueError("Approved join cannot cross a list/title boundary.")
|
| 184 |
+
reason = "approved_annotation"
|
| 185 |
+
if (
|
| 186 |
+
current and reason is None and decision != "separate"
|
| 187 |
+
and not LIST_ITEM.match(current["text"])
|
| 188 |
+
and not LIST_ITEM.match(text)
|
| 189 |
+
and "unclosed_bracket" in split_sentences(current["text"])[-1]["flags"]
|
| 190 |
+
and closes_brackets_ahead(current["text"], blocks, position, max_chars, boundary_decisions)
|
| 191 |
+
):
|
| 192 |
+
reason = "unclosed_bracket"
|
| 193 |
+
separator = ""
|
| 194 |
+
|
| 195 |
+
# Preserve the boundary between Latin words or numbers.
|
| 196 |
+
if reason:
|
| 197 |
+
last = current["text"][-1]
|
| 198 |
+
first = text[0]
|
| 199 |
+
if (
|
| 200 |
+
last.isascii() and first.isascii()
|
| 201 |
+
and last.isalnum() and first.isalnum()
|
| 202 |
+
):
|
| 203 |
+
separator = " "
|
| 204 |
+
|
| 205 |
+
if reason and (
|
| 206 |
+
len(current["text"]) + len(separator) + len(text) > max_chars
|
| 207 |
+
):
|
| 208 |
+
if decision == "join":
|
| 209 |
+
raise ValueError("Approved join exceeds max_chars; review the complete chain.")
|
| 210 |
+
current["flags"].append("join_length_limit")
|
| 211 |
+
reason = None
|
| 212 |
+
|
| 213 |
+
if reason:
|
| 214 |
+
offset = len(current["text"]) + len(separator)
|
| 215 |
+
current["joins"].append({
|
| 216 |
+
"left_block": current["parts"][-1]["block_id"],
|
| 217 |
+
"right_block": block["id"],
|
| 218 |
+
"reason": reason,
|
| 219 |
+
})
|
| 220 |
+
current["text"] += separator + text
|
| 221 |
+
current["parts"].append({
|
| 222 |
+
"block_id": block["id"],
|
| 223 |
+
"start": offset,
|
| 224 |
+
"end": offset + len(text),
|
| 225 |
+
})
|
| 226 |
+
else:
|
| 227 |
+
flush()
|
| 228 |
+
current = {
|
| 229 |
+
"text": text,
|
| 230 |
+
"parts": [{
|
| 231 |
+
"block_id": block["id"],
|
| 232 |
+
"start": 0,
|
| 233 |
+
"end": len(text),
|
| 234 |
+
}],
|
| 235 |
+
"joins": [],
|
| 236 |
+
"flags": [],
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
flush()
|
| 240 |
+
return paragraphs
|