| """ |
| Qwen3-4B baseline evaluation on BABILong QA1 (32k). |
| |
| This script evaluates the pretrained Qwen model WITHOUT any training, |
| using the same chunk-based streaming approach as the Titans training script. |
| |
| Purpose: Establish a baseline to compare with Titans memory-augmented models. |
| """ |
|
|
| import os |
| import json |
| import math |
| import argparse |
| import logging |
| from dataclasses import dataclass |
| from typing import Optional, Dict, List |
|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| from torch.utils.data import Dataset, DataLoader |
| from tqdm import tqdm |
|
|
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s - %(levelname)s - %(message)s" |
| ) |
| logger = logging.getLogger(__name__) |
|
|
|
|
| @dataclass |
| class EvalConfig: |
| |
| model_path: str = "/data/huangyifei/huggingface_cache/hub/models--Qwen--Qwen3-4B-Instruct-2507/snapshots/cdbee75f17c01a7cc42f958dc650907174af0554" |
| data_path: str = "/data/yty/BABILong/babilong-train-5k-samples/data/qa1/32k.json" |
| output_dir: str = "./outputs/qwen_baseline_eval" |
|
|
| |
| chunk_size: int = 8192 |
| max_length: int = 32768 |
| answer_reserve_tokens: int = 64 |
|
|
| |
| batch_size: int = 1 |
| max_samples: Optional[int] = 500 |
| print_examples: int = 20 |
|
|
| |
| bf16: bool = True |
| fp16: bool = False |
| use_tf32: bool = True |
|
|
| seed: int = 42 |
|
|
|
|
| class BABILongDataset(Dataset): |
| """Same dataset class as training script for consistency.""" |
|
|
| def __init__( |
| self, |
| data_path: str, |
| tokenizer, |
| max_length: int = 32768, |
| answer_reserve_tokens: int = 64, |
| max_samples: Optional[int] = None, |
| ): |
| self.tokenizer = tokenizer |
| self.max_length = max_length |
| self.answer_reserve_tokens = answer_reserve_tokens |
|
|
| logger.info(f"Loading dataset: {data_path}") |
| with open(data_path, "r") as f: |
| self.data = json.load(f) |
|
|
| if max_samples: |
| self.data = self.data[:max_samples] |
|
|
| logger.info(f"Dataset size: {len(self.data)}") |
|
|
| def __len__(self): |
| return len(self.data) |
|
|
| def __getitem__(self, idx): |
| item = self.data[idx] |
| text = f"{item['input']}\n\nQuestion: {item['question']}\nAnswer:" |
| target = item["target"] |
|
|
| pad_id = self.tokenizer.pad_token_id or 0 |
| reserve = int(self.answer_reserve_tokens) |
|
|
| prompt_ids = self.tokenizer( |
| text, |
| max_length=max(self.max_length - reserve, 1), |
| truncation=True, |
| add_special_tokens=True, |
| return_tensors="pt", |
| ).input_ids.squeeze(0) |
|
|
| answer_ids = self.tokenizer( |
| f" {target}", |
| add_special_tokens=False, |
| return_tensors="pt", |
| ).input_ids.squeeze(0) |
|
|
| available = max(self.max_length - prompt_ids.numel(), 0) |
| answer_ids = answer_ids[:available] |
|
|
| input_ids = torch.cat([prompt_ids, answer_ids], dim=0)[: self.max_length] |
|
|
| labels = torch.full_like(input_ids, fill_value=-100) |
| if answer_ids.numel() > 0: |
| start = prompt_ids.numel() |
| end = min(start + answer_ids.numel(), labels.numel()) |
| labels[start:end] = input_ids[start:end] |
|
|
| seq_len = input_ids.numel() |
| if seq_len < self.max_length: |
| pad_len = self.max_length - seq_len |
| input_ids = F.pad(input_ids, (0, pad_len), value=int(pad_id)) |
| labels = F.pad(labels, (0, pad_len), value=-100) |
| attention_mask = torch.cat( |
| [torch.ones(seq_len, dtype=torch.long), torch.zeros(pad_len, dtype=torch.long)], |
| dim=0, |
| ) |
| else: |
| attention_mask = torch.ones(self.max_length, dtype=torch.long) |
|
|
| return { |
| "input_ids": input_ids.to(dtype=torch.long), |
| "labels": labels.to(dtype=torch.long), |
| "attention_mask": attention_mask, |
| "target_text": target, |
| } |
|
|
|
|
| def collate_fn(batch): |
| |
| target_texts = [b.pop("target_text") for b in batch] |
| tensor_batch = {k: torch.stack([b[k] for b in batch], dim=0) for k in batch[0].keys()} |
| tensor_batch["target_texts"] = target_texts |
| return tensor_batch |
|
|
|
|
| class QwenChunkwiseEvaluator: |
| """ |
| Evaluates Qwen model using chunk-wise streaming (same as training). |
| |
| Key difference from training: NO memory module, just pure Qwen forward pass. |
| Each chunk is processed independently with KV cache reset between samples. |
| """ |
|
|
| def __init__(self, model, tokenizer, config: EvalConfig, device: torch.device): |
| self.model = model |
| self.tokenizer = tokenizer |
| self.config = config |
| self.device = device |
| self.hidden_size = model.config.hidden_size |
|
|
| def _split_into_chunks(self, seq_len: int, chunk_size: int): |
| """Split sequence into chunks, same as training.""" |
| chunks = [] |
| for start in range(0, seq_len, chunk_size): |
| end = min(start + chunk_size, seq_len) |
| chunks.append((start, end)) |
| return chunks |
|
|
| @torch.no_grad() |
| def evaluate_sample( |
| self, |
| input_ids: torch.Tensor, |
| attention_mask: torch.Tensor, |
| labels: torch.Tensor, |
| ) -> Dict: |
| """ |
| Evaluate a single sample using chunk-wise streaming. |
| |
| Process: |
| 1. Split input into chunks |
| 2. Process each chunk through Qwen (with overlap for next-token prediction) |
| 3. Collect predictions only for answer tokens (labels != -100) |
| 4. Compute loss, token accuracy, and EM accuracy |
| """ |
| batch_size, seq_len = input_ids.shape |
| chunk_size = self.config.chunk_size |
| chunks = self._split_into_chunks(seq_len, chunk_size) |
|
|
| loss_fct_sum = nn.CrossEntropyLoss(reduction="sum") |
| total_loss_sum = 0.0 |
| total_loss_tokens = 0 |
|
|
| pred_tokens: List[int] = [] |
| target_tokens: List[int] = [] |
|
|
| for start, end in chunks: |
| |
| proc_start = max(0, start - 1) |
| chunk_ids = input_ids[:, proc_start:end] |
| chunk_labels = labels[:, proc_start:end] |
| chunk_mask = attention_mask[:, proc_start:end] |
|
|
| |
| outputs = self.model( |
| input_ids=chunk_ids, |
| attention_mask=chunk_mask, |
| use_cache=False, |
| output_hidden_states=False, |
| return_dict=True, |
| ) |
| logits = outputs.logits |
|
|
| |
| if chunk_labels is not None and (chunk_labels != -100).any(): |
| |
| shift_logits = logits[:, :-1, :].contiguous() |
| shift_labels = chunk_labels[:, 1:].contiguous() |
|
|
| valid = shift_labels != -100 |
| if valid.any(): |
| valid_logits = shift_logits[valid] |
| valid_targets = shift_labels[valid] |
|
|
| |
| chunk_loss = loss_fct_sum(valid_logits.float(), valid_targets) |
| total_loss_sum += chunk_loss.item() |
| total_loss_tokens += valid_targets.numel() |
|
|
| |
| pred_ids = torch.argmax(valid_logits, dim=-1) |
| pred_tokens.extend(pred_ids.cpu().tolist()) |
| target_tokens.extend(valid_targets.cpu().tolist()) |
|
|
| |
| if total_loss_tokens > 0: |
| avg_loss = total_loss_sum / total_loss_tokens |
| else: |
| avg_loss = 0.0 |
|
|
| |
| if len(pred_tokens) > 0: |
| tok_correct = sum(p == t for p, t in zip(pred_tokens, target_tokens)) |
| tok_acc = tok_correct / len(pred_tokens) |
| else: |
| tok_acc = 0.0 |
|
|
| |
| if len(pred_tokens) > 0: |
| pred_text = self.tokenizer.decode(pred_tokens, skip_special_tokens=True).strip() |
| target_text = self.tokenizer.decode(target_tokens, skip_special_tokens=True).strip() |
| em_match = (pred_text == target_text) |
| else: |
| pred_text = "" |
| target_text = "" |
| em_match = False |
|
|
| return { |
| "loss": avg_loss, |
| "tok_acc": tok_acc, |
| "em_match": em_match, |
| "pred_text": pred_text, |
| "target_text": target_text, |
| "num_tokens": len(pred_tokens), |
| } |
|
|
| @torch.no_grad() |
| def evaluate_dataset(self, dataloader: DataLoader, print_examples: int = 10) -> Dict: |
| """Evaluate entire dataset.""" |
| self.model.eval() |
|
|
| total_loss = 0.0 |
| total_batches = 0 |
| total_tok_correct = 0 |
| total_tok_total = 0 |
| total_em_correct = 0 |
| total_em_total = 0 |
| printed = 0 |
|
|
| pbar = tqdm(dataloader, desc="Evaluating", dynamic_ncols=True) |
| for batch in pbar: |
| input_ids = batch["input_ids"].to(self.device) |
| attention_mask = batch["attention_mask"].to(self.device) |
| labels = batch["labels"].to(self.device) |
| target_texts = batch["target_texts"] |
|
|
| |
| for i in range(input_ids.shape[0]): |
| result = self.evaluate_sample( |
| input_ids[i:i+1], |
| attention_mask[i:i+1], |
| labels[i:i+1], |
| ) |
|
|
| if result["num_tokens"] > 0: |
| total_loss += result["loss"] |
| total_batches += 1 |
| total_tok_correct += int(result["tok_acc"] * result["num_tokens"]) |
| total_tok_total += result["num_tokens"] |
| total_em_correct += int(result["em_match"]) |
| total_em_total += 1 |
|
|
| |
| if printed < print_examples: |
| logger.info( |
| f"[EVAL SAMPLE {printed + 1}] " |
| f"pred={repr(result['pred_text'])} | " |
| f"label={repr(result['target_text'])} | " |
| f"match={result['em_match']}" |
| ) |
| printed += 1 |
|
|
| |
| if total_em_total > 0: |
| pbar.set_postfix({ |
| "em_acc": f"{total_em_correct / total_em_total * 100:.1f}%", |
| "tok_acc": f"{total_tok_correct / max(total_tok_total, 1) * 100:.1f}%", |
| }) |
|
|
| |
| avg_loss = total_loss / max(total_batches, 1) |
| tok_acc = total_tok_correct / max(total_tok_total, 1) |
| em_acc = total_em_correct / max(total_em_total, 1) |
|
|
| return { |
| "loss": avg_loss, |
| "tok_acc": tok_acc, |
| "em_acc": em_acc, |
| "total_samples": total_em_total, |
| "total_tokens": total_tok_total, |
| } |
|
|
|
|
| def main(): |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
| parser = argparse.ArgumentParser(description="Evaluate Qwen baseline on BABILong") |
| parser.add_argument("--model_path", type=str, default=None, help="Path to Qwen model") |
| parser.add_argument("--data_path", type=str, default=None, help="Path to BABILong data") |
| parser.add_argument("--output_dir", type=str, default=None, help="Output directory") |
| parser.add_argument("--max_samples", type=int, default=None, help="Max samples to evaluate") |
| parser.add_argument("--chunk_size", type=int, default=None, help="Chunk size for streaming") |
| parser.add_argument("--batch_size", type=int, default=1, help="Batch size") |
| parser.add_argument("--print_examples", type=int, default=20, help="Number of examples to print") |
| parser.add_argument("--eval_split", type=str, default="eval", choices=["train", "eval", "all"], |
| help="Which split to evaluate: train (90%), eval (10%), or all") |
| args = parser.parse_args() |
|
|
| config = EvalConfig() |
| if args.model_path: |
| config.model_path = args.model_path |
| if args.data_path: |
| config.data_path = args.data_path |
| if args.output_dir: |
| config.output_dir = args.output_dir |
| if args.max_samples is not None: |
| config.max_samples = args.max_samples |
| if args.chunk_size is not None: |
| config.chunk_size = args.chunk_size |
| if args.batch_size: |
| config.batch_size = args.batch_size |
| if args.print_examples is not None: |
| config.print_examples = args.print_examples |
|
|
| torch.manual_seed(config.seed) |
|
|
| |
| if torch.cuda.is_available(): |
| device = torch.device("cuda") |
| else: |
| device = torch.device("cpu") |
|
|
| |
| if torch.cuda.is_available() and config.use_tf32: |
| torch.backends.cuda.matmul.allow_tf32 = True |
| torch.backends.cudnn.allow_tf32 = True |
| try: |
| torch.set_float32_matmul_precision("high") |
| except Exception: |
| pass |
|
|
| logger.info("=" * 60) |
| logger.info("Qwen3-4B Baseline Evaluation (NO TRAINING)") |
| logger.info("=" * 60) |
| logger.info(f"model_path: {config.model_path}") |
| logger.info(f"data_path: {config.data_path}") |
| logger.info(f"output_dir: {config.output_dir}") |
| logger.info(f"max_samples: {config.max_samples}") |
| logger.info(f"max_length: {config.max_length}") |
| logger.info(f"chunk_size: {config.chunk_size}") |
| logger.info(f"eval_split: {args.eval_split}") |
| logger.info("=" * 60) |
|
|
| |
| logger.info("Loading tokenizer...") |
| tokenizer = AutoTokenizer.from_pretrained(config.model_path, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| |
| try: |
| import transformers |
| from transformers.utils import import_utils as _import_utils |
|
|
| def _disabled(*args, **kwargs): |
| return False |
|
|
| _import_utils.is_flash_attn_2_available = _disabled |
| if hasattr(transformers, "utils") and hasattr(transformers.utils, "is_flash_attn_2_available"): |
| transformers.utils.is_flash_attn_2_available = _disabled |
| _import_utils.is_torchao_available = _disabled |
| if hasattr(transformers, "utils") and hasattr(transformers.utils, "is_torchao_available"): |
| transformers.utils.is_torchao_available = _disabled |
| except Exception as e: |
| logger.warning(f"Disable checks failed (ignored): {e}") |
|
|
| |
| logger.info("Loading model...") |
| torch_dtype = torch.bfloat16 if config.bf16 else (torch.float16 if config.fp16 else torch.float32) |
| model = AutoModelForCausalLM.from_pretrained( |
| config.model_path, |
| torch_dtype=torch_dtype, |
| device_map=None, |
| trust_remote_code=True, |
| attn_implementation="sdpa", |
| low_cpu_mem_usage=True, |
| ) |
| model.to(device) |
| model.config.use_cache = False |
| model.eval() |
| logger.info(f"Model loaded: {model.config.hidden_size} hidden size, {model.config.num_hidden_layers} layers") |
|
|
| |
| logger.info("Loading dataset...") |
| full_dataset = BABILongDataset( |
| config.data_path, |
| tokenizer, |
| max_length=config.max_length, |
| answer_reserve_tokens=config.answer_reserve_tokens, |
| max_samples=config.max_samples, |
| ) |
|
|
| |
| train_size = int(0.9 * len(full_dataset)) |
| eval_size = len(full_dataset) - train_size |
| train_dataset, eval_dataset = torch.utils.data.random_split( |
| full_dataset, |
| [train_size, eval_size], |
| generator=torch.Generator().manual_seed(config.seed), |
| ) |
|
|
| |
| if args.eval_split == "train": |
| dataset = train_dataset |
| split_name = "train" |
| elif args.eval_split == "eval": |
| dataset = eval_dataset |
| split_name = "eval" |
| else: |
| dataset = full_dataset |
| split_name = "all" |
|
|
| logger.info(f"Evaluating on '{split_name}' split: {len(dataset)} samples") |
|
|
| dataloader = DataLoader( |
| dataset, |
| batch_size=config.batch_size, |
| shuffle=False, |
| collate_fn=collate_fn, |
| num_workers=0, |
| ) |
|
|
| |
| evaluator = QwenChunkwiseEvaluator(model, tokenizer, config, device) |
|
|
| |
| logger.info("Starting evaluation...") |
| results = evaluator.evaluate_dataset(dataloader, print_examples=config.print_examples) |
|
|
| |
| ppl = math.exp(min(20.0, results["loss"])) |
| logger.info("=" * 60) |
| logger.info("EVALUATION RESULTS (Qwen Baseline - NO TRAINING)") |
| logger.info("=" * 60) |
| logger.info(f"Split: {split_name}") |
| logger.info(f"Total samples: {results['total_samples']}") |
| logger.info(f"Total answer tokens: {results['total_tokens']}") |
| logger.info(f"Loss: {results['loss']:.4f}") |
| logger.info(f"Perplexity: {ppl:.3f}") |
| logger.info(f"Token Accuracy: {results['tok_acc'] * 100:.2f}%") |
| logger.info(f"EM Accuracy: {results['em_acc'] * 100:.2f}%") |
| logger.info("=" * 60) |
|
|
| |
| os.makedirs(config.output_dir, exist_ok=True) |
| results_path = os.path.join(config.output_dir, f"baseline_results_{split_name}.json") |
| with open(results_path, "w") as f: |
| json.dump({ |
| "split": split_name, |
| "total_samples": int(results["total_samples"]), |
| "total_tokens": int(results["total_tokens"]), |
| "loss": float(results["loss"]), |
| "perplexity": float(ppl), |
| "tok_acc_pct": float(results["tok_acc"] * 100), |
| "em_acc_pct": float(results["em_acc"] * 100), |
| "config": { |
| "model_path": config.model_path, |
| "data_path": config.data_path, |
| "max_samples": config.max_samples, |
| "max_length": config.max_length, |
| "chunk_size": config.chunk_size, |
| } |
| }, f, indent=2) |
| logger.info(f"Results saved to: {results_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|