LucaVirus icon indicating copy to clipboard operation
LucaVirus copied to clipboard

Keyword arguments {'text_pair': None, 'seq_type': 'gene'} not recognized.

Open yehuicheng2002 opened this issue 10 months ago • 2 comments

Hello, I encountered a problem while fine-tuning for sequence classification tasks. The keyword arguments {'text_pair': None, 'seq_type': 'gene'} are repeatedly not recognized. my tokenizers Version: 0.21.4,transformers Version: 4.51.3,python=3.10,On the README, it works fine and outputs correctly.This is the code in notebook: import torch import lucavirus from datasets import Dataset

from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer

model_id = "LucaGroup/LucaVirus-gene-step3.8M" model_path='/models/LucaGroup/LucaVirus-gene-step3.8M' model = AutoModelForSequenceClassification.from_pretrained( model_path, task_level="seq_level", task_type="multi_class", classifier_num_labels=2, trust_remote_code=True, force_download=True )

tokenizer = AutoTokenizer.from_pretrained( model_id, trust_remote_code=True, force_download=True ) def sliding_window(seq, window, stride): if len(seq) <= window: return [seq] return [seq[i:i+window] for i in range(0, len(seq)-window+1, stride)] train_raw[0]=[{'accession': 'OQ175183', 'seq': 'AGAACTGATAAGCACGACGCTTTTTGGATTGTAAAGAAGTGCACGAAGTCAGTTATGGAACACGAGCAGTCCATCTATAAACTGATTTCAGATTGTGGTGCAGTTGCAAAGCATGACTTTTTCACTTGGAAAGAGGGTAGGTCTGTCTATGGTAATGTTTGTCGTCAACCTATATGGAAGAGCATGCATGAAAAATTGTATATTTGACTATCTAGTAACTGAAGACCTAGCTGCTTTGATAGGGATACACAAAAAAAAAAAA', 'label': 0}, inputids, masks, labels, accs = [], [], [], [] for r in train_raw[0:1]: chunks = sliding_window(r["seq"], CONFIG["WINDOW_SIZE"], CONFIG["STRIDE"]) enc = tokenizer( chunks, padding="max_length", truncation=True, max_length=CONFIG["MODEL_MAX_LENGTH"] ) inputids.extend(enc["input_ids"]) masks.extend(enc["attention_mask"]) labels.extend([r.get("label", -1)] * len(chunks)) accs.extend([r["accession"]] * len(chunks))

dataset=Dataset.from_dict({ "input_ids": inputids, "attention_mask": masks, "labels": labels, "accession": accs, }) OUTCELL出现了数不清的 Keyword arguments {'text_pair': None, 'seq_type': 'gene'} not recognized. Keyword arguments {'text_pair': None, 'seq_type': 'gene'} not recognized.输出enc.keys()dict_keys(['input_ids', 'token_type_ids', 'attention_mask']),正常,训练时候,后面训练loss基本不动,

Image Image ``

yehuicheng2002 avatar Jan 20 '26 14:01 yehuicheng2002

完整的训练代码如下: import os import sys import json import logging

from pathlib import Path from datetime import datetime from copy import deepcopy

import numpy as np import pandas as pd import torch

from datasets import Dataset from sklearn.utils.class_weight import compute_class_weight from sklearn.metrics import ( accuracy_score, matthews_corrcoef, precision_recall_fscore_support, average_precision_score, roc_auc_score, confusion_matrix )

from transformers import ( AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments, DefaultDataCollator )

from accelerate import Accelerator import swanlab

CONFIG = { "FOLD_NAME": "fold_1",

"MODEL_NAME": "LucaVirus-gene-step3.8M",
"MODEL_ID": "LucaGroup/LucaVirus-gene-step3.8M",

# --- Token / Window ---
"MODEL_MAX_LENGTH": 2000,
"WINDOW_SIZE": 2000,
"STRIDE": 1000,

# --- Training ---
"NUM_TRAIN_EPOCHS": 1,
"PER_DEVICE_TRAIN_BATCH_SIZE": 4,
"PER_DEVICE_EVAL_BATCH_SIZE": 4,
"LEARNING_RATE": 1e-5,
"WEIGHT_DECAY": 0.01,
"WARMUP_RATIO": 0.1,
"LOGGING_STEPS": 1,
"EVAL_STEPS": 20,
"SAVE_STEPS": 100,
"SAVE_TOTAL_LIMIT": 1,
"LOAD_BEST_MODEL_AT_END": True,
"METRIC_FOR_BEST_MODEL": "eval_pr_auc",
"GREATER_IS_BETTER": True,

"GRADIENT_ACCUMULATION_STEPS": 1,
"BF16": True,

"SWANLAB_ENTITY": None,

}

accelerator = Accelerator()

1. 工具函数

def setup_logging(log_path: Path): log_path.parent.mkdir(parents=True, exist_ok=True) logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler(log_path), logging.StreamHandler(sys.stdout) ] )

