| import argparse |
| import json |
| import logging |
| import math |
| import random |
| import shutil |
| from pathlib import Path |
| from typing import Any, Dict, List, Optional, Sequence, Tuple |
|
|
| import matplotlib |
|
|
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import numpy as np |
| import pandas as pd |
| import torch |
| from transformers import AutoModelForMaskedLM, AutoModelForSequenceClassification, AutoTokenizer |
|
|
|
|
| logging.basicConfig(level=logging.INFO) |
| logger = logging.getLogger(__name__) |
|
|
| BUCKET_TOKENS = {"low": "<sp0>", "mid": "<sp1>", "high": "<sp2>"} |
| BUCKET_ORDER = ["low", "mid", "high"] |
| DNA_BASES = ("A", "C", "G", "T") |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser( |
| description="Sample a trained masked discrete diffusion model and score generated DeepSTARR sequences." |
| ) |
| parser.add_argument("--diffusion_model", type=str, required=True) |
| parser.add_argument("--base_model_for_code", type=str, default=None, help="Optional base model dir to copy custom remote-code files from.") |
| parser.add_argument("--dataset_dir", type=str, required=True) |
| parser.add_argument("--predictor_model", type=str, default=None) |
| parser.add_argument("--output_dir", type=str, default="results/deepstarr_discrete_diffusion_eval") |
| parser.add_argument("--split", type=str, default="valid", choices=["train", "valid", "test"]) |
| parser.add_argument("--sequence_col", type=str, default="sequence") |
| parser.add_argument("--label_col", type=str, default="label") |
| parser.add_argument("--score_mode", type=str, default="sum", choices=["sum", "mean", "label_0", "label_1", "max"]) |
| parser.add_argument("--low_quantile", type=float, default=0.25) |
| parser.add_argument("--high_quantile", type=float, default=0.75) |
| parser.add_argument("--conditioned", action="store_true") |
| parser.add_argument("--num_per_bucket", type=int, default=128) |
| parser.add_argument("--sequence_length", type=int, default=246) |
| parser.add_argument("--num_diffusion_steps", type=int, default=64) |
| parser.add_argument("--batch_size", type=int, default=32) |
| parser.add_argument("--predictor_batch_size", type=int, default=64) |
| parser.add_argument("--score_batch_size", type=int, default=16) |
| parser.add_argument("--pll_chunk_size", type=int, default=64) |
| parser.add_argument("--max_length", type=int, default=256) |
| parser.add_argument("--temperature", type=float, default=1.0) |
| parser.add_argument("--top_k", type=int, default=0) |
| parser.add_argument("--seed", type=int, default=42) |
| parser.add_argument("--bf16", action="store_true") |
| parser.add_argument("--attn_implementation", type=str, default="sdpa", choices=["sdpa", "eager", "flash_attention_2"]) |
| return parser.parse_args() |
|
|
|
|
| def normalize_label(value: Any) -> List[float]: |
| if hasattr(value, "tolist"): |
| value = value.tolist() |
| if isinstance(value, str): |
| value = json.loads(value) |
| return [float(value[0]), float(value[1])] |
|
|
|
|
| def compute_activity_score(label: Sequence[float], mode: str) -> float: |
| if mode == "sum": |
| return float(label[0] + label[1]) |
| if mode == "mean": |
| return float((label[0] + label[1]) / 2.0) |
| if mode == "label_0": |
| return float(label[0]) |
| if mode == "label_1": |
| return float(label[1]) |
| if mode == "max": |
| return float(max(label[0], label[1])) |
| raise ValueError(f"Unsupported score_mode: {mode}") |
|
|
|
|
| def assign_bucket(score: float, low_threshold: float, high_threshold: float) -> str: |
| if score <= low_threshold: |
| return "low" |
| if score >= high_threshold: |
| return "high" |
| return "mid" |
|
|
|
|
| def load_bucketed_reference(args) -> pd.DataFrame: |
| train_df = pd.read_parquet(Path(args.dataset_dir) / "train.parquet") |
| split_df = pd.read_parquet(Path(args.dataset_dir) / f"{args.split}.parquet") |
| train_scores = train_df[args.label_col].map( |
| lambda value: compute_activity_score(normalize_label(value), args.score_mode) |
| ) |
| low_threshold = float(train_scores.quantile(args.low_quantile)) |
| high_threshold = float(train_scores.quantile(args.high_quantile)) |
|
|
| out = split_df.copy() |
| out["activity_score"] = out[args.label_col].map( |
| lambda value: compute_activity_score(normalize_label(value), args.score_mode) |
| ) |
| out["activity_bucket"] = out["activity_score"].map( |
| lambda score: assign_bucket(score, low_threshold, high_threshold) |
| ) |
| out["condition_token"] = out["activity_bucket"].map(BUCKET_TOKENS) |
| out[args.sequence_col] = out[args.sequence_col].astype(str).str.strip().str.upper() |
| return out |
|
|
|
|
| def resolve_dtype(args): |
| if args.bf16 and torch.cuda.is_available() and torch.cuda.is_bf16_supported(): |
| return torch.bfloat16 |
| return torch.float32 |
|
|
|
|
| def ensure_remote_code_files(model_dir: str, fallback_model_dir: Optional[str] = None): |
| target = Path(model_dir) |
| missing = [ |
| filename |
| for filename in ("configuration_generanno.py", "modeling_generanno.py", "tokenizer.py") |
| if not (target / filename).exists() |
| ] |
| if not missing: |
| return |
| if fallback_model_dir is None: |
| logger.warning( |
| "Model directory %s is missing remote-code files: %s", |
| model_dir, |
| ", ".join(missing), |
| ) |
| return |
| source = Path(fallback_model_dir) |
| for filename in missing: |
| src = source / filename |
| if src.exists(): |
| shutil.copy2(src, target / filename) |
| logger.info("Copied %s from %s to %s", filename, source, target) |
|
|
|
|
| def get_base_ids(tokenizer) -> Tuple[List[int], Dict[int, str]]: |
| base_ids = [] |
| id_to_base = {} |
| for base in DNA_BASES: |
| token_id = tokenizer.convert_tokens_to_ids(base) |
| if token_id is None or token_id == tokenizer.unk_token_id: |
| encoded = tokenizer(base, add_special_tokens=False)["input_ids"] |
| if len(encoded) == 1: |
| token_id = encoded[0] |
| if token_id is None or token_id == tokenizer.unk_token_id: |
| raise ValueError(f"Could not resolve tokenizer id for base {base!r}.") |
| base_ids.append(int(token_id)) |
| id_to_base[int(token_id)] = base |
| return base_ids, id_to_base |
|
|
|
|
| def encode_initial_batch( |
| tokenizer, |
| buckets: Sequence[str], |
| sequence_length: int, |
| conditioned: bool, |
| ) -> torch.Tensor: |
| mask_id = tokenizer.mask_token_id |
| if mask_id is None: |
| raise ValueError("Tokenizer must define a mask token for diffusion sampling.") |
|
|
| rows = [] |
| for bucket in buckets: |
| prefix_ids: List[int] = [] |
| if conditioned: |
| prefix_ids = tokenizer(BUCKET_TOKENS[bucket], add_special_tokens=False)["input_ids"] |
| body_ids = [mask_id] * sequence_length |
| token_ids = tokenizer.build_inputs_with_special_tokens(prefix_ids + body_ids) |
| rows.append(torch.tensor(token_ids, dtype=torch.long)) |
|
|
| max_len = max(row.numel() for row in rows) |
| pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id |
| padded = torch.full((len(rows), max_len), int(pad_id), dtype=torch.long) |
| for idx, row in enumerate(rows): |
| padded[idx, : row.numel()] = row |
| return padded |
|
|
|
|
| def sample_from_logits(logits: torch.Tensor, base_ids: Sequence[int], temperature: float, top_k: int) -> torch.Tensor: |
| restricted = logits[:, list(base_ids)] |
| if temperature <= 0: |
| return torch.tensor([base_ids[i] for i in restricted.argmax(dim=-1).tolist()], device=logits.device) |
| restricted = restricted / temperature |
| if top_k and 0 < top_k < restricted.size(-1): |
| values, indices = torch.topk(restricted, k=top_k, dim=-1) |
| probs = torch.softmax(values, dim=-1) |
| sampled = torch.multinomial(probs, num_samples=1).squeeze(-1) |
| return torch.tensor([base_ids[i] for i in indices[torch.arange(indices.size(0), device=indices.device), sampled].tolist()], device=logits.device) |
| probs = torch.softmax(restricted, dim=-1) |
| sampled = torch.multinomial(probs, num_samples=1).squeeze(-1) |
| return torch.tensor([base_ids[i] for i in sampled.tolist()], device=logits.device) |
|
|
|
|
| def iterative_unmask( |
| model, |
| tokenizer, |
| buckets: Sequence[str], |
| args, |
| base_ids: Sequence[int], |
| id_to_base: Dict[int, str], |
| device: str, |
| ) -> List[str]: |
| input_ids = encode_initial_batch(tokenizer, buckets, args.sequence_length, args.conditioned).to(device) |
| attention_mask = torch.ones_like(input_ids) |
| mask_id = tokenizer.mask_token_id |
|
|
| model.eval() |
| with torch.inference_mode(): |
| for step in range(args.num_diffusion_steps, 0, -1): |
| masked = input_ids == mask_id |
| if not masked.any(): |
| break |
| logits = model(input_ids=input_ids, attention_mask=attention_mask).logits |
| for row_idx in range(input_ids.size(0)): |
| positions = torch.nonzero(masked[row_idx], as_tuple=False).flatten() |
| if positions.numel() == 0: |
| continue |
| fill_count = max(1, math.ceil(positions.numel() / step)) |
| confidences = torch.softmax(logits[row_idx, positions][:, list(base_ids)], dim=-1).max(dim=-1).values |
| selected = positions[torch.topk(confidences, k=min(fill_count, positions.numel())).indices] |
| sampled = sample_from_logits( |
| logits[row_idx, selected], |
| base_ids=base_ids, |
| temperature=args.temperature, |
| top_k=args.top_k, |
| ) |
| input_ids[row_idx, selected] = sampled |
|
|
| sequences = [] |
| for row in input_ids.detach().cpu().tolist(): |
| chars = [id_to_base[token_id] for token_id in row if token_id in id_to_base] |
| sequences.append("".join(chars)[: args.sequence_length]) |
| return sequences |
|
|
|
|
| def load_diffusion_model(args, dtype): |
| fallback = getattr(args, "base_model_for_code", None) |
| ensure_remote_code_files(args.diffusion_model, fallback) |
| tokenizer = AutoTokenizer.from_pretrained(args.diffusion_model, trust_remote_code=True) |
| model = AutoModelForMaskedLM.from_pretrained( |
| args.diffusion_model, |
| trust_remote_code=True, |
| torch_dtype=dtype, |
| ) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token or tokenizer.mask_token |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| model.to(device) |
| return tokenizer, model, device |
|
|
|
|
| def load_predictor(args, dtype): |
| if not args.predictor_model: |
| return None, None, None |
| tokenizer = AutoTokenizer.from_pretrained(args.predictor_model, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token or tokenizer.mask_token |
| try: |
| model = AutoModelForSequenceClassification.from_pretrained( |
| args.predictor_model, |
| trust_remote_code=True, |
| attn_implementation=args.attn_implementation, |
| torch_dtype=dtype, |
| ) |
| except TypeError: |
| model = AutoModelForSequenceClassification.from_pretrained( |
| args.predictor_model, |
| trust_remote_code=True, |
| torch_dtype=dtype, |
| ) |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| model.to(device) |
| model.eval() |
| return tokenizer, model, device |
|
|
|
|
| def predict_scores(sequences: Sequence[str], tokenizer, model, device: str, max_length: int, batch_size: int) -> List[List[float]]: |
| outputs: List[List[float]] = [] |
| for start in range(0, len(sequences), batch_size): |
| batch = list(sequences[start : start + batch_size]) |
| enc = tokenizer( |
| batch, |
| add_special_tokens=True, |
| padding=True, |
| truncation=True, |
| max_length=max_length, |
| return_tensors="pt", |
| ) |
| enc.pop("token_type_ids", None) |
| enc = enc.to(device) |
| with torch.inference_mode(): |
| logits = model(**enc).logits |
| outputs.extend(logits.detach().float().cpu().tolist()) |
| return outputs |
|
|
|
|
| def build_generation_rows(args, tokenizer, model, base_ids, id_to_base, device) -> List[Dict[str, Any]]: |
| rows: List[Dict[str, Any]] = [] |
| bucket_schedule = [] |
| for bucket in BUCKET_ORDER: |
| bucket_schedule.extend([bucket] * args.num_per_bucket) |
|
|
| for start in range(0, len(bucket_schedule), args.batch_size): |
| batch_buckets = bucket_schedule[start : start + args.batch_size] |
| sequences = iterative_unmask( |
| model=model, |
| tokenizer=tokenizer, |
| buckets=batch_buckets, |
| args=args, |
| base_ids=base_ids, |
| id_to_base=id_to_base, |
| device=device, |
| ) |
| for bucket, sequence in zip(batch_buckets, sequences): |
| rows.append( |
| { |
| "source": "generated", |
| "activity_bucket": bucket, |
| "condition_token": BUCKET_TOKENS[bucket], |
| "generated_sequence": sequence, |
| "valid_dna": set(sequence).issubset(set(DNA_BASES)), |
| "generated_bp_length": len(sequence), |
| } |
| ) |
| return rows |
|
|
|
|
| def build_reference_rows(args, reference_df: pd.DataFrame) -> List[Dict[str, Any]]: |
| rows: List[Dict[str, Any]] = [] |
| rng = np.random.default_rng(args.seed) |
| for bucket in BUCKET_ORDER: |
| bucket_df = reference_df[reference_df["activity_bucket"] == bucket] |
| sample_n = min(args.num_per_bucket, len(bucket_df)) |
| if sample_n == 0: |
| continue |
| indices = rng.choice(bucket_df.index.to_numpy(), size=sample_n, replace=False) |
| for _, row in bucket_df.loc[indices].iterrows(): |
| sequence = str(row[args.sequence_col])[: args.sequence_length] |
| rows.append( |
| { |
| "source": "reference", |
| "activity_bucket": bucket, |
| "condition_token": BUCKET_TOKENS[bucket], |
| "generated_sequence": sequence, |
| "valid_dna": set(sequence).issubset(set(DNA_BASES)), |
| "generated_bp_length": len(sequence), |
| "source_id": str(row.get("id", "")), |
| "source_label": normalize_label(row[args.label_col]), |
| } |
| ) |
| return rows |
|
|
|
|
| def attach_scores(rows: List[Dict[str, Any]], predictor_tokenizer, predictor_model, predictor_device: str, args): |
| sequences = [row["generated_sequence"] for row in rows] |
| scores = predict_scores( |
| sequences, |
| tokenizer=predictor_tokenizer, |
| model=predictor_model, |
| device=predictor_device, |
| max_length=args.max_length, |
| batch_size=args.predictor_batch_size, |
| ) |
| for row, score in zip(rows, scores): |
| row["prediction"] = score |
| row["prediction_label_0"] = float(score[0]) |
| row["prediction_label_1"] = float(score[1]) |
| row["prediction_sum"] = float(sum(score)) |
| row["score_source"] = "predictor" |
|
|
|
|
| def encode_conditioned_sequence(tokenizer, bucket: str, sequence: str, conditioned: bool) -> List[int]: |
| prefix_ids: List[int] = [] |
| if conditioned: |
| prefix_ids = tokenizer(BUCKET_TOKENS[bucket], add_special_tokens=False)["input_ids"] |
| body_ids = tokenizer(sequence, add_special_tokens=False)["input_ids"] |
| return tokenizer.build_inputs_with_special_tokens(prefix_ids + body_ids) |
|
|
|
|
| def score_sequences_with_diffusion( |
| rows: List[Dict[str, Any]], |
| tokenizer, |
| model, |
| device: str, |
| conditioned: bool, |
| base_ids: Sequence[int], |
| max_length: int, |
| batch_size: int, |
| chunk_size: int, |
| ): |
| base_id_set = set(int(token_id) for token_id in base_ids) |
| mask_id = tokenizer.mask_token_id |
| pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id |
| model.eval() |
|
|
| for start in range(0, len(rows), batch_size): |
| batch_rows = rows[start : start + batch_size] |
| encoded_rows = [] |
| base_positions_rows = [] |
| for row in batch_rows: |
| token_ids = encode_conditioned_sequence( |
| tokenizer, |
| bucket=row["activity_bucket"], |
| sequence=row["generated_sequence"][:max_length], |
| conditioned=conditioned, |
| )[:max_length] |
| base_positions = [idx for idx, token_id in enumerate(token_ids) if int(token_id) in base_id_set] |
| encoded_rows.append(torch.tensor(token_ids, dtype=torch.long)) |
| base_positions_rows.append(base_positions) |
|
|
| max_len = max(item.numel() for item in encoded_rows) |
| input_ids = torch.full((len(encoded_rows), max_len), int(pad_id), dtype=torch.long) |
| attention_mask = torch.zeros_like(input_ids) |
| for row_idx, token_ids in enumerate(encoded_rows): |
| input_ids[row_idx, : token_ids.numel()] = token_ids |
| attention_mask[row_idx, : token_ids.numel()] = 1 |
|
|
| logprob_sums = [0.0 for _ in batch_rows] |
| token_counts = [0 for _ in batch_rows] |
|
|
| for chunk_start in range(0, max((len(pos) for pos in base_positions_rows), default=0), chunk_size): |
| masked_input = input_ids.clone() |
| selected_positions_rows = [] |
| for row_idx, positions in enumerate(base_positions_rows): |
| selected = positions[chunk_start : chunk_start + chunk_size] |
| selected_positions_rows.append(selected) |
| if selected: |
| masked_input[row_idx, selected] = mask_id |
| if not any(selected_positions_rows): |
| continue |
| with torch.inference_mode(): |
| logits = model( |
| input_ids=masked_input.to(device), |
| attention_mask=attention_mask.to(device), |
| ).logits.detach().float().cpu() |
| log_probs = torch.log_softmax(logits, dim=-1) |
| for row_idx, selected in enumerate(selected_positions_rows): |
| for pos in selected: |
| true_id = int(input_ids[row_idx, pos].item()) |
| logprob_sums[row_idx] += float(log_probs[row_idx, pos, true_id].item()) |
| token_counts[row_idx] += 1 |
|
|
| for row, total, count in zip(batch_rows, logprob_sums, token_counts): |
| score = total / count if count else float("nan") |
| row["prediction"] = [score] |
| row["prediction_sum"] = score |
| row["diffusion_pll"] = score |
| row["score_source"] = "diffusion_pll" |
|
|
|
|
| def summarise(rows: List[Dict[str, Any]]) -> Dict[str, Any]: |
| summary: Dict[str, Any] = {"num_rows": len(rows)} |
| for source in ["generated", "reference"]: |
| source_rows = [row for row in rows if row["source"] == source] |
| if not source_rows: |
| continue |
| summary[source] = { |
| "num_rows": len(source_rows), |
| "valid_dna_rate": sum(1 for row in source_rows if row["valid_dna"]) / len(source_rows), |
| "unique_rate": len({row["generated_sequence"] for row in source_rows}) / len(source_rows), |
| "mean_prediction_sum": sum(row["prediction_sum"] for row in source_rows) / len(source_rows), |
| } |
| if all("prediction_label_0" in row for row in source_rows): |
| summary[source]["mean_prediction_label_0"] = sum(row["prediction_label_0"] for row in source_rows) / len(source_rows) |
| summary[source]["mean_prediction_label_1"] = sum(row["prediction_label_1"] for row in source_rows) / len(source_rows) |
| by_bucket = {} |
| for bucket in BUCKET_ORDER: |
| bucket_rows = [row for row in source_rows if row["activity_bucket"] == bucket] |
| if not bucket_rows: |
| continue |
| by_bucket[bucket] = { |
| "num_rows": len(bucket_rows), |
| "valid_dna_rate": sum(1 for row in bucket_rows if row["valid_dna"]) / len(bucket_rows), |
| "unique_rate": len({row["generated_sequence"] for row in bucket_rows}) / len(bucket_rows), |
| "mean_prediction_sum": sum(row["prediction_sum"] for row in bucket_rows) / len(bucket_rows), |
| } |
| if all("prediction_label_0" in row for row in bucket_rows): |
| by_bucket[bucket]["mean_prediction_label_0"] = sum(row["prediction_label_0"] for row in bucket_rows) / len(bucket_rows) |
| by_bucket[bucket]["mean_prediction_label_1"] = sum(row["prediction_label_1"] for row in bucket_rows) / len(bucket_rows) |
| summary[source]["by_activity_bucket"] = by_bucket |
| return summary |
|
|
|
|
| def save_jsonl(path: Path, rows: Sequence[Dict[str, Any]]): |
| with open(path, "w", encoding="utf-8") as f: |
| for row in rows: |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") |
|
|
|
|
| def plot_violin(rows: List[Dict[str, Any]], output_path: Path): |
| fig, ax = plt.subplots(figsize=(9, 5), dpi=180) |
| positions = [] |
| data = [] |
| labels = [] |
| colors = [] |
| for bucket_idx, bucket in enumerate(BUCKET_ORDER): |
| for source_idx, source in enumerate(["reference", "generated"]): |
| values = [ |
| row["prediction_sum"] |
| for row in rows |
| if row["activity_bucket"] == bucket and row["source"] == source |
| ] |
| if not values: |
| continue |
| positions.append(bucket_idx * 3 + source_idx) |
| data.append(values) |
| labels.append(f"{bucket}\n{source}") |
| colors.append("#6f8fc9" if source == "reference" else "#d87c4a") |
|
|
| parts = ax.violinplot(data, positions=positions, showmeans=True, showextrema=False) |
| for body, color in zip(parts["bodies"], colors): |
| body.set_facecolor(color) |
| body.set_alpha(0.55) |
| body.set_edgecolor("#333333") |
| if "cmeans" in parts: |
| parts["cmeans"].set_color("#111111") |
| parts["cmeans"].set_linewidth(1.2) |
|
|
| ax.set_xticks(positions) |
| ax.set_xticklabels(labels) |
| ax.set_ylabel("Predictor score sum") |
| ax.set_title("Predictor score distribution by activity bucket") |
| ax.grid(axis="y", alpha=0.25) |
| fig.tight_layout() |
| fig.savefig(output_path) |
| plt.close(fig) |
|
|
|
|
| def plot_bucket_bar(summary: Dict[str, Any], output_path: Path): |
| generated = summary.get("generated", {}).get("by_activity_bucket", {}) |
| reference = summary.get("reference", {}).get("by_activity_bucket", {}) |
| x = np.arange(len(BUCKET_ORDER)) |
| width = 0.34 |
| gen_values = [generated.get(bucket, {}).get("mean_prediction_sum", np.nan) for bucket in BUCKET_ORDER] |
| ref_values = [reference.get(bucket, {}).get("mean_prediction_sum", np.nan) for bucket in BUCKET_ORDER] |
|
|
| fig, ax = plt.subplots(figsize=(7.5, 4.5), dpi=180) |
| ax.bar(x - width / 2, ref_values, width, label="reference", color="#6f8fc9") |
| ax.bar(x + width / 2, gen_values, width, label="generated", color="#d87c4a") |
| ax.set_xticks(x) |
| ax.set_xticklabels(BUCKET_ORDER) |
| ax.set_ylabel("Mean sequence score") |
| ax.set_title("Sequence score by activity bucket") |
| ax.grid(axis="y", alpha=0.25) |
| ax.legend(frameon=False) |
| fig.tight_layout() |
| fig.savefig(output_path) |
| plt.close(fig) |
|
|
|
|
| def main(): |
| args = parse_args() |
| random.seed(args.seed) |
| np.random.seed(args.seed) |
| torch.manual_seed(args.seed) |
|
|
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| dtype = resolve_dtype(args) |
| diffusion_tokenizer, diffusion_model, diffusion_device = load_diffusion_model(args, dtype) |
| base_ids, id_to_base = get_base_ids(diffusion_tokenizer) |
| generated_rows = build_generation_rows( |
| args, |
| tokenizer=diffusion_tokenizer, |
| model=diffusion_model, |
| base_ids=base_ids, |
| id_to_base=id_to_base, |
| device=diffusion_device, |
| ) |
|
|
| reference_df = load_bucketed_reference(args) |
| reference_rows = build_reference_rows(args, reference_df) |
| all_rows = generated_rows + reference_rows |
|
|
| predictor_tokenizer, predictor_model, predictor_device = load_predictor(args, dtype) |
| if predictor_model is not None: |
| attach_scores(all_rows, predictor_tokenizer, predictor_model, predictor_device, args) |
| score_source = "predictor" |
| else: |
| score_sequences_with_diffusion( |
| all_rows, |
| tokenizer=diffusion_tokenizer, |
| model=diffusion_model, |
| device=diffusion_device, |
| conditioned=args.conditioned, |
| base_ids=base_ids, |
| max_length=args.max_length, |
| batch_size=args.score_batch_size, |
| chunk_size=args.pll_chunk_size, |
| ) |
| score_source = "diffusion_pll" |
| summary = summarise(all_rows) |
| summary.update( |
| { |
| "diffusion_model": args.diffusion_model, |
| "predictor_model": args.predictor_model, |
| "score_source": score_source, |
| "dataset_dir": args.dataset_dir, |
| "split": args.split, |
| "conditioned": args.conditioned, |
| "sequence_length": args.sequence_length, |
| "num_diffusion_steps": args.num_diffusion_steps, |
| } |
| ) |
|
|
| save_jsonl(output_dir / "diffusion_scoring_details.jsonl", all_rows) |
| with open(output_dir / "diffusion_scoring_summary.json", "w", encoding="utf-8") as f: |
| json.dump(summary, f, indent=2, ensure_ascii=False) |
| plot_bucket_bar(summary, output_dir / "bucket_score_bar.png") |
| if predictor_model is not None: |
| plot_violin(all_rows, output_dir / "bucket_predictor_score_violin.png") |
| logger.info("Saved evaluation outputs to %s", output_dir) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|