"""ML stage rules: label parquet -> signal stores -> trainings -> evaluation -> gate. Stage targets (referenced by the top-level Snakefile `rule all`): STAGE_A_TARGETS — 12-point arch/param ladder + shuffled-label control, per-run test evaluation with the trap store, the gate verdict and the TP1 label-QC report. STAGE_B_TARGETS — only populated once the Stage-A winner is configured (config: stage_b_arch/stage_b_budget/stage_b_stride): windows ablation, robustness variants and the alignment-baseline report on the winner's test split. Run directories: ../data/ml_models/{tag}/{arch}_{budget}_{stride} with tag in { ladder, control, windows4, holdout, core_clade, bacillus_group }. The CLI run ids (params.run_id) carry the v2 suffixes (-shuf, -w4, -holdout, -core, -bacgrp); the gate takes the g11 runs (ladder + windows ablation + holdout) and ignores the restricted-clade diagnostics (class set differs by design). """ MODEL_LABELS = "hac" # probe labels come from the HAC arm (fast arm = baseline) N_CLASSES = len(config["species_list"]) MAIN_STORE = f"../data/ml_inputs/nomiss_{MODEL_LABELS}_data_store" W4_STORE = f"../data/ml_inputs/nomiss_{MODEL_LABELS}_data_store_w{config['max_windows_per_read']}" TRAP_STORE = f"../data/ml_inputs/trap_{MODEL_LABELS}_data_store" RUNS_DIR = "../data/ml_models" STAGE_B_ARCH = str(config.get("stage_b_arch", "") or "") STAGE_B_BUDGET = str(config.get("stage_b_budget", "") or "") STAGE_B_STRIDE = str(config.get("stage_b_stride", "") or "") STAGE_B_READY = bool(STAGE_B_ARCH and STAGE_B_BUDGET and STAGE_B_STRIDE) def _flag(key): """Truthy config key reader ('True'/'true' from --config become booleans).""" v = config.get(key) return v is True or str(v).lower() == "true" if (any(_flag(k) for k in ("windows_ablation", "holdout_runs", "core_clade", "bacillus_group")) and not STAGE_B_READY): raise ValueError( "Stage-B variants are enabled in config but stage_b_arch/stage_b_budget/stage_b_stride " "is not filled in (pick the winner from the Stage-A ladder reports first)" ) # --------------------------------------------------------------------------- # pod5 chunk wiring (wildcard-safe helpers; nomiss values are fixed) # --------------------------------------------------------------------------- def dataset_pod5_list(w): """Input function: pod5 chunk paths for the rule's dataset wildcard.""" return [ f"../data/raw_pod5/{w.dataset}/{get_run_name(w)}_{b}.pod5" for b in get_batch_range(w) ] NOMISS_RUN = RUN_NAMES["nomiss"] def nomiss_pod5_list(w=None): """Input function: nomiss pod5 chunk paths (dataset fixed, no wildcards).""" return [ f"../data/raw_pod5/nomiss/{NOMISS_RUN}_{b}.pod5" for b in batch_names("nomiss") ] def store_exclude_flags(w): """CLI fragment listing a store's excluded refs/genera from config (wildcards).""" excl = config["store_excludes"][w.dataset] parts = [] for ref in excl.get("refs", []): parts += ["--exclude-ref", str(ref)] for genus in excl.get("genera", []): parts += ["--exclude-genus", str(genus)] return " ".join(parts) def nomiss_store_excludes(w=None): """Same as store_exclude_flags for the (fixed) nomiss dataset.""" excl = config["store_excludes"]["nomiss"] parts = [] for ref in excl.get("refs", []): parts += ["--exclude-ref", str(ref)] for genus in excl.get("genera", []): parts += ["--exclude-genus", str(genus)] return " ".join(parts) def fmt_budget(raw: str) -> str: """Format a nominal budget (wildcard string) as '1.0M' for run ids.""" return f"{int(raw) / 1_000_000:.1f}M" def _csv(genera): return ",".join(str(g) for g in genera) # tag -> (stage, store, run-id suffix, extra flags, extra genera flag) _CG = _csv(config["core_clade_genera"]) _AG = _csv(config["bacillus_group_genera"]) TRAIN_TAG_SPECS = { "ladder": {"stage": "ladder_point", "store": MAIN_STORE, "suffix": "", "flags": "", "genera_flag": ""}, "control": {"stage": "control", "store": MAIN_STORE, "suffix": "-shuf", "flags": "", "genera_flag": ""}, "windows4": {"stage": "windows_ablation", "store": W4_STORE, "suffix": "-w4", "flags": "", "genera_flag": ""}, "holdout": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-holdout", "flags": "--holdout-runs", "genera_flag": ""}, "core_clade": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-core", "flags": "", "genera_flag": f"--genera {_CG}"}, "bacillus_group": {"stage": "robustness", "store": MAIN_STORE, "suffix": "-bacgrp", "flags": "", "genera_flag": f"--genera {_AG}"}, } def train_spec(w): return TRAIN_TAG_SPECS[w.tag] def train_run_id(w): spec = train_spec(w) if w.tag == "core_clade": n = len(config["core_clade_genera"]) elif w.tag == "bacillus_group": n = len(config["bacillus_group_genera"]) else: n = N_CLASSES return f"{w.arch}_{fmt_budget(w.budget)}_s{w.stride}_g{n}{spec['suffix']}" # --------------------------------------------------------------------------- # labels + signal stores # --------------------------------------------------------------------------- wildcard_constraints: dataset="nomiss|trap", tag=r"ladder|control|windows4|holdout|core_clade|bacillus_group", arch="cnn|linatt", budget=r"\d+", stride=r"4|8", model="hac|fast" def label_alignments(w): """Input function: alignment artifacts feeding the label parquet. CUDA branch: the per-batch CRAMs written by dorado's native aligner (consumed directly, no merge step -> no dataset-sized intermediate). ROCm fallback: the single merged BAM from the fastq->minimap2 chain. """ if GPU_STACK == "cuda": return [ f"../data/aligned_reads/{w.dataset}/{w.model}/{run_name(w.dataset)}_{b}.cram" for b in batch_names(w.dataset) ] return f"../data/aligned_reads/{w.dataset}_{w.model}_to_genome.bam" rule prepare_read_labels: input: alignments=label_alignments, reference="../data/reference_genomes/full_reference.fasta", output: "../data/ml_inputs/{dataset}_{model}_label_store.pq", threads: 4 conda: "../envs/bam2parquet.yaml" script: "../scripts/bam2annotation.py" rule build_data_store: input: pod5=dataset_pod5_list, labels="../data/ml_inputs/{dataset}_{model}_label_store.pq", output: directory("../data/ml_inputs/{dataset}_{model}_data_store"), params: wpr=1, excludes=store_exclude_flags, threads: 4 conda: config["torch_env"] shell: """ python -m custom_models store \ --out {output} \ --pod5 {input.pod5} \ --labels {input.labels} \ --max-windows-per-read {params.wpr} \ {params.excludes} """ rule build_store_windows_ablation: input: pod5=nomiss_pod5_list, labels=f"../data/ml_inputs/nomiss_{MODEL_LABELS}_label_store.pq", output: directory(W4_STORE), params: wpr=config["max_windows_per_read"], excludes=nomiss_store_excludes, threads: 4 conda: config["torch_env"] shell: """ python -m custom_models store \ --out {output} \ --pod5 {input.pod5} \ --labels {input.labels} \ --max-windows-per-read {params.wpr} \ {params.excludes} """ # --------------------------------------------------------------------------- # training (Stage-A ladder, control, Stage-B variants) # --------------------------------------------------------------------------- rule train_probe: input: store=lambda w: train_spec(w)["store"], output: # run-dir marker files (the CLI writes config/ckpt/history inside the # run dir); further files (report/test_split) are produced by test_probe config=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/config.json", ckpt=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/ckpt.pt", history=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/history.parquet", params: run_dir=lambda w: f"{RUNS_DIR}/{w.tag}/{w.arch}_{w.budget}_{w.stride}", run_id=train_run_id, stage=lambda w: train_spec(w)["stage"], flags=lambda w: train_spec(w)["flags"], genera_flag=lambda w: train_spec(w)["genera_flag"], threads: 8 resources: gpu=1 conda: config["torch_env"] shell: """ python -m custom_models train \ --arch {wildcards.arch} \ --budget {wildcards.budget} \ --stride {wildcards.stride} \ --budget-tol {config[budget_tolerance]} \ {params.flags} {params.genera_flag} \ --store {input.store} \ --out-dir {params.run_dir} \ --run-id {params.run_id} \ --stage {params.stage} \ --seed {config[seed]} """ # --------------------------------------------------------------------------- # evaluation: val-calibrated tau + test artifacts + trap eval (TP2) # --------------------------------------------------------------------------- rule test_probe: input: ckpt=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/ckpt.pt", trap_store=TRAP_STORE, output: report=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/report.json", test_split=f"{RUNS_DIR}/{{tag}}/{{arch}}_{{budget}}_{{stride}}/test_split.parquet", params: run_dir=lambda w: f"{RUNS_DIR}/{w.tag}/{w.arch}_{w.budget}_{w.stride}", threads: 8 resources: gpu=1 conda: config["torch_env"] shell: """ python -m custom_models test \ --run-dir {params.run_dir} \ --trap-store {input.trap_store} \ --n-boot {config[bootstrap_n]} """ # --------------------------------------------------------------------------- # gate (v2 §6): PASS/MARGINAL/MARGINAL-TRAP/FAIL over the g11 runs # --------------------------------------------------------------------------- LADDER_RUNS = expand( f"{RUNS_DIR}/ladder/{{arch}}_{{budget}}_{{stride}}", arch=[str(a) for a in config["ladder"]["arches"]], budget=[str(b) for b in config["ladder"]["budgets"]], stride=[str(s) for s in config["ladder"]["strides"]], ) GATE_RUN_DIRS = list(LADDER_RUNS) CONTROL_RUN_DIR = f"{RUNS_DIR}/control/{config['control']['arch']}_{config['control']['budget']}_{config['control']['stride']}" CONTROL_REPORT = f"{CONTROL_RUN_DIR}/report.json" if STAGE_B_READY: if _flag("windows_ablation"): _va = [STAGE_B_BUDGET] if config.get("windows_ablation_secondary_budget"): _va.append(str(config.get("windows_ablation_secondary_budget"))) GATE_RUN_DIRS += expand( f"{RUNS_DIR}/windows4/{{arch}}_{{budget}}_{{stride}}", arch=[STAGE_B_ARCH], budget=_va, stride=[STAGE_B_STRIDE], ) if _flag("holdout_runs"): GATE_RUN_DIRS.append(f"{RUNS_DIR}/holdout/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}") rule gate_verdict: input: reports=[f"{d}/report.json" for d in GATE_RUN_DIRS], control_report=CONTROL_REPORT, output: f"{RUNS_DIR}/gate_verdict.json", params: runs=" ".join(GATE_RUN_DIRS), # run dirs (config-static) control=CONTROL_RUN_DIR, chance_tol=config["gate_chance_tol"], threads: 1 conda: config["torch_env"] shell: """ python -m custom_models gate \ --runs {params.runs} \ --control {params.control} \ --chance-tol {params.chance_tol} """ # --------------------------------------------------------------------------- # TP1 label-side QC: trap captures counted from the labelled corpus # (trap reads are excluded from training at the store; their count here is # the read-side evidence the v2 doc requires to be reported). # --------------------------------------------------------------------------- rule trap_capture_qc: input: labels="../data/ml_inputs/nomiss_hac_label_store.pq", output: "../data/ml_inputs/nomiss_hac_trap_capture_qc.json", params: trap_genera=config["trap_genera"], threads: 1 conda: "../envs/bam2parquet.yaml" script: "../scripts/label_qc.py" # --------------------------------------------------------------------------- # Stage-A target set # --------------------------------------------------------------------------- STAGE_A_TARGETS = ( [f"{d}/report.json" for d in LADDER_RUNS] + [ CONTROL_REPORT, f"{RUNS_DIR}/gate_verdict.json", "../data/ml_inputs/nomiss_hac_trap_capture_qc.json", ] ) # --------------------------------------------------------------------------- # Stage-B target set (only after the Stage-A winner is configured) # --------------------------------------------------------------------------- STAGE_B_TARGETS = [] if STAGE_B_READY: _sb_run_dir = f"{RUNS_DIR}/ladder/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}" _sb_budgets = [STAGE_B_BUDGET] if config.get("windows_ablation_secondary_budget"): _sb_budgets.append(str(config.get("windows_ablation_secondary_budget"))) if _flag("windows_ablation"): STAGE_B_TARGETS += expand( f"{RUNS_DIR}/windows4/{{arch}}_{{budget}}_{{stride}}/report.json", arch=[STAGE_B_ARCH], budget=_sb_budgets, stride=[STAGE_B_STRIDE], ) if _flag("holdout_runs"): STAGE_B_TARGETS.append( f"{RUNS_DIR}/holdout/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json" ) if _flag("core_clade"): STAGE_B_TARGETS.append( f"{RUNS_DIR}/core_clade/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json" ) if _flag("bacillus_group"): STAGE_B_TARGETS.append( f"{RUNS_DIR}/bacillus_group/{STAGE_B_ARCH}_{STAGE_B_BUDGET}_{STAGE_B_STRIDE}/report.json" ) # alignment baseline (dorado-fast + minimap2 + LCA) on the identical test set rule baseline_eval: input: test_split=f"{_sb_run_dir}/test_split.parquet", truth_labels="../data/ml_inputs/nomiss_hac_label_store.pq", baseline_labels="../data/ml_inputs/nomiss_fast_label_store.pq", output: f"{_sb_run_dir}/baseline_report.json", params: run_id=f"{STAGE_B_ARCH}_{fmt_budget(STAGE_B_BUDGET)}_s{STAGE_B_STRIDE}_g{N_CLASSES}", threads: 1 conda: "../envs/bam2parquet.yaml" script: "../scripts/baseline_eval.py" STAGE_B_TARGETS.append(f"{_sb_run_dir}/baseline_report.json")