def load_jsonl(path: Path): if not path.exists(): return [] with open(path) as f: return [json.loads(l) for l in f]

def sliding_window(seq, window, stride): if len(seq) <= window: return [seq] return [seq[i:i+window] for i in range(0, len(seq)-window+1, stride)]

def tokenize_dataset(raw, tokenizer): input_ids, masks, labels, accs = [], [], [], []

for r in raw:
    chunks = sliding_window(r["seq"], CONFIG["WINDOW_SIZE"], CONFIG["STRIDE"])
    enc = tokenizer(
        chunks,
        padding="max_length",
        truncation=True,
        max_length=CONFIG["MODEL_MAX_LENGTH"]
    )
    input_ids.extend(enc["input_ids"])
    masks.extend(enc["attention_mask"])
    labels.extend([r.get("label", -1)] * len(chunks))
    accs.extend([r["accession"]] * len(chunks))

return Dataset.from_dict({
    "input_ids": input_ids,
    "attention_mask": masks,
    "labels": labels,
    "accession": accs,
})

def compute_metrics(eval_pred): logits = eval_pred.predictions labels = eval_pred.label_ids preds = np.argmax(logits, axis=-1)

acc = accuracy_score(labels, preds)
prec, rec, f1, _ = precision_recall_fscore_support(
    labels, preds, average="binary", zero_division=0
)
mcc = matthews_corrcoef(labels, preds)
tn, fp, fn, tp = confusion_matrix(labels, preds, labels=[0,1]).ravel()

probs = torch.softmax(torch.tensor(logits), -1)[:,1].numpy()
try:
    pr_auc = average_precision_score(labels, probs)
    roc_auc = roc_auc_score(labels, probs)
except ValueError:
    pr_auc, roc_auc = float("nan"), float("nan")

return {
    "accuracy": acc,
    "precision": prec,
    "recall": rec,
    "f1": f1,
    "mcc": mcc,
    "pr_auc": pr_auc,
    "roc_auc": roc_auc,
    "tp": tp, "fp": fp, "tn": tn, "fn": fn
}

def aggregate_predictions(dataset, logits): d = {} for acc, logit in zip(dataset["accession"], logits): d.setdefault(acc, []).append(logit)

results = []
for acc, logs in d.items():
    probs = torch.softmax(torch.tensor(logs), -1)
    pos = probs[:,1]
    neg = probs[:,0]
    ll_pos = torch.log(pos + 1e-9).sum().item()
    ll_neg = torch.log(neg + 1e-9).sum().item()

    results.append({
        "accession": acc,
        "aggregated_prediction": int(ll_pos > ll_neg),
        "avg_positive_probability": float(pos.mean()),
    })
return results

def main(): fold = CONFIG["FOLD_NAME"]

out_root = CONFIG["OUTPUT_BASE_PATH"]
out_root.mkdir(parents=True, exist_ok=True)

