File size: 18,532 Bytes
4196369 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 |
"""
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:
# paths - same as training config
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"
# streaming settings - same as training
chunk_size: int = 8192
max_length: int = 32768
answer_reserve_tokens: int = 64
# evaluation
batch_size: int = 1 # use 1 for simplicity in baseline eval
max_samples: Optional[int] = 500 # same as training default
print_examples: int = 20
# precision
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, # keep original target for comparison
}
def collate_fn(batch):
# separate target_text from tensor fields
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:
# Include 1 overlap token for next-token prediction at chunk boundaries
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]
# Forward pass through Qwen
outputs = self.model(
input_ids=chunk_ids,
attention_mask=chunk_mask,
use_cache=False,
output_hidden_states=False,
return_dict=True,
)
logits = outputs.logits # [batch, seq, vocab]
# Compute loss and predictions for answer tokens
if chunk_labels is not None and (chunk_labels != -100).any():
# Shift for next-token prediction
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]
# Compute loss
chunk_loss = loss_fct_sum(valid_logits.float(), valid_targets)
total_loss_sum += chunk_loss.item()
total_loss_tokens += valid_targets.numel()
# Collect predictions
pred_ids = torch.argmax(valid_logits, dim=-1)
pred_tokens.extend(pred_ids.cpu().tolist())
target_tokens.extend(valid_targets.cpu().tolist())
# Compute metrics
if total_loss_tokens > 0:
avg_loss = total_loss_sum / total_loss_tokens
else:
avg_loss = 0.0
# Token accuracy
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
# EM accuracy (exact match of decoded strings)
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"]
# Process each sample in batch
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
# Print examples
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
# Update progress bar
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}%",
})
# Compute final metrics
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)
# Device setup
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
# TF32 settings
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)
# Load tokenizer
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
# Disable flash-attn checks
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}")
# Load model
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")
# Load dataset
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,
)
# Split dataset same as training (90% train, 10% eval)
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),
)
# Select which split to evaluate
if args.eval_split == "train":
dataset = train_dataset
split_name = "train"
elif args.eval_split == "eval":
dataset = eval_dataset
split_name = "eval"
else: # all
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,
)
# Create evaluator
evaluator = QwenChunkwiseEvaluator(model, tokenizer, config, device)
# Run evaluation
logger.info("Starting evaluation...")
results = evaluator.evaluate_dataset(dataloader, print_examples=config.print_examples)
# Print results
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)
# Save results
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()
|