setup_logging(out_root / f"run_{fold}_{datetime.now():%Y%m%d_%H%M%S}.log")
logging.info(f"Running ONLY {fold}")

tokenizer = AutoTokenizer.from_pretrained(
    CONFIG["MODEL_ID"],
    trust_remote_code=True,
    force_download=True
)

for family in CONFIG["VIRAL_FAMILIES"]:
    logging.info(f"===== {family} / {fold} =====")

    fam_dir = CONFIG["BASE_DATA_PATH"] / family / fold
    out_dir = out_root / family
    out_dir.mkdir(parents=True, exist_ok=True)

    train_raw = load_jsonl(fam_dir / "train.jsonl")
    dev_raw   = load_jsonl(fam_dir / "dev.jsonl")
    pred_raw  = load_jsonl(fam_dir / "pred.jsonl")
    future_raw = load_jsonl(CONFIG["BASE_DATA_PATH"] / family / "future.jsonl")

    if not train_raw:
        logging.warning("No train data, skip.")
        continue

    train_ds = tokenize_dataset(train_raw, tokenizer)
    print("🧪 Dataset columns:", train_ds.column_names)

    sample = train_ds[0]
    print("🧪 One sample keys:", sample.keys())
    dev_ds   = tokenize_dataset(dev_raw, tokenizer)
    pred_ds  = tokenize_dataset(pred_raw, tokenizer)

    labels = np.array(train_ds["labels"])
    weights = compute_class_weight("balanced", classes=np.unique(labels), y=labels)

    model = AutoModelForSequenceClassification.from_pretrained(
        CONFIG["BASE_MODEL_PATH"],
        task_level="seq_level",
        task_type="multi_class",
        classifier_num_labels=2,
        trust_remote_code=True
    )
    model.config.class_weights = weights.tolist()

    if accelerator.is_main_process:
        swanlab.init(
            project=f"{family}_fold1",
            name=f"{fold}",
            config=deepcopy(CONFIG)
        )

    args = TrainingArguments(
        output_dir=str(out_dir / fold),
        num_train_epochs=CONFIG["NUM_TRAIN_EPOCHS"],
        per_device_train_batch_size=CONFIG["PER_DEVICE_TRAIN_BATCH_SIZE"],
        per_device_eval_batch_size=CONFIG["PER_DEVICE_EVAL_BATCH_SIZE"],
        learning_rate=CONFIG["LEARNING_RATE"],
        weight_decay=CONFIG["WEIGHT_DECAY"],
        warmup_ratio=CONFIG["WARMUP_RATIO"],
        logging_steps=CONFIG["LOGGING_STEPS"],
        eval_steps=CONFIG["EVAL_STEPS"],
        eval_strategy="steps",
        save_steps=CONFIG["SAVE_STEPS"],
        save_total_limit=CONFIG["SAVE_TOTAL_LIMIT"],
        load_best_model_at_end=True,
        metric_for_best_model="eval_pr_auc",
        report_to="swanlab",
        bf16=CONFIG["BF16"],
        gradient_accumulation_steps=CONFIG["GRADIENT_ACCUMULATION_STEPS"],
        remove_unused_columns=True,
    )

    trainer = Trainer(
        model=model,
        args=args,
        train_dataset=train_ds,
        eval_dataset=dev_ds,
        compute_metrics=compute_metrics,
        data_collator=DefaultDataCollator(),
    )

    trainer.train()
    trainer.evaluate()

    preds = trainer.predict(pred_ds)
    agg = aggregate_predictions(pred_ds, preds.predictions)
    pd.DataFrame(agg).to_csv(out_dir / f"{fold}_pred_results.csv", index=False)

    if accelerator.is_main_process:
        swanlab.finish()

    logging.info(f"{family} done.\n")

if name == "main": main()

yehuicheng2002 avatar Jan 20 '26 15:01 yehuicheng2002

I have solve it

yehuicheng2002 avatar Jan 22 '26 10:01 yehuicheng2002